@*
    EN: Staff portal layout — Sidebar with role-specific menu + Content area.
    VI: Layout cổng nhân viên — Sidebar với menu theo vai trò + Vùng nội dung.

    Roles: Cashier, Waiter, Kitchen, Manager — each sees different menu items.
    Common: Dashboard, Attendance, Leave Requests, Notifications, Profile.
*@
@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 DataService
@inject WebClientTpos.Client.Services.LocalStorageService LocalStorage

@* 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="staff-layout">
    @* ═══ SIDEBAR ═══ *@
    <aside class="staff-sidebar @(_sidebarOpen ? "staff-sidebar--open" : "")">
        @* Logo *@
        <div class="staff-sidebar__logo">
            <div class="staff-sidebar__logo-icon">G</div>
            <div class="staff-sidebar__logo-text">
                <span class="staff-sidebar__logo-name">aPOS Staff</span>
                <span class="staff-sidebar__logo-sub">@_shopName</span>
            </div>
        </div>

        @* Navigation *@
        <nav class="staff-sidebar__nav">
            @* ── TỔNG QUAN ── *@
            <span class="staff-nav-label">TỔNG QUAN</span>
            <NavLink href="/staff/dashboard" class="staff-nav-item" Match="NavLinkMatch.All" ActiveClass="staff-nav-item--active">
                <i data-lucide="layout-dashboard"></i>
                <span>Dashboard</span>
            </NavLink>

            @* ── CÔNG VIỆC ── *@
            @if (_staffRole == "Manager" || _staffRole == "Kitchen" || _staffRole == "Waiter" || _staffRole == "Cashier")
            {
                <span class="staff-nav-label">CÔNG VIỆC</span>

                @if (_staffRole == "Kitchen")
                {
                    <NavLink href="/staff/kitchen" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                        <i data-lucide="chef-hat"></i>
                        <span>Bếp</span>
                    </NavLink>
                }
                @if (_staffRole == "Waiter")
                {
                    <NavLink href="/staff/tables" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                        <i data-lucide="clipboard-list"></i>
                        <span>Bàn / Order</span>
                    </NavLink>
                }
                @if (_staffRole == "Cashier")
                {
                    <NavLink href="/staff/pos" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                        <i data-lucide="monitor"></i>
                        <span>Thu ngân</span>
                    </NavLink>
                }
                @if (_staffRole == "Manager")
                {
                    <NavLink href="/staff/overview" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                        <i data-lucide="bar-chart-3"></i>
                        <span>Báo cáo</span>
                    </NavLink>
                    <NavLink href="/staff/team" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                        <i data-lucide="users"></i>
                        <span>Nhân viên</span>
                    </NavLink>
                }
            }

            @* ── NHÂN SỰ ── *@
            <span class="staff-nav-label">NHÂN SỰ</span>
            <NavLink href="/staff/attendance" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                <i data-lucide="clock"></i>
                <span>Chấm công</span>
            </NavLink>
            <NavLink href="/staff/leave" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                <i data-lucide="calendar-off"></i>
                <span>Nghỉ phép</span>
            </NavLink>
            <NavLink href="/staff/schedule" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                <i data-lucide="calendar-days"></i>
                <span>Lịch làm việc</span>
            </NavLink>
            <NavLink href="/staff/notifications" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                <i data-lucide="bell"></i>
                <span>Thông báo</span>
                @if (_unreadNotifications > 0)
                {
                    <span class="staff-badge">@_unreadNotifications</span>
                }
            </NavLink>
            <NavLink href="/staff/payroll" class="staff-nav-item" ActiveClass="staff-nav-item--active">
                <i data-lucide="wallet"></i>
                <span>Lương</span>
            </NavLink>
        </nav>

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

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

    @* ═══ MAIN AREA ═══ *@
    <main class="staff-main">
        @* Mobile-only hamburger toggle *@
        <div class="staff-mobile-bar">
            <button class="staff-mobile-toggle" @onclick="ToggleSidebar">
                <i data-lucide="menu"></i>
            </button>
            <span class="staff-mobile-bar__title">aPOS Staff</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;">Có lỗi xảy ra</h3>
                    <p style="font-size:13px;color:var(--admin-text-tertiary);margin:0 0 16px;">Vui lòng thử lại</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>
                        Tải lại
                    </button>
                </div>
            </ErrorContent>
        </ErrorBoundary>
    </main>
</div>

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

    private string _staffRole = "Staff";
    private string _shopName = "Cửa hàng";
    private Guid? _shopId;
    private int _unreadNotifications = 0;
    private string? _staffDisplayName;

    /// <summary>
    /// EN: Current staff role — accessible from child pages.
    /// VI: Vai trò nhân viên hiện tại — truy cập được từ trang con.
    /// </summary>
    public string StaffRole => _staffRole;
    public Guid? ShopId => _shopId;

    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)
        {
            // EN: Restore session from localStorage if AuthState lost after forceLoad navigation.
            //     JS interop is only available in OnAfterRenderAsync, not OnInitializedAsync.
            // VI: Khôi phục session từ localStorage nếu AuthState mất sau forceLoad navigation.
            //     JS interop chỉ khả dụng trong OnAfterRenderAsync, không phải OnInitializedAsync.
            if (!AuthState.IsAuthenticated)
            {
                try { await AuthSvc.TryRestoreSessionAsync("staff"); } catch { }
            }

            // EN: Load staff profile (role, shop) after session is restored
            // VI: Load profile nhân viên (vai trò, shop) sau khi session đã được khôi phục
            await LoadStaffProfile();

            // EN: Resolve user display name from localStorage via LocalStorageService (FRONT-W-07).
            // VI: Lấy tên hiển thị từ localStorage qua LocalStorageService (FRONT-W-07).
            if (_resolvedUserName == null)
            {
                var email = await LocalStorage.GetAsync("aPOS_email_staff")
                    ?? await LocalStorage.GetAsync("aPOS_email");
                if (!string.IsNullOrEmpty(email))
                    _resolvedUserName = email.Split('@').FirstOrDefault() ?? "Staff";
                else if (AuthState.IsAuthenticated && !string.IsNullOrEmpty(AuthState.UserEmail))
                    _resolvedUserName = AuthState.UserEmail.Split('@').FirstOrDefault() ?? "Staff";
            }

            StateHasChanged();
        }
    }

    private async Task LoadStaffProfile()
    {
        try
        {
            var profile = await DataService.GetMyStaffProfileAsync();
            if (profile != null)
            {
                _staffRole = profile.Role ?? "Staff";
                _shopName = profile.ShopName ?? "Cửa hàng";
                _shopId = profile.ShopId;
                var fn = profile.FirstName?.Trim();
                var ln = profile.LastName?.Trim();
                if (!string.IsNullOrEmpty(fn) || !string.IsNullOrEmpty(ln))
                    _staffDisplayName = $"{fn} {ln}".Trim();
            }
        }
        catch
        {
            // EN: Fallback to default / VI: Dùng mặc định nếu lỗi
        }
    }

    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? _resolvedUserName;
    private string _userName => _staffDisplayName ?? _resolvedUserName ?? "Staff";
    private string _userInitials => _userName.Length >= 2
        ? _userName[..2].ToUpper()
        : _userName.ToUpper();

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

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