@*
    EN: Admin back-office layout — 2-level sidebar (Admin vs Shop) + Content area.
    VI: Layout quản trị — Sidebar 2 cấp (Admin vs Cửa hàng) + Vùng nội dung.
    
    Admin Level: Dashboard, Quản lý Cửa hàng, Hệ thống, Phân quyền, Cài đặt
    Shop Level:  Detected via URL /admin/shop/{shopId}/**, shows vertical-specific menu
*@
@inherits LayoutComponentBase
@implements IDisposable
@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject WebClientTpos.Client.Services.AuthStateService AuthState
@inject WebClientTpos.Client.Services.AuthService AuthSvc
@inject WebClientTpos.Client.Services.PosDataService PosData
@inject Microsoft.Extensions.Localization.IStringLocalizer<AdminLayout> L
@using WebClientTpos.Client.Services

@* EN: Theme providers moved to App.razor (FRONT-W-06) — DefaultDark is the ThemeStateService default. *@
@* VI: Theme providers đã chuyển về App.razor (FRONT-W-06) — DefaultDark là mặc định của ThemeStateService. *@

<div class="admin-layout">
    @* ═══ SIDEBAR ═══ *@
    <aside class="admin-sidebar @(_sidebarOpen ? "admin-sidebar--open" : "")">
        @* Logo *@
        <div class="admin-sidebar__logo">
            <div class="admin-sidebar__logo-icon">G</div>
            <div class="admin-sidebar__logo-text">
                <span class="admin-sidebar__logo-name">aPOS Admin</span>
                <span class="admin-sidebar__logo-sub">Management Console</span>
            </div>
        </div>

        @* Navigation *@
        <nav class="admin-sidebar__nav">
            @if (_isShopContext)
            {
                @* ═══ SHOP LEVEL SIDEBAR ═══ *@
                
                @* Back to Admin *@
                <a href="/admin" class="admin-nav-item admin-nav-item--back" style="margin-bottom:8px;">
                    <i data-lucide="arrow-left"></i>
                    <span>@L["Admin_Nav_BackToAdmin"]</span>
                </a>

                @* Shop Info Header *@
                <div style="padding:12px 16px;margin-bottom:4px;">
                    <div style="display:flex;align-items:center;gap:10px;">
                        <div style="width:32px;height:32px;border-radius:8px;background:rgba(255,92,0,0.15);display:flex;align-items:center;justify-content:center;">
                            <i data-lucide="@ShopSidebarConfig.GetVerticalIcon(_shopCategory)" style="width:16px;height:16px;color:var(--admin-orange-primary);"></i>
                        </div>
                        <div>
                            <div style="font-weight:600;font-size:14px;color:var(--admin-text-primary);">@_shopName</div>
                            <div style="font-size:11px;color:var(--admin-text-tertiary);">@L[ShopSidebarConfig.GetVerticalLabel(_shopCategory)]</div>
                        </div>
                    </div>
                </div>

                @* Vertical-specific menu *@
                <span class="admin-nav-label">@L["Admin_Nav_SectionManage"]</span>
                @foreach (var item in ShopSidebarConfig.GetMenuItems(_shopCategory))
                {
                    var route = $"/admin/shop/{_shopId}/{item.Route}";
                    var cssClass = item.IsSub ? "admin-nav-item admin-nav-item--sub" : "admin-nav-item";
                    <NavLink href="@route" class="@cssClass" ActiveClass="admin-nav-item--active">
                        <i data-lucide="@item.Icon"></i>
                        <span>@L[item.Label]</span>
                    </NavLink>
                }
            }
            else
            {
                @* ═══ ADMIN LEVEL SIDEBAR ═══ *@
                
                @* ── TỔNG QUAN ── *@
                <span class="admin-nav-label">@L["Admin_Nav_SectionOverview"]</span>
                <NavLink href="/admin" class="admin-nav-item" Match="NavLinkMatch.All" ActiveClass="admin-nav-item--active">
                    <i data-lucide="layout-dashboard"></i>
                    <span>Dashboard</span>
                </NavLink>

                @* ── KINH DOANH ── *@
                <span class="admin-nav-label">@L["Admin_Nav_SectionBusiness"]</span>
                <NavLink href="/admin/stores" class="admin-nav-item" ActiveClass="admin-nav-item--active">
                    <i data-lucide="store"></i>
                    <span>@L["Admin_Nav_Stores"]</span>
                </NavLink>

                @* ── QUẢN TRỊ ── *@
                <span class="admin-nav-label">@L["Admin_Nav_SectionAdmin"]</span>
                <NavLink href="/admin/users" class="admin-nav-item" ActiveClass="admin-nav-item--active">
                    <i data-lucide="users"></i>
                    <span>@L["Admin_Nav_Users"]</span>
                </NavLink>
                <NavLink href="/admin/roles" class="admin-nav-item" ActiveClass="admin-nav-item--active">
                    <i data-lucide="shield"></i>
                    <span>@L["Admin_Nav_Roles"]</span>
                </NavLink>

                @* ── HỆ THỐNG ── *@
                <span class="admin-nav-label">@L["Admin_Nav_SectionSystem"]</span>
                <NavLink href="/admin/system/audit" class="admin-nav-item" ActiveClass="admin-nav-item--active">
                    <i data-lucide="file-text"></i>
                    <span>@L["Admin_Nav_AuditLog"]</span>
                </NavLink>
                <NavLink href="/admin/system/devices" class="admin-nav-item" ActiveClass="admin-nav-item--active">
                    <i data-lucide="monitor-smartphone"></i>
                    <span>@L["Admin_Nav_Devices"]</span>
                </NavLink>
                <NavLink href="/admin/system/integrations" class="admin-nav-item" ActiveClass="admin-nav-item--active">
                    <i data-lucide="plug"></i>
                    <span>@L["Admin_Nav_Integrations"]</span>
                </NavLink>
                <NavLink href="/admin/settings" class="admin-nav-item" ActiveClass="admin-nav-item--active">
                    <i data-lucide="settings"></i>
                    <span>@L["Admin_Nav_Settings"]</span>
                </NavLink>
            }
        </nav>

        @* User profile *@
        <div class="admin-sidebar__user">
            <div class="admin-user-avatar">@_userInitials</div>
            <div class="admin-user-info">
                <span class="admin-user-name">@_userName</span>
                <span class="admin-user-role">@_userRole</span>
            </div>
            <button @onclick="Logout" title="@L["Admin_Nav_Logout"]">
                <i data-lucide="log-out"></i>
            </button>
        </div>
    </aside>

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

    @* ═══ MAIN AREA ═══ *@
    <main class="admin-main">
        @* Mobile-only hamburger toggle *@
        <div class="admin-mobile-bar">
            <button class="admin-mobile-toggle" @onclick="ToggleSidebar">
                <i data-lucide="menu"></i>
            </button>
            <span class="admin-mobile-bar__title">aPOS Admin</span>
        </div>
        <ErrorBoundary @ref="_errorBoundary">
            <ChildContent>
                <CascadingValue Value="this">
                    @Body
                </CascadingValue>
            </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;">@L["Admin_Error_Title"]</h3>
                    <p style="font-size:13px;color:var(--admin-text-tertiary);margin:0 0 16px;">@L["Admin_Error_Subtitle"]</p>
                    <button class="admin-btn-primary" @onclick="RecoverError" style="display:inline-flex;align-items:center;gap:8px;">
                        <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i>
                        @L["Admin_Error_Reload"]
                    </button>
                </div>
            </ErrorContent>
        </ErrorBoundary>
    </main>
</div>

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

    // EN: Shop context detection — parsed from URL
    // VI: Phát hiện context cửa hàng — parse từ URL
    private bool _isShopContext = false;
    private string? _shopId;
    private string _shopName = "";
    private string? _shopCategory;

    protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += OnLocationChanged;
        // EN: Subscribe to auth state changes so user display refreshes after login/logout
        // VI: Subscribe auth state để cập nhật user display sau login/logout
        AuthState.OnChange += OnAuthStateChanged;
        DetectShopContext();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // EN: Re-init Lucide icons after every render (Blazor navigation replaces DOM)
        // VI: Khởi tạo lại Lucide icons sau mỗi lần render (Blazor navigation thay đổi DOM)
        try { await JS.InvokeVoidAsync("lucide.createIcons"); } catch { }

        if (firstRender)
        {
            // EN: Restore session from BFF if AuthState is lost after forceLoad navigation.
            //     TryRestoreSessionAsync calls /api/bff/auth/session — reads the httpOnly cookie server-side.
            // VI: Khôi phục session từ BFF nếu AuthState mất sau forceLoad navigation.
            //     TryRestoreSessionAsync gọi /api/bff/auth/session — đọc httpOnly cookie phía server.
            if (!AuthState.IsAuthenticated)
            {
                try { await AuthSvc.TryRestoreSessionAsync(); } catch { }
            }

            // EN: FRONT-C-04 — Route guard: redirect unauthenticated users to login.
            //     Checked after session restore so valid sessions are not wrongly rejected.
            // VI: FRONT-C-04 — Bảo vệ route: chuyển hướng user chưa xác thực về trang đăng nhập.
            //     Kiểm tra sau khi khôi phục session để tránh từ chối sai các session hợp lệ.
            if (!AuthState.IsAuthenticated)
            {
                var returnUrl = Uri.EscapeDataString(NavigationManager.Uri);
                NavigationManager.NavigateTo($"/auth/login?returnUrl={returnUrl}", forceLoad: false);
                return;
            }

            // EN: FRONT-C-05 — Validate shopId against user permissions via BFF.
            //     If the shop is not accessible, redirect to admin index to prevent IDOR.
            // VI: FRONT-C-05 — Xác thực shopId với quyền user qua BFF.
            //     Nếu shop không có quyền truy cập, chuyển hướng về admin để ngăn IDOR.
            if (_isShopContext && !string.IsNullOrEmpty(_shopId) && Guid.TryParse(_shopId, out var shopGuid))
            {
                try
                {
                    var shop = await PosData.GetShopByIdAsync(shopGuid);
                    if (shop == null)
                    {
                        // EN: BFF returned 404/403 — user has no access to this shop.
                        // VI: BFF trả về 404/403 — user không có quyền truy cập shop này.
                        NavigationManager.NavigateTo("/admin", forceLoad: false);
                        return;
                    }

                    // EN: Populate shop context from verified backend data (not just URL).
                    // VI: Điền thông tin context shop từ dữ liệu backend đã xác thực (không chỉ từ URL).
                    if (string.IsNullOrEmpty(_shopName) || _shopName.StartsWith("Shop #"))
                        _shopName = shop.Name;
                    if (_shopCategory == null && !string.IsNullOrEmpty(shop.Category))
                        _shopCategory = shop.Category.ToLowerInvariant();
                }
                catch { /* Network error — allow render, BFF will 401 on subsequent calls */ }
            }

            // EN: Resolve user display name from AuthState (restored from BFF session).
            // VI: Lấy tên hiển thị từ AuthState (khôi phục từ BFF session).
            if (_resolvedUserName == null && AuthState.IsAuthenticated && !string.IsNullOrEmpty(AuthState.UserEmail))
            {
                _resolvedUserName = AuthState.UserEmail.Split('@').FirstOrDefault() ?? "Admin";
            }

            StateHasChanged();
        }
    }

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

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

    private void OnLocationChanged(object? sender, Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs e)
    {
        DetectShopContext();
        StateHasChanged();
    }

    /// <summary>
    /// EN: Detect if current URL is in shop context (/admin/shop/{shopId}/**).
    /// VI: Phát hiện URL hiện tại có đang trong context cửa hàng không.
    /// </summary>
    private void DetectShopContext()
    {
        var uri = new Uri(NavigationManager.Uri);
        var path = uri.AbsolutePath;

        // EN: Match pattern /admin/shop/{shopId}/**
        // VI: Match pattern /admin/shop/{shopId}/**
        if (path.StartsWith("/admin/shop/") && path.Length > "/admin/shop/".Length)
        {
            var remaining = path["/admin/shop/".Length..];
            var slashIndex = remaining.IndexOf('/');
            _shopId = slashIndex > 0 ? remaining[..slashIndex] : remaining;
            _isShopContext = true;

            // EN: Use shopId as name fallback if not yet set by child page
            // VI: Dùng shopId làm tên nếu chưa được set bởi trang con
            if (string.IsNullOrEmpty(_shopName))
                _shopName = $"Shop #{_shopId?[..8]}";

            // EN: Detect shop category from URL path segments
            // VI: Phát hiện loại cửa hàng từ các phần URL
            if (_shopCategory == null && slashIndex > 0)
            {
                var subPath = remaining[(slashIndex + 1)..];
                var subSlash = subPath.IndexOf('/');
                var section = subSlash > 0 ? subPath[..subSlash] : subPath;
                // EN: Map URL section to shop category
                // VI: Map section URL sang danh mục cửa hàng
                _shopCategory = section switch
                {
                    "cafe" or "restaurant" or "karaoke" or "spa" => section,
                    _ => _shopCategory
                };
            }
        }
        else
        {
            _isShopContext = false;
            _shopId = null;
        }
    }

    /// <summary>
    /// EN: Set shop context info (called from pages that know shop details).
    /// VI: Đặt thông tin context cửa hàng (gọi từ pages biết chi tiết shop).
    /// </summary>
    public void SetShopContext(string shopId, string name, string? category)
    {
        _shopId = shopId;
        _shopName = name;
        _shopCategory = category;
        _isShopContext = true;
        StateHasChanged();
    }

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

    // EN: Compute user display info from AuthState with localStorage fallback
    // VI: Tính toán thông tin hiển thị user từ AuthState với fallback localStorage
    private string? _resolvedUserName;
    private string _userName => _resolvedUserName
        ?? (AuthState.IsAuthenticated ? (AuthState.UserEmail?.Split('@').FirstOrDefault() ?? "Admin") : null)
        ?? "Admin";
    private string _userInitials => _userName.Length >= 2
        ? _userName[..2].ToUpper()
        : _userName.ToUpper();
    private string _userRole => "Admin";

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


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