using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DansoriEQ.App.Controls;

/// <summary>Animated equalizer bars — a lively "AI is working" indicator. Pure WPF (경로 A).</summary>
public partial class EqBarsFx : UserControl
{
    private readonly List<Rectangle> _bars = new();
    private readonly Random _rng = new();
    private bool _running;

    public int BarCount { get; set; } = 5;
    public double BarMaxHeight { get; set; } = 18;
    public double BarMinHeight { get; set; } = 4;
    public Brush BarBrush { get; set; } = new LinearGradientBrush(
        Color.FromRgb(0x38, 0xE0, 0xC4), Color.FromRgb(0x4C, 0xC2, 0xFF), 90);

    public EqBarsFx()
    {
        InitializeComponent();
        Loaded += (_, __) => Build();
    }

    private void Build()
    {
        if (_bars.Count > 0) return;
        Bars.Height = BarMaxHeight;
        for (int i = 0; i < BarCount; i++)
        {
            var r = new Rectangle
            {
                Width = 3, Height = BarMinHeight, RadiusX = 1.5, RadiusY = 1.5,
                Margin = new Thickness(1.5, 0, 1.5, 0),
                VerticalAlignment = VerticalAlignment.Bottom,
                Fill = BarBrush
            };
            _bars.Add(r);
            Bars.Children.Add(r);
        }
    }

    /// <summary>Start the bar animation.</summary>
    public void Start()
    {
        Build();
        if (_running) return;
        _running = true;
        for (int i = 0; i < _bars.Count; i++)
        {
            var anim = new DoubleAnimation
            {
                From = BarMinHeight,
                To = BarMaxHeight,
                Duration = TimeSpan.FromMilliseconds(_rng.Next(360, 720)),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever,
                BeginTime = TimeSpan.FromMilliseconds(i * 90),
                EasingFunction = new SineEase { EasingMode = EasingMode.EaseInOut }
            };
            _bars[i].BeginAnimation(HeightProperty, anim);
        }
    }

    /// <summary>Stop and flatten the bars.</summary>
    public void Stop()
    {
        _running = false;
        foreach (var b in _bars)
        {
            b.BeginAnimation(HeightProperty, null);
            b.Height = BarMinHeight;
        }
    }
}
