@using System.Globalization
@using CommunityToolkit.Mvvm.Messaging
@using salesbook.Shared.Core.Messages.Back
@inherits LayoutComponentBase
@inject IJSRuntime JS
@inject IMessenger Messenger
@inject BackNavigationService BackService

<MudThemeProvider Theme="_currentTheme" @ref="@_mudThemeProvider" @bind-IsDarkMode="@IsDarkMode" />
<MudPopoverProvider/>
<MudDialogProvider/>
<MudSnackbarProvider/>

<div class="page">
    <NavMenu/>

    <main>
        <article>
            @Body
        </article>
    </main>

</div>

@code {
    private MudThemeProvider? _mudThemeProvider;
    private bool IsDarkMode { get; set; }
    private string _mainContentClass = "";

    private readonly MudTheme _currentTheme = new()
    {
        PaletteLight = new PaletteLight()
        {
            Primary = "#00a0de",
            Secondary = "#002339",
            Tertiary = "#dff2ff",
            TextPrimary = "#000"
        },
        PaletteDark = new PaletteDark
        {
            Primary = "#00a0de",
            Secondary = "#002339",
            Tertiary = "#dff2ff",
            Surface = "#000406",
            Background = "#000406",
            TextPrimary = "#fff",
            GrayDark = "#E0E0E0"
        }
    };

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // if (firstRender)
        // {
        //     var isDarkMode = LocalStorage.GetString("isDarkMode");

        //     if (isDarkMode == null && _mudThemeProvider != null)
        //     {
        //         IsDarkMode = await _mudThemeProvider.GetSystemPreference();
        //         await _mudThemeProvider.WatchSystemPreference(OnSystemPreferenceChanged);
        //         LocalStorage.SetString("isDarkMode", IsDarkMode.ToString());
        //         StateHasChanged();
        //     }
        //     else
        //     {
        //         IsDarkMode = bool.Parse(isDarkMode!);
        //     }

        //     if (IsDarkMode)
        //     {
        //         _mainContentClass += "is-dark";
        //         StateHasChanged();
        //     }
        // }
    }

    private async Task OnSystemPreferenceChanged(bool newValue)
    {
        IsDarkMode = newValue;
    }

    protected override void OnInitialized()
    {
        BackService.OnHardwareBack += async () => { await JS.InvokeVoidAsync("goBack"); };

        var culture = new CultureInfo("it-IT", false);

        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;
    }

}