using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// GAME 1303 Tier 8 — Drachma. MythoClash's experience currency.
///
/// Fozaan's rule, straight from the pitch: "Drachma cannot be taken from you, but you can
/// gain more as you fight more opponents." So this only ever goes up from fighting — but
/// it CAN be spent on unlocking levels, which is different from being taken away.
///
/// SETUP
///  1. One empty GameObject "Wallet" with this script. Persist Across Scenes ✓.
///  2. Wire EncounterManager.OnMonsterDefeated -> ExperienceWallet.Add.
///  3. Wire OnTotalChanged to a HUD counter.
///  4. Tier 4's LevelData/LevelProgress handles which levels are unlocked; point its
///     unlock cost at an ItemType called Drachma and keep them in sync, OR use this
///     wallet's CanAfford/Spend directly from your level-select buttons. Pick ONE — two
///     currencies that mean the same thing is a bug factory.
/// </summary>
public class ExperienceWallet : MonoBehaviour
{
    public static ExperienceWallet Instance { get; private set; }

    public bool persistAcrossScenes = true;
    public int startingAmount = 0;

    [Header("Events")]
    public UnityEvent<int> OnTotalChanged;
    public UnityEvent<int> OnEarned;      // amount earned this time
    public UnityEvent<int> OnSpent;

    public int Total { get; private set; }
    /// <summary>Everything ever earned — for a stats screen. Never goes down.</summary>
    public int LifetimeEarned { get; private set; }

    void Awake()
    {
        if (Instance != null && Instance != this) { Destroy(gameObject); return; }
        Instance = this;
        if (persistAcrossScenes) DontDestroyOnLoad(gameObject);
        Total = startingAmount;
    }

    void Start() => OnTotalChanged?.Invoke(Total);

    public void Add(int amount)
    {
        if (amount <= 0) return;
        Total += amount;
        LifetimeEarned += amount;
        OnEarned?.Invoke(amount);
        OnTotalChanged?.Invoke(Total);
        ChoiceFlagManager.Instance?.AddCount("drachma_earned", amount);
    }

    public bool CanAfford(int cost) => Total >= cost;

    public bool Spend(int cost)
    {
        if (!CanAfford(cost)) return false;
        Total -= cost;
        OnSpent?.Invoke(cost);
        OnTotalChanged?.Invoke(Total);
        return true;
    }

    public void SetTotal(int value)
    {
        Total = Mathf.Max(0, value);
        OnTotalChanged?.Invoke(Total);
    }
}