@*
    EN: Super Admin layout — platform-level management panel with sidebar navigation.
    VI: Layout Super Admin — trang quản lý nền tảng với sidebar navigation.
*@
@inherits LayoutComponentBase
@implements IDisposable
@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject WebClientTpos.Client.Services.AuthStateService AuthState
@inject WebClientTpos.Client.Services.AuthService AuthSvc
@inject Microsoft.Extensions.Localization.IStringLocalizer<SuperAdminLayout> L
@using WebClientTpos.Client.Services

<div class="sa-layout">
    @* ═══ SIDEBAR ═══ *@
    <aside class="sa-sidebar @(_sidebarOpen ? "sa-sidebar--open" : "")">
        @* Logo *@
        <div class="sa-sidebar__logo">
            <div class="sa-sidebar__logo-icon">
                <i data-lucide="shield-check" style="width:20px;height:20px;color:#1E40AF;"></i>
            </div>
            <div class="sa-sidebar__logo-text">
                <span class="sa-sidebar__logo-name">aPOS Platform</span>
                <span class="sa-sidebar__logo-sub">Super Admin</span>
            </div>
        </div>

        @* Navigation *@
        <nav class="sa-sidebar__nav">
            <span class="sa-nav-label">@L["SA_Section_Overview"]</span>
            <NavLink href="/superadmin/dashboard" class="sa-nav-item" Match="NavLinkMatch.All" ActiveClass="sa-nav-item--active">
                <i data-lucide="layout-dashboard"></i>
                <span>@L["SA_Nav_Dashboard"]</span>
            </NavLink>

            <span class="sa-nav-label">@L["SA_Section_Business"]</span>
            <NavLink href="/superadmin/merchants" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="building-2"></i>
                <span>@L["SA_Nav_Merchants"]</span>
            </NavLink>
            <NavLink href="/superadmin/subscriptions" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="credit-card"></i>
                <span>@L["SA_Nav_Subscriptions"]</span>
            </NavLink>

            <span class="sa-nav-label">@L["SA_Section_Users"]</span>
            <NavLink href="/superadmin/users" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="users"></i>
                <span>@L["SA_Nav_Users"]</span>
            </NavLink>
            <NavLink href="/superadmin/roles" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="shield"></i>
                <span>@L["SA_Nav_Roles"]</span>
            </NavLink>

            <span class="sa-nav-label">@L["SA_Section_System"]</span>
            <NavLink href="/superadmin/system/health" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="activity"></i>
                <span>@L["SA_Nav_SystemHealth"]</span>
            </NavLink>
            <NavLink href="/superadmin/system/audit" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="file-text"></i>
                <span>@L["SA_Nav_AuditLog"]</span>
            </NavLink>
            <NavLink href="/superadmin/system/flags" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="toggle-left"></i>
                <span>@L["SA_Nav_FeatureFlags"]</span>
            </NavLink>

            <span class="sa-nav-label">@L["SA_Section_Config"]</span>
            <NavLink href="/superadmin/settings" class="sa-nav-item" ActiveClass="sa-nav-item--active">
                <i data-lucide="settings"></i>
                <span>@L["SA_Nav_Settings"]</span>
            </NavLink>
        </nav>

        @* User profile *@
        <div class="sa-sidebar__user">
            <div class="sa-user-avatar">SA</div>
            <div class="sa-user-info">
                <span class="sa-user-name">@_userName</span>
                <span class="sa-user-role">Super Admin</span>
            </div>
            <button @onclick="Logout" title="Đăng xuất">
                <i data-lucide="log-out"></i>
            </button>
        </div>
    </aside>

    @* Mobile overlay *@
    @if (_sidebarOpen)
    {
        <div class="sa-sidebar-overlay" @onclick="CloseSidebar"></div>
    }

    @* ═══ MAIN AREA ═══ *@
    <main class="sa-main">
        <div class="sa-mobile-bar">
            <button class="sa-mobile-toggle" @onclick="ToggleSidebar">
                <i data-lucide="menu"></i>
            </button>
            <span class="sa-mobile-bar__title">aPOS Super Admin</span>
        </div>
        <ErrorBoundary @ref="_errorBoundary">
            <ChildContent>
                @Body
            </ChildContent>
            <ErrorContent>
                <div style="text-align:center;padding:48px 20px;">
                    <div style="width:64px;height:64px;border-radius:20px;background:rgba(239,68,68,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
                        <i data-lucide="alert-triangle" style="width:28px;height:28px;color:#EF4444;"></i>
                    </div>
                    <h3 style="font-size:16px;font-weight:700;margin:0 0 8px;color:#EF4444;">Đã xảy ra lỗi</h3>
                    <p style="font-size:13px;color:var(--sa-text-tertiary);margin:0 0 16px;">Vui lòng thử lại hoặc liên hệ bộ phận kỹ thuật.</p>
                    <button class="sa-btn-primary" @onclick="RecoverError" style="display:inline-flex;align-items:center;gap:8px;">
                        <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i>
                        Tải lại
                    </button>
                </div>
            </ErrorContent>
        </ErrorBoundary>
    </main>
</div>

@code {
    private bool _sidebarOpen = false;
    private ErrorBoundary? _errorBoundary;

    protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += OnLocationChanged;
        AuthState.OnChange += OnAuthStateChanged;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        try { await JS.InvokeVoidAsync("lucide.createIcons"); } catch { }

        if (firstRender)
        {
            if (!AuthState.IsAuthenticated)
            {
                try { await AuthSvc.TryRestoreSessionAsync(); } catch { }
            }

            if (!AuthState.IsAuthenticated)
            {
                var returnUrl = Uri.EscapeDataString(NavigationManager.Uri);
                NavigationManager.NavigateTo($"/auth/login?returnUrl={returnUrl}", forceLoad: false);
                return;
            }

            StateHasChanged();
        }
    }

    private void OnAuthStateChanged()
    {
        try { InvokeAsync(StateHasChanged); } catch { }
    }

    private void RecoverError() => _errorBoundary?.Recover();

    private void OnLocationChanged(object? sender, Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs e)
        => StateHasChanged();

    private void ToggleSidebar() => _sidebarOpen = !_sidebarOpen;
    private void CloseSidebar() => _sidebarOpen = false;

    private string _userName => AuthState.IsAuthenticated
        ? (AuthState.UserEmail?.Split('@').FirstOrDefault() ?? "Admin")
        : "Admin";

    private async Task Logout()
    {
        await AuthSvc.LogoutAsync();
        NavigationManager.NavigateTo("/auth/login", forceLoad: true);
    }

    public void Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
        AuthState.OnChange -= OnAuthStateChanged;
    }
}
