using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using QuizPleaseTest.Boot.Settings;
using QuizPleaseTest.Boot.UI;
using QuizPleaseTest.Common.StateMachine;
using UnityEngine;

namespace QuizPleaseTest.Boot.States
{
    public class SplashState : IState
    {
        private readonly SplashUIView _view;
        private readonly BootStatusUIView _statusView;
        private readonly BootSettings _settings;

        public SplashState(SplashUIView view, BootStatusUIView statusView, BootSettings settings)
        {
            _view = view;
            _statusView = statusView;
            _settings = settings;
        }

        public async UniTask EnterAsync(CancellationToken ct)
        {
            _statusView.SetStatus("Splash");
            _statusView.SetProgress(0f);

            _view.Bind(new SplashUIViewModel());
            _view.Initialize();

            int delayMs = Mathf.Max(0, Mathf.RoundToInt(_settings.SplashDurationSeconds * 1000f));
            try
            {
                await UniTask.Delay(delayMs, cancellationToken: ct);
            }
            catch (OperationCanceledException) when (ct.IsCancellationRequested)
            {
                _view.Release();
                throw;
            }
        }

        public UniTask ExitAsync(CancellationToken ct)
        {
            _view.Release();
            return UniTask.CompletedTask;
        }
    }
}
