using System;
using System.Windows.Forms;

namespace Elfisa.UI.Helpers
{
    internal sealed class AnimationTimer : IDisposable
    {
        private readonly Timer _timer;
        private readonly Action<float> _onTick;
        private Action _onComplete;
        private float _from;
        private float _to;
        private float _progress;
        private int _durationMs;
        private int _elapsed;

        public AnimationTimer(Action<float> onTick, Action onComplete = null)
        {
            _onTick = onTick;
            _onComplete = onComplete;
            _timer = new Timer { Interval = 16 };
            _timer.Tick += OnTimerTick;
        }

        public void AnimateTo(float target, int durationMs = 140, Action onComplete = null)
        {
            _from = _progress;
            _to = Math.Max(0f, Math.Min(1f, target));
            _durationMs = Math.Max(1, durationMs);
            _elapsed = 0;
            _onComplete = onComplete;
            _timer.Start();
        }

        private void OnTimerTick(object sender, EventArgs e)
        {
            _elapsed += _timer.Interval;
            var t = Math.Min(1f, _elapsed / (float)_durationMs);
            t = 1f - (float)Math.Pow(1f - t, 3f);
            _progress = _from + ((_to - _from) * t);
            _onTick(_progress);

            if (_elapsed >= _durationMs)
            {
                _progress = _to;
                _timer.Stop();
                var complete = _onComplete;
                _onComplete = null;
                complete?.Invoke();
            }
        }

        public void Dispose()
        {
            _timer.Stop();
            _timer.Dispose();
        }
    }
}
