using System;
using System.Drawing;
using System.Windows.Forms;
using Elfisa.UI.Theming;

namespace Elfisa.UI.Helpers
{
    /// <summary>
    /// Полупрозрачный оверлей для плавных переходов между экранами (Fluent motion ~150ms).
    /// </summary>
    public sealed class FadeOverlayPanel : Panel
    {
        private readonly AnimationTimer _animTimer;
        private float _opacity;
        private Action _midAction;

        public FadeOverlayPanel()
        {
            Dock = DockStyle.Fill;
            Visible = false;
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.UserPaint |
                     ControlStyles.OptimizedDoubleBuffer |
                     ControlStyles.ResizeRedraw, true);
            _animTimer = new AnimationTimer(v =>
            {
                _opacity = v;
                Invalidate();
            });
        }

        public void Flash(int durationMs, Action midAction)
        {
            _midAction = midAction;
            Visible = true;
            BringToFront();
            _animTimer.AnimateTo(1f, durationMs / 2, OnFadeInComplete);
        }

        private void OnFadeInComplete()
        {
            _midAction?.Invoke();
            _midAction = null;
            _animTimer.AnimateTo(0f, 120, () =>
            {
                Visible = false;
                _opacity = 0f;
            });
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            var theme = ThemeManager.Colors;
            var alpha = (int)(180 * _opacity);
            using (var brush = new SolidBrush(Color.FromArgb(alpha, theme.Surface)))
            {
                e.Graphics.FillRectangle(brush, ClientRectangle);
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _animTimer.Dispose();
            }

            base.Dispose(disposing);
        }
    }
}
