using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using TMPro;

/// <summary>
/// GAME 1303 Tier 4 — One button on a level-select screen. Shows locked/cleared state,
/// the best time, and loads the level when clicked.
///
/// SETUP
///  1. Make a UI Button prefab: Image (thumbnail), a TMP text for the name, another for
///     the best time, a padlock Image, and a checkmark/star Image. Add this script and
///     drag each part into its slot.
///  2. LevelSelectMenu spawns these — you normally don't place them by hand.
///  3. Clicking a locked level that has an unlock cost tries to pay it (LevelProgress
///     .TryPurchase). If it can't, OnRefused fires — show "Need 5 more".
/// </summary>
public class LevelSelectButton : MonoBehaviour
{
    [Header("Parts")]
    public Button button;
    public Image thumbnail;
    public TMP_Text nameText;
    public TMP_Text bestTimeText;
    public GameObject lockedIcon;
    public GameObject clearedIcon;
    public TMP_Text costText;

    [Header("Events")]
    public UnityEvent OnRefused;

    private LevelData level;
    private LevelSet set;

    public void Bind(LevelData data, LevelSet owningSet)
    {
        level = data;
        set = owningSet;

        if (nameText) nameText.text = data.displayName;
        if (thumbnail && data.thumbnail) thumbnail.sprite = data.thumbnail;

        Refresh();

        if (button != null)
        {
            button.onClick.RemoveAllListeners();
            button.onClick.AddListener(Click);
        }
    }

    public void Refresh()
    {
        if (level == null) return;
        bool unlocked = LevelProgress.IsUnlocked(level, set);
        bool cleared = LevelProgress.IsCleared(level.levelId);
        float best = LevelProgress.GetBestTime(level.levelId);

        if (lockedIcon) lockedIcon.SetActive(!unlocked);
        if (clearedIcon) clearedIcon.SetActive(cleared);
        if (bestTimeText) bestTimeText.text = best < 0f ? "" : LevelTimer.Format(best);
        if (costText)
        {
            bool showCost = !unlocked && level.unlockCost > 0;
            costText.gameObject.SetActive(showCost);
            if (showCost) costText.text = level.unlockCost.ToString();
        }
        // Locked-but-purchasable levels stay clickable so the player can buy them
        if (button) button.interactable = unlocked || level.unlockCost > 0;
    }

    void Click()
    {
        if (level == null) return;

        if (!LevelProgress.IsUnlocked(level, set))
        {
            if (LevelProgress.TryPurchase(level)) Refresh();
            else { AudioManager.Instance?.PlaySFX("door_locked"); OnRefused?.Invoke(); return; }
        }

        if (!string.IsNullOrEmpty(level.sceneName)) SceneLoader.Instance?.LoadScene(level.sceneName);
        else Debug.LogWarning($"LevelData '{level.levelId}' has no Scene Name.");
    }
}