using Microsoft.JSInterop;

namespace NexusReader.UI.Shared.Services;

public sealed class FocusModeService : IFocusModeService
{
    private readonly IJSRuntime _jsRuntime;
    public bool IsFocusModeActive { get; private set; }
    public event Func<Task>? OnFocusModeChanged;

    public FocusModeService(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    public async Task InitializeAsync()
    {
        try
        {
            var value = await _jsRuntime.InvokeAsync<string>("localStorage.getItem", "nexus_focus_mode");
            if (value == "true" && !IsFocusModeActive)
            {
                IsFocusModeActive = true;
                if (OnFocusModeChanged != null) await OnFocusModeChanged();
            }
        }
        catch
        {
            // Ignored during pre-rendering or unsupported environments
        }
    }

    public async Task ToggleAsync()
    {
        IsFocusModeActive = !IsFocusModeActive;
        if (OnFocusModeChanged != null) await OnFocusModeChanged();

        try
        {
            await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "nexus_focus_mode", IsFocusModeActive ? "true" : "false");
        }
        catch { }
    }
}
