using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using TMPro;

/// <summary>
/// GAME 1303 Tier 4 — Builds a grid of level buttons from a LevelSet. Zap Attack's sector
/// map, MythoClash's pantheon select.
///
/// SETUP
///  1. Canvas -> Panel with a Grid Layout Group. Add this script to the panel.
///  2. Drag the LevelSelectButton prefab into Button Prefab, and the panel's transform
///     into Container (usually the same object).
///  3. Drag your LevelSets into the list. Set Current Set Index, or call ShowSet(i) from
///     tabs / arrow buttons.
///  4. Set Title Text and Progress Text if you want "Sector 1" and "6 / 10 cleared".
///  5. Buttons refresh every time the panel is enabled, so returning from a level updates
///     the locks immediately.
/// </summary>
public class LevelSelectMenu : MonoBehaviour
{
    public List<LevelSet> sets = new List<LevelSet>();
    public int currentSetIndex = 0;

    [Header("Building")]
    public LevelSelectButton buttonPrefab;
    public Transform container;

    [Header("Labels (optional)")]
    public TMP_Text titleText;
    public TMP_Text progressText;
    public string progressFormat = "{0} / {1} cleared";

    [Header("Events")]
    public UnityEvent<int> OnSetChanged;

    private readonly List<LevelSelectButton> spawned = new List<LevelSelectButton>();

    void OnEnable() => ShowSet(currentSetIndex);

    public void ShowSet(int index)
    {
        if (sets.Count == 0 || buttonPrefab == null) return;
        currentSetIndex = Mathf.Clamp(index, 0, sets.Count - 1);
        LevelSet set = sets[currentSetIndex];
        if (container == null) container = transform;

        // Clear old buttons
        foreach (var b in spawned) if (b != null) Destroy(b.gameObject);
        spawned.Clear();

        foreach (var level in set.levels)
        {
            if (level == null) continue;
            var btn = Instantiate(buttonPrefab, container);
            btn.Bind(level, set);
            spawned.Add(btn);
        }

        if (titleText) titleText.text = set.displayName;
        if (progressText) progressText.text = string.Format(progressFormat, set.ClearedCount(), set.levels.Count);
        OnSetChanged?.Invoke(currentSetIndex);
    }

    public void NextSet()     => ShowSet(currentSetIndex + 1);
    public void PreviousSet() => ShowSet(currentSetIndex - 1);

    /// <summary>Wire to a "Clear save data" button. Rebuilds the grid afterwards.</summary>
    public void ResetAllProgress()
    {
        LevelProgress.ResetAll();
        ShowSet(currentSetIndex);
    }
}