@using DeepDrftPublic.Client.Controls
@using DeepDrftPublic.Client.Controls.AudioPlayerBar
@using DeepDrftPublic.Client.Services
@using DeepDrftPublic.Client.Common
@using DeepDrftShared.Client.Common
@using Microsoft.AspNetCore.Components
@inherits LayoutComponentBase
@implements IDisposable

<MudThemeProvider Theme="@DeepDrftPalettes.Embed" IsDarkMode="_isDarkMode" />
<div class="@ThemeWrapperClass">
    <MudLayout Style="display: flex; flex-direction: column; min-height: 100vh">
        <AudioPlayerProvider>
            <MudMainContent Class="pt-0">
                @Body
            </MudMainContent>
        </AudioPlayerProvider>
    </MudLayout>
</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 const string DarkModeKey = "darkMode";
    private bool _isDarkMode = false;
    private PersistingComponentStateSubscription _persistingSubscription;

    [Inject] public required PersistentComponentState PersistentState { get; set; }
    [Inject] public required DarkModeSettings DarkModeSettings { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        // Restore persisted dark mode state (from server prerender)
        if (PersistentState.TryTakeFromJson<bool>(DarkModeKey, out var restored))
        {
            _isDarkMode = restored;
            DarkModeSettings.IsDarkMode = restored;
        }
        else
        {
            _isDarkMode = DarkModeSettings.IsDarkMode;
        }

        // Register to persist state when prerendering completes
        _persistingSubscription = PersistentState.RegisterOnPersisting(PersistDarkMode);
    }

    // Theme wrapper class for CSS targeting
    private string ThemeWrapperClass => _isDarkMode ? "deepdrft-theme-dark" : "deepdrft-theme-light";

    private Task PersistDarkMode()
    {
        PersistentState.PersistAsJson(DarkModeKey, _isDarkMode);
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _persistingSubscription.Dispose();
    }
}


