using System.Collections.Generic;
using UnityEngine;

namespace GameSDK
{
    /// <summary>
    /// UI面板管理器，负责面板的显示/隐藏切换
    /// </summary>
    public class SDKUIManager : MonoBehaviour
    {
        public static SDKUIManager Instance { get; private set; }

        private Dictionary<string, BasePanel> panelDict = new Dictionary<string, BasePanel>();
        private Stack<BasePanel> panelStack = new Stack<BasePanel>();

        private void Awake()
        {
            if (Instance != null && Instance != this)
            {
                Destroy(gameObject);
                return;
            }
            Instance = this;
        }

        /// <summary>
        /// 显示指定类型的面板，并压入栈（当前面板会暂停）
        /// </summary>
        public void ShowPanel<T>() where T : BasePanel
        {
            string panelName = typeof(T).Name;
            if (panelDict.TryGetValue(panelName, out BasePanel panel))
            {
                // 暂停当前面板（不弹栈）
                if (panelStack.Count > 0)
                {
                    BasePanel topPanel = panelStack.Peek();
                    if (topPanel != panel) topPanel.OnPause();
                }
                // 显示新面板并压栈
                panel.OnEnter();
                panelStack.Push(panel);
            }
            else
            {
                Debug.LogError($"[SDK] 面板未注册: {panelName}");
            }
        }

        /// <summary>
        /// 关闭当前面板并返回上一个面板
        /// </summary>
        public void PopPanel()
        {
            if (panelStack.Count > 0)
            {
                BasePanel top = panelStack.Pop();
                top.OnExit();
            }

            if (panelStack.Count > 0)
            {
                BasePanel peek = panelStack.Peek();
                peek.OnResume();
            }
        }

        /// <summary>
        /// 注册面板
        /// </summary>
        public void RegisterPanel(string panelName, BasePanel panel)
        {
            if (!panelDict.ContainsKey(panelName))
            {
                panelDict.Add(panelName, panel);
                // 注册时直接隐藏面板（面板此时 inactive，CanvasGroup 可能还不存在）
                panel.gameObject.SetActive(false);
            }
        }

        /// <summary>
        /// 关闭所有面板并显示指定面板（清空栈后重新 Push）
        /// </summary>
        public void ShowOnlyPanel<T>() where T : BasePanel
        {
            // 清空栈并关闭所有面板
            while (panelStack.Count > 0)
            {
                BasePanel top = panelStack.Pop();
                top.OnExit();
            }
            ShowPanel<T>();
        }

        /// <summary>
        /// 关闭整个SDK UI
        /// </summary>
        public void CloseAll()
        {
            while (panelStack.Count > 0)
            {
                BasePanel top = panelStack.Pop();
                top.OnExit();
            }
        }
    }
}
