@implements IDisposable
@inject RolemasterDb.App.Frontend.AppState.ThemeState ThemeState

<label class="shell-theme-switcher">
    <span class="shell-theme-switcher-label">Theme</span>
    <select class="input-shell shell-theme-switcher-select" value="@CurrentValue" @onchange="HandleChanged">
        <option value="system">System</option>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
    </select>
</label>

@code {
    private string CurrentValue =>
        ThemeState.CurrentMode switch
        {
            RolemasterDb.App.Frontend.AppState.ThemeMode.Light => "light",
            RolemasterDb.App.Frontend.AppState.ThemeMode.Dark => "dark",
            _ => "system"
        };

    protected override void OnInitialized()
    {
        ThemeState.Changed += HandleThemeChanged;
    }

    private async Task HandleChanged(ChangeEventArgs args)
    {
        var nextMode = args.Value?.ToString() switch
        {
            "light" => RolemasterDb.App.Frontend.AppState.ThemeMode.Light,
            "dark" => RolemasterDb.App.Frontend.AppState.ThemeMode.Dark,
            _ => RolemasterDb.App.Frontend.AppState.ThemeMode.System
        };

        await ThemeState.SetModeAsync(nextMode);
    }

    private void HandleThemeChanged()
    {
        _ = InvokeAsync(StateHasChanged);
    }

    public void Dispose()
    {
        ThemeState.Changed -= HandleThemeChanged;
    }
}
