using UnityEngine;
using UnityEngine.UI;
using IStalk.Runner;

namespace IStalk.UI
{
    public class DamageIndicator : MonoBehaviour
    {
        [SerializeField] private Image _damageOverlay;
        [SerializeField] private Image _downedOverlay;
        [SerializeField] private float _flashDuration = 0.3f;
        [SerializeField] private Color _flashColor = new(1f, 0f, 0f, 0.4f);

        private float _flashTimer;
        private RunnerHealth _health;

        public void Initialize(RunnerHealth health)
        {
            _health = health;
            _health.OnHit += OnHit;
            _health.OnDowned += OnDowned;
            _health.OnRevived += OnRevived;

            if (_damageOverlay != null) SetOverlayAlpha(_damageOverlay, 0);
            if (_downedOverlay != null) _downedOverlay.gameObject.SetActive(false);
        }

        private void OnHit()
        {
            _flashTimer = _flashDuration;
        }

        private void OnDowned()
        {
            if (_downedOverlay != null) _downedOverlay.gameObject.SetActive(true);
        }

        private void OnRevived()
        {
            if (_downedOverlay != null) _downedOverlay.gameObject.SetActive(false);
        }

        private void Update()
        {
            if (_damageOverlay == null) return;

            if (_flashTimer > 0)
            {
                _flashTimer -= Time.deltaTime;
                float alpha = (_flashTimer / _flashDuration) * _flashColor.a;
                SetOverlayAlpha(_damageOverlay, alpha);
            }
            else
            {
                float persistentAlpha = 0f;
                if (_health != null && _health.HitsTaken > 0)
                    persistentAlpha = (float)_health.HitsTaken / _health.MaxHits * 0.2f;
                SetOverlayAlpha(_damageOverlay, persistentAlpha);
            }
        }

        private void SetOverlayAlpha(Image img, float alpha)
        {
            Color c = _flashColor;
            c.a = alpha;
            img.color = c;
        }

        private void OnDestroy()
        {
            if (_health != null)
            {
                _health.OnHit -= OnHit;
                _health.OnDowned -= OnDowned;
                _health.OnRevived -= OnRevived;
            }
        }
    }
}
