using UnityEngine;

[System.Serializable]
public abstract class Item : ScriptableObject
{
    [Header("Item Basic Info")]
    public string itemName;
    public string description;
    public Sprite icon;
    public GameObject model3D; // For 3D representation in-game
    public ItemType itemType;
    public ItemRarity rarity = ItemRarity.Common;

    [Header("Cost")]
    public int goldCost;
    public int silverCost;
    public int copperCost;

    [Header("Tags")]
    public string[] searchTags; // For search functionality

    public virtual bool CanAfford(Bank bank)
    {
        int totalCopperCost = goldCost * 100 + silverCost * 10 + copperCost;
        int totalCopperAvailable = bank.gold * 100 + bank.silver * 10 + bank.copper;
        return totalCopperAvailable >= totalCopperCost;
    }

    public virtual void Purchase(Bank bank)
    {
        if (!CanAfford(bank))
        {
            Debug.LogWarning($"Cannot afford {itemName}");
            return;
        }

        // Convert everything to copper for easier calculation
        int totalCopperCost = goldCost * 100 + silverCost * 10 + copperCost;
        int totalCopperAvailable = bank.gold * 100 + bank.silver * 10 + bank.copper;

        int remainingCopper = totalCopperAvailable - totalCopperCost;

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

        Debug.Log($"Purchased {itemName} for {goldCost}g {silverCost}s {copperCost}c");
    }

    public virtual string GetCostString()
    {
        string cost = "";
        if (goldCost > 0) cost += $"{goldCost}g ";
        if (silverCost > 0) cost += $"{silverCost}s ";
        if (copperCost > 0) cost += $"{copperCost}c";
        return cost.Trim();
    }

    public virtual bool MatchesSearch(string searchTerm)
    {
        if (string.IsNullOrEmpty(searchTerm)) return true;

        searchTerm = searchTerm.ToLower();

        // Check name
        if (itemName.ToLower().Contains(searchTerm)) return true;

        // Check description
        if (description.ToLower().Contains(searchTerm)) return true;

        // Check tags
        if (searchTags != null)
        {
            foreach (string tag in searchTags)
            {
                if (tag.ToLower().Contains(searchTerm)) return true;
            }
        }

        return false;
    }
}

[System.Serializable]
public enum ItemType
{
    Weapon,
    Armor,
    Miscellaneous,
    Consumable,
    Tool,
    Accessory
}

[System.Serializable]
public enum ItemRarity
{
    Common,
    Uncommon,
    Rare,
    Epic,
    Legendary
}
