using UnityEngine;
using UnityEngine.Events;

namespace GameSDK
{
    /// <summary>
    /// SDK 主入口，单例模式
    /// </summary>
    public class SDKManager : MonoBehaviour
    {
        public static SDKManager Instance { get; private set; }

        public event UnityAction OnLoginSuccess;
        public event UnityAction OnLogout;

        public bool IsLoggedIn { get; private set; }
        public string CurrentUser { get; private set; }

        [Tooltip("是否在启动时自动弹出登录面板")]
        public bool autoShowLogin = true;

        private bool panelsRegistered = false;

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

            // 确保整个 SDK Canvas 不被销毁
            var canvas = GetComponentInParent<Canvas>();
            if (canvas != null)
                DontDestroyOnLoad(canvas.gameObject);
        }

        private void Start()
        {
            // 使用协程确保 SDKUIManager 单例已完全初始化
            StartCoroutine(AutoRegisterPanelsCoroutine());
        }

        private System.Collections.IEnumerator AutoRegisterPanelsCoroutine()
        {
            // 等待一帧，确保所有单例初始化完成
            yield return null;

            // 再次检查 SDKUIManager 是否已就绪
            int maxRetries = 10;
            int retries = 0;
            while (SDKUIManager.Instance == null && retries < maxRetries)
            {
                yield return null;
                retries++;
            }

            if (SDKUIManager.Instance == null)
            {
                Debug.LogError("[SDK] SDKUIManager 初始化失败，请检查场景配置");
                yield break;
            }

            AutoRegisterPanels();

            if (autoShowLogin && panelsRegistered)
            {
                SDKUIManager.Instance.ShowPanel<LoginPanel>();
            }
        }

        /// <summary>
        /// 自动发现 PanelContainer 下所有面板并注册
        /// </summary>
        private void AutoRegisterPanels()
        {
            var panelContainer = transform.Find("PanelContainer");
            if (panelContainer == null)
            {
                Debug.LogError("[SDK] PanelContainer not found under SDKRoot!");
                return;
            }

            for (int i = 0; i < panelContainer.childCount; i++)
            {
                var child = panelContainer.GetChild(i);
                var panel = child.GetComponent<BasePanel>();
                if (panel != null)
                {
                    SDKUIManager.Instance.RegisterPanel(child.name, panel);
                }
            }
            panelsRegistered = true;
        }

        public void LoginSuccess(string username)
        {
            IsLoggedIn = true;
            CurrentUser = username;
            Debug.Log($"[SDK] 用户登录成功: {username}");
            OnLoginSuccess?.Invoke();
        }

        public void Logout()
        {
            IsLoggedIn = false;
            CurrentUser = null;
            Debug.Log("[SDK] 用户已退出登录");
            OnLogout?.Invoke();
            SDKUIManager.Instance.CloseAll();
            SDKUIManager.Instance.ShowPanel<LoginPanel>();
        }
    }
}
