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

namespace Noctalk_client.Splash_screen;

public sealed class SplashBootTextController
{
    private const string Text_to_type = "Entering darknet...";
    private const double Type_start_seconds = 1.0;
    private const double Type_duration_seconds = 1.5;
    private const double Fade_start_seconds = 7.5;
    private readonly FrameworkElement container;
    private readonly TextBlock textBlock;
    private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromMilliseconds(24) };
    private readonly DateTime startUtc;
    private bool fadeStarted;

    public SplashBootTextController(FrameworkElement The_container, TextBlock The_text_block)
    {
        container = The_container;
        textBlock = The_text_block;
        startUtc = DateTime.UtcNow;
        timer.Tick += (_, _) => Boot_text__tick();
    }

    public void Boot_text__start()
    {
        container.Opacity = 0;
        textBlock.Text = string.Empty;
        timer.Start();
    }

    public void Boot_text__stop()
    {
        timer.Stop();
    }

    private void Boot_text__tick()
    {
        double seconds = (DateTime.UtcNow - startUtc).TotalSeconds;
        if (seconds < Type_start_seconds)
        {
            return;
        }

        container.Opacity = 1;
        double typeProgress = Math.Clamp((seconds - Type_start_seconds) / Type_duration_seconds, 0, 1);
        int characterCount = Math.Min(Text_to_type.Length, (int)Math.Ceiling(Text_to_type.Length * typeProgress));
        textBlock.Text = Text_to_type[..characterCount];

        if (!fadeStarted && seconds >= Fade_start_seconds)
        {
            fadeStarted = true;
            timer.Stop();
            DoubleAnimation fadeAnimation = new(1, 0, TimeSpan.FromSeconds(2))
            {
                EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseInOut }
            };
            container.BeginAnimation(UIElement.OpacityProperty, fadeAnimation);
        }
    }
}
