using System;
using UnityEngine;

namespace Jovian.PopupSystem {
    /// <summary>
    /// Default popup animator that fades CanvasGroup alpha. Each category gets its own instance
    /// so concurrent show/hide animations don't corrupt each other.
    /// </summary>
    public sealed class FadePopupAnimator : IPopupAnimator {
        private CanvasGroup target;
        private float timer;
        private float elapsed;
        private float startAlpha;
        private float endAlpha;
        private Action onFinish;

        public bool IsAnimating => target != null;

        public void Show(CanvasGroup canvasGroup, float duration, Action onComplete) {
            target = canvasGroup;
            timer = Mathf.Max(duration, 0.001f);
            elapsed = 0f;
            startAlpha = 0f;
            endAlpha = 1f;
            onFinish = onComplete;
            canvasGroup.alpha = 0f;
        }

        public void Hide(CanvasGroup canvasGroup, float duration, Action onComplete) {
            target = canvasGroup;
            timer = Mathf.Max(duration, 0.001f);
            elapsed = 0f;
            startAlpha = canvasGroup.alpha;
            endAlpha = 0f;
            onFinish = onComplete;
        }

        public void Tick(float deltaTime) {
            if(target == null) {
                return;
            }

            elapsed += deltaTime;
            var t = Mathf.Clamp01(elapsed / timer);
            target.alpha = Mathf.Lerp(startAlpha, endAlpha, t);

            if(!(t >= 1f)) {
                return;
            }
            var callback = onFinish;
            target = null;
            onFinish = null;
            callback?.Invoke();
        }
    }
}
