@inherits LayoutComponentBase
@implements IDisposable

@inject AppThemeState ThemeState
@inject IJSRuntime JS

<div class="page @(sidebarCollapsed ? "sidebar-collapsed" : string.Empty)">
    <div class="sidebar @(sidebarCollapsed ? "sidebar-collapsed" : string.Empty)">
        <NavMenu IsCollapsed="sidebarCollapsed" OnToggleSidebar="ToggleSidebar" />
    </div>

    <main>
        <div class="top-row px-4">
            <a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
        </div>

        <article class="content px-4">
            @Body
        </article>
    </main>
</div>

<div id="blazor-error-ui" data-nosnippet>
    An unhandled error has occurred.
    <a href="." class="reload">Reload</a>
    <span class="dismiss">🗙</span>
</div>

@code {
    private bool sidebarCollapsed = true;

    protected override void OnInitialized()
    {
        ThemeState.ThemeModeChanged += HandleThemeModeChanged;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
        {
            return;
        }

        var themeMode = await ThemeState.EnsureLoadedAsync();
        await ApplyThemeAsync(themeMode);
    }

    private void ToggleSidebar()
    {
        sidebarCollapsed = !sidebarCollapsed;
    }

    private void HandleThemeModeChanged(AppThemeMode themeMode)
    {
        _ = InvokeAsync(() => ApplyThemeAsync(themeMode).AsTask());
    }

    private ValueTask ApplyThemeAsync(AppThemeMode themeMode)
    {
        return JS.InvokeVoidAsync("workTrackerTheme.setTheme", themeMode.ToString().ToLowerInvariant());
    }

    public void Dispose()
    {
        ThemeState.ThemeModeChanged -= HandleThemeModeChanged;
    }
}
