using BackOffice.Common.Utilities;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using MudBlazor;

namespace BackOffice.Shared;

public partial class MainLayout
{
    // Navigation, LocalStorageService, Snackbar are injected via _Imports.razor

    private bool _drawerOpen = true;
    private bool _isDarkMode;
    private MudThemeProvider _themeProvider = null!;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        GlobalConstants.ConstSnackbar = Snackbar;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                var stored = await LocalStorageService.GetItemAsync<bool?>("darkMode");
                if (stored.HasValue)
                {
                    _isDarkMode = stored.Value;
                }
                else
                {
                    _isDarkMode = await _themeProvider.GetSystemPreference();
                }
                StateHasChanged();
            }
            catch
            {
                // Ignore localStorage errors
            }
        }
    }

    private async Task ToggleDarkMode()
    {
        _isDarkMode = !_isDarkMode;
        try
        {
            await LocalStorageService.SetItemAsync("darkMode", _isDarkMode);
        }
        catch
        {
            // Ignore localStorage errors
        }
    }

    private void DrawerToggle()
    {
        _drawerOpen = !_drawerOpen;
    }

    private async Task Signout()
    {
        await LocalStorageService.RemoveItemAsync("AuthToken");
        Navigation.NavigateTo("/Login");
    }
}
