using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace DansoriEQ.App.Controls;

/// <summary>Brief success toast with a mascot pop-in. Pure WPF (경로 A).</summary>
public partial class MascotToast : UserControl
{
    private readonly DispatcherTimer _hold = new();
    private bool _showing;

    public MascotToast()
    {
        InitializeComponent();
        _hold.Tick += (_, __) => { _hold.Stop(); FadeOut(); };
    }

    /// <summary>Pop the toast in with a title/message, hold, then fade out.</summary>
    public void Show(string title = "튜닝 완료!", string message = "적용됐어요 👍", int holdMs = 1900)
    {
        TitleText.Text = title;
        MsgText.Text = message;

        Visibility = Visibility.Visible;
        _showing = true;

        var dur = TimeSpan.FromMilliseconds(220);
        var ease = new BackEase { EasingMode = EasingMode.EaseOut, Amplitude = 0.5 };
        PopScale.BeginAnimation(System.Windows.Media.ScaleTransform.ScaleXProperty,
            new DoubleAnimation(0.8, 1.0, dur) { EasingFunction = ease });
        PopScale.BeginAnimation(System.Windows.Media.ScaleTransform.ScaleYProperty,
            new DoubleAnimation(0.8, 1.0, dur) { EasingFunction = ease });
        BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(160)));

        _hold.Interval = TimeSpan.FromMilliseconds(holdMs);
        _hold.Stop();
        _hold.Start();
    }

    private void FadeOut()
    {
        if (!_showing) return;
        var fade = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(320));
        fade.Completed += (_, __) =>
        {
            if (!_showing) return;      // a new Show() may have re-triggered
            Visibility = Visibility.Collapsed;
        };
        _showing = false;
        BeginAnimation(OpacityProperty, fade);
    }
}
