using UnityEngine;

[System.Serializable]
public class Bank : MonoBehaviour
{
    [Header("Currency")]
    public int gold;
    public int silver;
    public int copper;

    [Header("Starting Money")]
    public int startingGold = 50;
    public int startingSilver = 0;
    public int startingCopper = 0;

    void Start()
    {
        // Initialize with starting money if all currencies are 0
        if (gold == 0 && silver == 0 && copper == 0)
        {
            gold = startingGold;
            silver = startingSilver;
            copper = startingCopper;
        }
    }

    public int GetTotalCopperValue()
    {
        return gold * 100 + silver * 10 + copper;
    }

    public string GetCurrencyString()
    {
        string result = "";
        if (gold > 0) result += $"{gold}g ";
        if (silver > 0) result += $"{silver}s ";
        if (copper > 0) result += $"{copper}c";
        return result.Trim();
    }

    public bool CanAfford(int goldCost, int silverCost, int copperCost)
    {
        int totalCopperCost = goldCost * 100 + silverCost * 10 + copperCost;
        return GetTotalCopperValue() >= totalCopperCost;
    }

    public bool SpendMoney(int goldCost, int silverCost, int copperCost)
    {
        if (!CanAfford(goldCost, silverCost, copperCost))
        {
            Debug.LogWarning($"Cannot afford cost: {goldCost}g {silverCost}s {copperCost}c");
            return false;
        }

        int totalCopperCost = goldCost * 100 + silverCost * 10 + copperCost;
        int remainingCopper = GetTotalCopperValue() - totalCopperCost;

        // Convert back to gold, silver, copper
        gold = remainingCopper / 100;
        remainingCopper %= 100;
        silver = remainingCopper / 10;
        copper = remainingCopper % 10;

        return true;
    }

    public void AddMoney(int addGold, int addSilver, int addCopper)
    {
        gold += addGold;
        silver += addSilver;
        copper += addCopper;

        // Convert excess copper to silver, and excess silver to gold
        if (copper >= 10)
        {
            silver += copper / 10;
            copper %= 10;
        }

        if (silver >= 10)
        {
            gold += silver / 10;
            silver %= 10;
        }
    }
}