namespace RpgRoller.Components.Pages;

public sealed class WorkspaceFeedbackService(WorkspaceState state, Func<Task> requestRefreshAsync)
{
    public void SetStatus(string message, bool isError)
    {
        Announce(message);
        AddToast(message, isError);
    }

    public void Announce(string message)
    {
        state.LiveAnnouncement = message;
    }

    public void ClearToasts()
    {
        state.Toasts.Clear();
    }

    private void AddToast(string message, bool isError)
    {
        var toastId = Guid.NewGuid();
        state.Toasts.Add(new(toastId, message, isError));
        _ = DismissToastLaterAsync(toastId);
    }

    private async Task DismissToastLaterAsync(Guid toastId)
    {
        await Task.Delay(ToastDurationMs);

        if (state.Toasts.RemoveAll(toast => toast.Id == toastId) == 0)
            return;

        try
        {
            await requestRefreshAsync();
        }
        catch (ObjectDisposedException)
        {
        }
    }

    private const int ToastDurationMs = 3200;
}