using UnityEngine;

namespace GameSDK
{
    /// <summary>
    /// UI面板基类，支持淡入淡出动画
    /// </summary>
    public class BasePanel : MonoBehaviour
    {
        protected CanvasGroup canvasGroup;

        public float fadeDuration = 0.25f;

        private float fadeTarget = -1f;
        private float fadeTimer = 0f;
        private float fadeFrom = 0f;
        private System.Action fadeCallback;

        /// <summary>
        /// 确保 CanvasGroup 存在（lazy init，应对 inactive 面板）
        /// </summary>
        protected void EnsureCanvasGroup()
        {
            if (canvasGroup == null)
            {
                canvasGroup = GetComponent<CanvasGroup>();
                if (canvasGroup == null)
                    canvasGroup = gameObject.AddComponent<CanvasGroup>();
            }
        }

        protected virtual void Awake()
        {
            EnsureCanvasGroup();
        }

        protected virtual void Update()
        {
            if (fadeTarget < 0f) return;

            fadeTimer += Time.deltaTime;
            float t = Mathf.Clamp01(fadeTimer / fadeDuration);
            canvasGroup.alpha = Mathf.Lerp(fadeFrom, fadeTarget, t);

            if (t >= 1f)
            {
                canvasGroup.alpha = fadeTarget;

                if (fadeTarget > 0f)
                    canvasGroup.blocksRaycasts = true;

                System.Action cb = fadeCallback;
                fadeTarget = -1f;
                fadeCallback = null;
                cb?.Invoke();
            }
        }

        public virtual void OnEnter()
        {
            gameObject.SetActive(true);
            EnsureCanvasGroup();
            canvasGroup.blocksRaycasts = true;
            StartFade(1f);
        }

        public virtual void OnPause()
        {
            StartFade(0f, () => gameObject.SetActive(false));
        }

        public virtual void OnResume()
        {
            gameObject.SetActive(true);
            EnsureCanvasGroup();
            canvasGroup.blocksRaycasts = true;
            StartFade(1f);
        }

        public virtual void OnExit()
        {
            StartFade(0f, () => gameObject.SetActive(false));
        }

        private void StartFade(float targetAlpha, System.Action onComplete = null)
        {
            EnsureCanvasGroup();
            fadeFrom = canvasGroup.alpha;
            fadeTarget = targetAlpha;
            fadeTimer = 0f;
            fadeCallback = onComplete;
        }
    }
}
