@using TaxBaik.Web.Client.Components.Admin.Shared
@inject NavigationManager Navigation
@inject TaxBaik.Web.Client.Components.Admin.Services.IAdminSessionBootstrap SessionBootstrap
@implements IDisposable

<div class="admin-shell">
    <header class="admin-topbar">
        <MudButton Variant="Variant.Outlined"
                   Color="Color.Primary"
                   Class="admin-menu-button"
                   aria-label="메뉴 토글"
                   aria-expanded="@drawerOpen"
                   OnClick="@ToggleDrawer">
            메뉴
        </MudButton>
        <div class="admin-topbar-title">
            <div class="admin-brand-text">TaxBaik</div>
            <div class="admin-brand-subtitle">세무회계 관리 대시보드</div>
        </div>
        <div class="admin-topbar-actions">
            <span class="admin-topbar-status">현재: @currentRouteLabel</span>
            <MudButton Variant="Variant.Text" Color="Color.Primary" Href="/" Target="_blank" Class="admin-topbar-action">
                공개 사이트
            </MudButton>
            <MudButton Variant="Variant.Text" Color="Color.Primary" Href="./logout" Class="admin-topbar-action">
                로그아웃
            </MudButton>
        </div>
    </header>

    <div class="admin-body">
        @if (drawerOpen)
        {
            <AdminSidebar />
        }

        <main class="admin-main">
            <div class="admin-content">
                @ChildContent
            </div>
        </main>
    </div>
</div>

@code {
    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    private bool drawerOpen = true;
    private string currentRouteLabel = "대시보드";

    protected override void OnInitialized()
    {
        UpdateRouteLabel();
        Navigation.LocationChanged += OnLocationChanged;
    }

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

        await SessionBootstrap.EnsureInitializedAsync();
    }

    private void OnLocationChanged(object? sender, LocationChangedEventArgs args)
    {
        UpdateRouteLabel();
        InvokeAsync(StateHasChanged);
    }

    private void ToggleDrawer()
    {
        drawerOpen = !drawerOpen;
    }

    private void UpdateRouteLabel()
    {
        var path = Navigation.ToBaseRelativePath(Navigation.Uri);
        path = string.IsNullOrWhiteSpace(path) ? "/" : "/" + path;
        currentRouteLabel = AdminNavigationCatalog.GetLabel(path);
    }

    public void Dispose()
    {
        Navigation.LocationChanged -= OnLocationChanged;
    }
}
