@page "/admin/shop/{ShopId}/{Section}"
@layout AdminLayout
@inherits AdminBase
@inject PosDataService DataService
@inject NavigationManager Nav
@using WebClientTpos.Client.Services

@*
    EN: Shop-scoped page — thin shell that routes to child components per section.
    VI: Trang theo cửa hàng — shell mỏng route tới component con theo section.
*@

<PageTitle>@_sectionTitle — @(_shopName ?? "Cửa hàng") — aPOS Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">@_sectionTitle</h1>
        <p class="admin-topbar__subtitle">@(_shopName ?? "Cửa hàng") • @_verticalLabel</p>
    </div>
    <div style="display:flex;align-items:center;gap:12px;">
        @* G9: Notification Bell *@
        <div style="position:relative;">
            <button @onclick='() => { _showNotifications = !_showNotifications; StateHasChanged(); }'
                style="width:40px;height:40px;border-radius:12px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);display:flex;align-items:center;justify-content:center;cursor:pointer;position:relative;">
                <i data-lucide="bell" style="width:18px;height:18px;color:var(--admin-text-secondary);"></i>
                <span style="position:absolute;top:6px;right:6px;width:8px;height:8px;border-radius:50%;background:#EF4444;border:2px solid var(--admin-bg-elevated);"></span>
            </button>
            @if (_showNotifications)
            {
                <div style="position:absolute;right:0;top:48px;width:320px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,0.3);z-index:100;overflow:hidden;">
                    <div style="padding:14px 16px;border-bottom:1px solid var(--admin-border-subtle);display:flex;justify-content:space-between;align-items:center;">
                        <span style="font-weight:700;font-size:14px;">Thông báo</span>
                        <span style="font-size:11px;color:var(--admin-orange-primary);cursor:pointer;">Xem tất cả</span>
                    </div>
                    @foreach (var notif in new[] {
                        new { Icon = "alert-triangle", Title = "Sắp hết hàng", Desc = "Espresso chỉ còn 3 phần", Time = "5 phút trước", Color = "#F59E0B" },
                        new { Icon = "package", Title = "Đơn hàng mới", Desc = "Bàn 3 — Phở bò x2, Gỏi cuốn x1", Time = "12 phút trước", Color = "#3B82F6" },
                        new { Icon = "check-circle", Title = "Ca làm hoàn thành", Desc = "Nguyễn Văn A đã kết thúc ca chiều", Time = "1 giờ trước", Color = "#22C55E" },
                        new { Icon = "wallet", Title = "Giao dịch ví", Desc = "Nạp thêm 500,000₫ vào ví store", Time = "3 giờ trước", Color = "#8B5CF6" } })
                    {
                        <div style="padding:12px 16px;border-bottom:1px solid var(--admin-border-subtle);cursor:pointer;transition:background 0.15s;" onmouseover="this.style.background='rgba(255,92,0,0.05)'" onmouseout="this.style.background='transparent'">
                            <div style="display:flex;gap:10px;align-items:flex-start;">
                                <div style="width:32px;height:32px;border-radius:8px;background:@($"{notif.Color}1a");display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                                    <i data-lucide="@notif.Icon" style="width:16px;height:16px;color:@notif.Color;"></i>
                                </div>
                                <div style="flex:1;">
                                    <div style="font-weight:600;font-size:13px;">@notif.Title</div>
                                    <div style="font-size:12px;color:var(--admin-text-tertiary);margin-top:2px;">@notif.Desc</div>
                                    <div style="font-size:11px;color:var(--admin-text-quaternary, #555);margin-top:4px;">@notif.Time</div>
                                </div>
                            </div>
                        </div>
                    }
                </div>
            }
        </div>
    </div>
</div>

@* ═══ CONTENT ═══ *@
<div class="admin-content" style="display:flex;flex-direction:column;gap:24px;">

    @if (!string.IsNullOrEmpty(_errorMessage))
    {
        <div class="admin-panel" style="border:1px solid rgba(239,68,68,0.3);">
            <div class="admin-panel__body" style="text-align:center;padding:40px 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-circle" style="width:28px;height:28px;color:#EF4444;"></i>
                </div>
                <h3 style="font-size:16px;font-weight:700;margin:0 0 8px;color:#EF4444;">Lỗi tải dữ liệu</h3>
                <p style="font-size:13px;color:var(--admin-text-tertiary);margin:0 0 16px;max-width:400px;margin-left:auto;margin-right:auto;">@_errorMessage</p>
                <button class="admin-btn-primary" @onclick="@(() => LoadData())" style="display:inline-flex;align-items:center;gap:8px;">
                    <i data-lucide="refresh-cw" style="width:14px;height:14px;"></i>
                    Thử lại
                </button>
            </div>
        </div>
    }
    else if (IsLoading)
    {
        <div style="text-align:center;padding:48px 20px;">
            <div class="spinner-small" style="width:32px;height:32px;margin:0 auto 16px;"></div>
            <p style="color:var(--admin-text-tertiary);font-size:14px;">Đang tải...</p>
        </div>
    }
    else
    {
        @switch (_section)
        {
            // ═══ OVERVIEW DASHBOARD ═══
            case "overview":
                <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;margin-bottom:20px;">
                    <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);"><i data-lucide="trending-up" style="color:#22C55E;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@ShopHelpers.FormatVND(_ovOrders.Sum(o => o.TotalAmount))</span><span class="admin-stat-card__label">Doanh thu</span></div></div>
                    <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(59,130,246,0.1);"><i data-lucide="receipt" style="color:#3B82F6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_ovOrders.Count</span><span class="admin-stat-card__label">Đơn hàng</span></div></div>
                    <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(255,92,0,0.1);"><i data-lucide="package" style="color:#FF5C00;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_ovProducts.Count</span><span class="admin-stat-card__label">Sản phẩm</span></div></div>
                    <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(139,92,246,0.1);"><i data-lucide="users" style="color:#8B5CF6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_ovStaff.Count</span><span class="admin-stat-card__label">Nhân viên</span></div></div>
                </div>
                @if (_posVertical == "restaurant" && _ovTables.Any())
                {
                    <div class="admin-panel" style="margin-bottom:16px;">
                        <div class="admin-panel__header"><h3 class="admin-panel__title">Bàn hôm nay</h3></div>
                        <div class="admin-panel__body"><div style="display:flex;gap:16px;flex-wrap:wrap;">
                            <span class="admin-status-badge admin-status-badge--online"><span class="admin-status-badge__dot"></span>Trống: @_ovTables.Count(t => t.Status == "available")</span>
                            <span class="admin-status-badge admin-status-badge--paused"><span class="admin-status-badge__dot"></span>Đang dùng: @_ovTables.Count(t => t.Status == "occupied")</span>
                            <span class="admin-status-badge admin-status-badge--setup"><span class="admin-status-badge__dot"></span>Đã đặt: @_ovTables.Count(t => t.Status == "reserved")</span>
                        </div></div>
                    </div>
                }
                @if (_posVertical == "karaoke" && _ovTables.Any())
                {
                    <div class="admin-panel" style="margin-bottom:16px;">
                        <div class="admin-panel__header"><h3 class="admin-panel__title">Phòng hôm nay</h3></div>
                        <div class="admin-panel__body"><div style="display:flex;gap:16px;flex-wrap:wrap;">
                            <span class="admin-status-badge admin-status-badge--online"><span class="admin-status-badge__dot"></span>Trống: @_ovTables.Count(t => t.Status == "available")</span>
                            <span class="admin-status-badge admin-status-badge--paused"><span class="admin-status-badge__dot"></span>Đang hát: @_ovTables.Count(t => t.Status == "occupied")</span>
                        </div></div>
                    </div>
                }
                @if ((_posVertical == "spa" || _posVertical == "beauty") && _ovAppts.Any())
                {
                    <div class="admin-panel" style="margin-bottom:16px;">
                        <div class="admin-panel__header"><h3 class="admin-panel__title">Lịch hẹn hôm nay</h3></div>
                        <div class="admin-panel__body"><div style="display:flex;gap:16px;flex-wrap:wrap;">
                            <span class="admin-status-badge admin-status-badge--online"><span class="admin-status-badge__dot"></span>Đã xác nhận: @_ovAppts.Count(a => a.Status == "Confirmed")</span>
                            <span class="admin-status-badge admin-status-badge--setup"><span class="admin-status-badge__dot"></span>Chờ: @_ovAppts.Count(a => a.Status == "Pending")</span>
                        </div></div>
                    </div>
                }
                @if (_ovOrders.Any())
                {
                    <div class="admin-panel">
                        <div class="admin-panel__header"><h3 class="admin-panel__title">Đơn gần đây</h3></div>
                        <div class="admin-panel__body" style="padding:0;">
                            <table class="admin-table" style="width:100%;"><thead><tr>
                                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">ID</th>
                                <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Số tiền</th>
                                <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Ngày</th>
                            </tr></thead><tbody>
                                @foreach (var o in _ovOrders.Take(10))
                                {
                                    <tr style="border-top:1px solid var(--admin-border-subtle);">
                                        <td style="padding:12px 16px;font-family:monospace;font-size:12px;">@o.Id.ToString()[..8]</td>
                                        <td style="padding:12px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@ShopHelpers.FormatVND(o.TotalAmount)</td>
                                        <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@o.CreatedAt.ToString("dd/MM HH:mm")</td>
                                    </tr>
                                }
                            </tbody></table>
                        </div>
                    </div>
                }
                else
                {
                    @RenderEmpty("layout-dashboard", "#3B82F6", "Chào mừng đến cửa hàng!", "Bắt đầu bán hàng qua POS để xem dữ liệu tại đây", "monitor", "Mở POS", $"/pos/{ShopId}/{_posVertical}")
                }
                @* Shop Info Edit *@
                <div class="admin-panel" style="margin-top:20px;">
                    <div class="admin-panel__header">
                        <h3 class="admin-panel__title">Thông tin cửa hàng</h3>
                        @if (!_editingShop)
                        {
                            <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick="StartEditShop">
                                <i data-lucide="pencil" style="width:16px;height:16px;"></i>Chỉnh sửa
                            </button>
                        }
                    </div>
                    @if (_editingShop)
                    {
                        <div style="padding:16px;">
                            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                                <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Tên cửa hàng</label><input @bind="_shopEditName" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                                <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Số điện thoại</label><input @bind="_shopEditPhone" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                                <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Email</label><input @bind="_shopEditEmail" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                                <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Mô tả</label><input @bind="_shopEditDesc" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                                <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Giờ mở cửa</label><input @bind="_shopEditOpenTime" placeholder="08:00" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                                <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Giờ đóng cửa</label><input @bind="_shopEditCloseTime" placeholder="22:00" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                            </div>
                            <div style="display:flex;gap:8px;margin-top:16px;">
                                <button class="admin-btn-primary" @onclick="SaveShopEdit" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>Lưu</button>
                                <button @onclick="@(() => _editingShop = false)" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;"><i data-lucide="x" style="width:14px;height:14px;"></i>Hủy</button>
                            </div>
                            @if (_shopEditMessage != null) { <div style="margin-top:8px;padding:8px 12px;border-radius:6px;font-size:13px;@(_shopEditSuccess ? "color:#22C55E;background:rgba(34,197,94,0.1);" : "color:#EF4444;background:rgba(239,68,68,0.1);")">@_shopEditMessage</div> }
                        </div>
                    }
                    else
                    {
                        <div style="padding:16px;color:var(--admin-text-secondary);font-size:13px;">@(_shopName ?? "—") — Nhấn "Chỉnh sửa" để cập nhật thông tin.</div>
                    }
                </div>
                break;

            // ═══ EXTRACTED COMPONENTS ═══
            case "menu":
            case "products":
                <ShopMenu ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "inventory":
                <ShopInventory ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "finance":
                <ShopFinance ShopId="@(_shopGuid ?? Guid.Empty)" PosVertical="@_posVertical" />
                break;

            case "staff":
                <ShopStaff ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "customers":
                <ShopCustomers ShopGuid="@(_shopGuid ?? Guid.Empty)" ShopId="@ShopId" PosVertical="@_posVertical" />
                break;

            case "tables":
                <ShopTables ShopId="@(_shopGuid ?? Guid.Empty)" SubSection="tables" />
                break;

            case "rooms":
                <ShopTables ShopId="@(_shopGuid ?? Guid.Empty)" SubSection="rooms" />
                break;

            case "zones":
                <ShopTables ShopId="@(_shopGuid ?? Guid.Empty)" SubSection="zones" />
                break;

            case "appointments":
                <ShopAppointments ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "therapists":
                <ShopTherapists ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "kitchen":
                <ShopKitchen ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "resources":
                <ShopResources ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "reports":
                <ShopReports ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "recipes":
                <ShopRecipes ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "promotions":
                <ShopPromotions />
                break;

            case "settings":
                <ShopSettings ShopId="@(_shopGuid ?? Guid.Empty)" ShopName="@_shopName" VerticalLabel="@_verticalLabel" ShopStatus="@_shopStatus" />
                break;

            case "receipt-templates":
                <ReceiptTemplates ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "schedule":
                <ShopSchedule ShopId="@(_shopGuid ?? Guid.Empty)" SubSection="schedule" />
                break;

            case "shifts":
                <ShopSchedule ShopId="@(_shopGuid ?? Guid.Empty)" SubSection="shifts" />
                break;

            case "ai-chat":
                <ShopAiChat ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "drive":
                <ShopDrive />
                break;

            // ═══ SERVICES (reuses products, keep inline) ═══
            case "services":
                @if (!_serviceProducts.Any())
                {
                    @RenderEmpty("sparkles", "#EC4899", "Chưa có dịch vụ", "Thêm dịch vụ trong mục Menu/Sản phẩm", "coffee", "Quản lý sản phẩm", $"/admin/shop/{ShopId}/menu")
                }
                else
                {
                    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
                        @foreach (var p in _serviceProducts)
                        {
                            <div class="admin-panel">
                                <div class="admin-panel__body" style="padding:16px;text-align:center;">
                                    <div style="width:48px;height:48px;border-radius:12px;background:rgba(236,72,153,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;"><i data-lucide="sparkles" style="color:#EC4899;width:24px;height:24px;"></i></div>
                                    <div style="font-weight:600;font-size:14px;margin-bottom:4px;">@p.Name</div>
                                    <div style="font-weight:700;color:var(--admin-orange-primary);margin-top:8px;">@p.Price.ToString("N0")₫</div>
                                </div>
                            </div>
                        }
                    </div>
                }
                break;

            // ═══ POS redirect ═══
            case "pos":
                <div class="admin-panel">
                    <div class="admin-panel__body" style="text-align:center;padding:40px;">
                        <p style="margin-bottom:16px;">Mở POS bán hàng</p>
                        <a href="/pos/@ShopId/@_posVertical" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
                            <i data-lucide="monitor" style="width:16px;height:16px;"></i>Mở POS
                        </a>
                    </div>
                </div>
                break;

            // ═══ STUB SECTIONS ═══
            case "treatments":
                @RenderStubSection("clipboard-list", "#A855F7", "Liệu trình", "Theo dõi liệu trình điều trị — tính năng đang phát triển.")
                break;

            case "reservations":
                <ShopReservations ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "happy-hour":
                <ShopHappyHour ShopId="@(_shopGuid ?? Guid.Empty)" />
                break;

            case "packages":
                @RenderStubSection("gift", "#8B5CF6", "Gói dịch vụ", "Quản lý gói combo dịch vụ — tính năng đang phát triển.")
                break;

            case "consent":
                @RenderStubSection("file-check", "#EC4899", "Cam kết KH", "Biểu mẫu đồng ý khách hàng — tính năng đang phát triển.")
                break;

            case "doctors":
                @RenderStubSection("stethoscope", "#3B82F6", "Bác sĩ / CK", "Quản lý bác sĩ và chuyên gia — tính năng đang phát triển.")
                break;

            case "followup":
                @RenderStubSection("calendar-heart", "#EC4899", "Tái khám", "Lịch tái khám sau điều trị — tính năng đang phát triển.")
                break;

            case "combos":
                @RenderStubSection("layers", "#A855F7", "Combo dịch vụ", "Quản lý combo dịch vụ — tính năng đang phát triển.")
                break;

            // ═══ UNKNOWN SECTIONS ═══
            default:
                <div class="admin-panel">
                    <div class="admin-panel__body" style="text-align:center;padding:60px 20px;">
                        <div style="width:80px;height:80px;border-radius:24px;background:rgba(255,92,0,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                            <i data-lucide="@_sectionIcon" style="width:36px;height:36px;color:var(--admin-orange-primary);"></i>
                        </div>
                        <h2 style="font-size:22px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFFFFF);">@_sectionTitle</h2>
                        <p style="font-size:13px;color:#F59E0B;font-weight:600;margin:0 0 8px;">Tính năng đang phát triển</p>
                        <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;max-width:420px;margin-left:auto;margin-right:auto;">@_sectionDescription</p>
                        <div style="display:inline-flex;align-items:center;gap:8px;padding:8px 16px;border-radius:10px;background:rgba(245,158,11,0.1);border:1px solid rgba(245,158,11,0.25);">
                            <i data-lucide="clock" style="width:14px;height:14px;color:#F59E0B;"></i>
                            <span style="font-size:12px;color:#F59E0B;font-weight:600;">Sẽ ra mắt trong phiên bản tiếp theo</span>
                        </div>
                    </div>
                </div>
                break;
        }
    }
</div>

@if (!string.IsNullOrEmpty(_toastMessage))
{
    <div style="position:fixed;bottom:24px;right:24px;background:#1a1a2e;color:#fff;padding:12px 20px;border-radius:8px;font-size:13px;z-index:9999;box-shadow:0 4px 12px rgba(0,0,0,0.3);border-left:3px solid #ff5c00;">
        @_toastMessage
    </div>
}

@code {
    [Parameter] public string ShopId { get; set; } = "";
    [Parameter] public string Section { get; set; } = "";
    [CascadingParameter] public AdminLayout? AdminLayoutRef { get; set; }

    private string _shopName = "";
    private string _verticalLabel = "";
    private string? _shopStatus;
    private string _section = "";
    private string _sectionTitle = "";
    private string _sectionIcon = "layout-dashboard";
    private string _sectionDescription = "";
    private string? _errorMessage;
    private string _posVertical = "cafe";
    private Guid? _shopGuid;
    private bool _showNotifications;
    private string? _toastMessage;

    // Overview data
    private List<PosDataService.OrderInfo> _ovOrders = new();
    private List<PosDataService.AdminProductInfo> _ovProducts = new();
    private List<PosDataService.StaffInfo> _ovStaff = new();
    private List<PosDataService.TableInfo> _ovTables = new();
    private List<PosDataService.AppointmentInfo> _ovAppts = new();

    // Services section (reuses products)
    private List<PosDataService.AdminProductInfo> _serviceProducts = new();

    // Shop edit state
    private bool _editingShop;
    private string _shopEditName = "";
    private string _shopEditPhone = "";
    private string _shopEditEmail = "";
    private string _shopEditDesc = "";
    private string _shopEditOpenTime = "";
    private string _shopEditCloseTime = "";
    private string? _shopEditMessage;
    private bool _shopEditSuccess;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await LoadData();
    }

    protected override async Task OnParametersSetAsync()
    {
        if (_section != (Section?.ToLowerInvariant() ?? ""))
            await LoadData();
    }

    private async Task LoadData()
    {
        IsLoading = true;
        _errorMessage = null;
        _section = Section?.ToLowerInvariant() ?? "";
        ConfigureSection();

        try
        {
            _shopGuid = Guid.TryParse(ShopId, out var id) ? id : null;
            if (_shopGuid.HasValue)
            {
                var shop = await DataService.GetShopByIdAsync(_shopGuid.Value);
                if (shop != null)
                {
                    _shopName = shop.Name ?? "Cửa hàng";
                    _verticalLabel = ShopSidebarConfig.GetVerticalLabel(shop.Category);
                    _shopStatus = shop.Status;
                    _posVertical = MapCategoryToVertical(shop.Category);
                    AdminLayoutRef?.SetShopContext(ShopId, _shopName, shop.Category);
                }
            }

            // Only load data needed for sections handled directly by shell
            switch (_section)
            {
                case "overview":
                    _ovOrders = await DataService.GetOrdersAsync(_shopGuid);
                    _ovProducts = await DataService.GetAllProductsAsync(_shopGuid);
                    _ovStaff = await DataService.GetStaffForShopAsync(_shopGuid!.Value);
                    if (_shopGuid.HasValue && (_posVertical == "restaurant" || _posVertical == "karaoke"))
                        _ovTables = await DataService.GetTablesAsync(_shopGuid.Value);
                    if (_shopGuid.HasValue && (_posVertical == "spa" || _posVertical == "beauty"))
                        _ovAppts = await DataService.GetAppointmentsAsync(_shopGuid.Value);
                    break;
                case "services":
                    _serviceProducts = await DataService.GetAllProductsAsync(_shopGuid);
                    break;
                // All other sections are handled by child components with their own OnInitializedAsync
            }
        }
        catch (Exception ex)
        {
            _errorMessage = $"Không thể tải dữ liệu: {ex.Message}";
            Console.Error.WriteLine($"[ShopPage] Error loading {_section}: {ex}");
        }
        finally { IsLoading = false; }
    }

    private void ConfigureSection()
    {
        switch (_section)
        {
            case "overview": _sectionTitle = "Tổng quan"; _sectionIcon = "layout-dashboard"; _sectionDescription = "Tổng quan hoạt động cửa hàng."; break;
            case "menu": _sectionTitle = "Menu / Sản phẩm"; _sectionIcon = "coffee"; _sectionDescription = "Quản lý danh mục, sản phẩm, giá."; break;
            case "products": _sectionTitle = "Sản phẩm"; _sectionIcon = "package"; _sectionDescription = "Quản lý sản phẩm."; break;
            case "inventory": _sectionTitle = "Tồn kho"; _sectionIcon = "warehouse"; _sectionDescription = "Theo dõi tồn kho, cảnh báo hết hàng."; break;
            case "finance": _sectionTitle = "Tài chính"; _sectionIcon = "trending-up"; _sectionDescription = "Doanh thu, đơn hàng, chi phí."; break;
            case "staff": _sectionTitle = "Nhân sự"; _sectionIcon = "users"; _sectionDescription = "Quản lý nhân viên cửa hàng."; break;
            case "customers": _sectionTitle = "Khách hàng"; _sectionIcon = "heart"; _sectionDescription = "Khách hàng & thành viên — dữ liệu chung cho tất cả cửa hàng."; break;
            case "pos": _sectionTitle = "POS Bán hàng"; _sectionIcon = "monitor"; _sectionDescription = "Mở giao diện bán hàng tại điểm."; break;
            case "tables": _sectionTitle = "Quản lý Bàn"; _sectionIcon = "grid-3x3"; _sectionDescription = "Sơ đồ bàn, khu vực phục vụ."; break;
            case "kitchen": _sectionTitle = "Bếp (Kitchen)"; _sectionIcon = "flame"; _sectionDescription = "Màn hình hiển thị đơn cho bếp."; break;
            case "rooms": _sectionTitle = "Phòng"; _sectionIcon = "door-open"; _sectionDescription = "Quản lý phòng karaoke."; break;
            case "appointments": _sectionTitle = "Lịch hẹn"; _sectionIcon = "calendar"; _sectionDescription = "Quản lý lịch hẹn khách hàng."; break;
            case "therapists": _sectionTitle = "Nhân viên trị liệu"; _sectionIcon = "user-check"; _sectionDescription = "Quản lý nhân viên trị liệu, chuyên môn và trạng thái."; break;
            case "services": _sectionTitle = "Dịch vụ"; _sectionIcon = "sparkles"; _sectionDescription = "Quản lý danh mục dịch vụ."; break;
            case "resources": _sectionTitle = "Tài nguyên"; _sectionIcon = "door-open"; _sectionDescription = "Quản lý phòng, giường, thiết bị."; break;
            case "treatments": _sectionTitle = "Liệu trình"; _sectionIcon = "clipboard-list"; _sectionDescription = "Theo dõi liệu trình điều trị."; break;
            case "promotions": _sectionTitle = "Khuyến mãi"; _sectionIcon = "tag"; _sectionDescription = "Chương trình khuyến mãi — dữ liệu chung cho tất cả cửa hàng."; break;
            case "settings": _sectionTitle = "Thiết lập"; _sectionIcon = "settings"; _sectionDescription = "Cài đặt cửa hàng."; break;
            case "reports": _sectionTitle = "Báo cáo"; _sectionIcon = "bar-chart-2"; _sectionDescription = "Doanh thu, sản phẩm bán chạy."; break;
            case "schedule": _sectionTitle = "Lịch làm việc"; _sectionIcon = "calendar-clock"; _sectionDescription = "Lịch ca làm việc nhân viên."; break;
            case "recipes": _sectionTitle = "Nguyên liệu & Công thức"; _sectionIcon = "flask-conical"; _sectionDescription = "Quản lý nguyên liệu pha chế."; break;
            case "reservations": _sectionTitle = "Đặt bàn"; _sectionIcon = "calendar-check"; _sectionDescription = "Quản lý đặt bàn trước."; break;
            case "happy-hour": _sectionTitle = "Happy Hour"; _sectionIcon = "clock"; _sectionDescription = "Cấu hình khung giờ giảm giá."; break;
            case "packages": _sectionTitle = "Gói dịch vụ"; _sectionIcon = "gift"; _sectionDescription = "Quản lý gói combo dịch vụ."; break;
            case "consent": _sectionTitle = "Cam kết KH"; _sectionIcon = "file-check"; _sectionDescription = "Biểu mẫu đồng ý khách hàng."; break;
            case "doctors": _sectionTitle = "Bác sĩ / CK"; _sectionIcon = "stethoscope"; _sectionDescription = "Quản lý bác sĩ và chuyên gia."; break;
            case "followup": _sectionTitle = "Tái khám"; _sectionIcon = "calendar-heart"; _sectionDescription = "Lịch tái khám sau điều trị."; break;
            case "zones": _sectionTitle = "Khu vực"; _sectionIcon = "map-pin"; _sectionDescription = "Quản lý khu vực phục vụ."; break;
            case "combos": _sectionTitle = "Combo dịch vụ"; _sectionIcon = "layers"; _sectionDescription = "Quản lý combo dịch vụ."; break;
            case "shifts": _sectionTitle = "Ca làm việc"; _sectionIcon = "clock-4"; _sectionDescription = "Lịch ca làm, phân ca."; break;
            case "ai-chat": _sectionTitle = "AI Assistant"; _sectionIcon = "bot"; _sectionDescription = "Trợ lý AI — tương tác với hệ thống POS qua chat."; break;
            case "drive": _sectionTitle = "Lưu trữ"; _sectionIcon = "hard-drive"; _sectionDescription = "Quản lý tệp và thư mục."; break;
            case "receipt-templates": _sectionTitle = "Template Hoá đơn"; _sectionIcon = "receipt"; _sectionDescription = "Quản lý mẫu hoá đơn in."; break;
            default: _sectionTitle = Section ?? "Trang"; _sectionIcon = "layout-dashboard"; _sectionDescription = "Trang đang phát triển."; break;
        }
    }

    private static string MapCategoryToVertical(string? category) => (category?.ToLowerInvariant()) switch
    {
        "cafe" or "coffee" => "cafe",
        "restaurant" or "nhahang" => "restaurant",
        "karaoke" => "karaoke",
        "spa" => "spa",
        "beauty" or "salon" => "beauty",
        "retail" or "banle" => "retail",
        _ => "cafe"
    };

    private RenderFragment RenderEmpty(string icon, string color, string title, string desc, string? ctaIcon = null, string? ctaLabel = null, string? ctaHref = null) => __builder =>
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:@($"rgba({ShopHelpers.HexToRgb(color)},0.1)");display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="@icon" style="width:36px;height:36px;color:@color;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">@title</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">@desc</p>
            @if (ctaIcon != null && ctaLabel != null)
            {
                <a href="@(ctaHref ?? $"/admin/shop/{ShopId}/menu")" class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;text-decoration:none;">
                    <i data-lucide="@ctaIcon" style="width:16px;height:16px;"></i>
                    @ctaLabel
                </a>
            }
        </div>
    };

    private RenderFragment RenderStubSection(string icon, string color, string title, string desc) => __builder =>
    {
        <div class="admin-panel">
            <div class="admin-panel__body" style="text-align:center;padding:60px 20px;">
                <div style="width:80px;height:80px;border-radius:24px;background:@($"rgba({ShopHelpers.HexToRgb(color)},0.1)");display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                    <i data-lucide="@icon" style="width:36px;height:36px;color:@color;"></i>
                </div>
                <h2 style="font-size:22px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFFFFF);">@title</h2>
                <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;max-width:420px;margin-left:auto;margin-right:auto;">@desc</p>
                <div style="display:inline-flex;align-items:center;gap:8px;padding:8px 16px;border-radius:10px;background:rgba(245,158,11,0.1);border:1px solid rgba(245,158,11,0.25);">
                    <i data-lucide="clock" style="width:14px;height:14px;color:#F59E0B;"></i>
                    <span style="font-size:12px;color:#F59E0B;font-weight:600;">Sẽ ra mắt trong phiên bản tiếp theo</span>
                </div>
            </div>
        </div>
    };

    private void StartEditShop() { _editingShop = true; _shopEditName = _shopName ?? ""; _shopEditPhone = ""; _shopEditEmail = ""; _shopEditDesc = ""; _shopEditOpenTime = ""; _shopEditCloseTime = ""; _shopEditMessage = null; }

    private async Task SaveShopEdit()
    {
        var req = new PosDataService.UpdateShopRequest(_shopEditName, _shopEditPhone, _shopEditEmail, _shopEditDesc, _shopEditOpenTime, _shopEditCloseTime, null);
        var ok = await DataService.UpdateShopAsync(_shopGuid!.Value, req);
        _shopEditMessage = ok ? "Đã cập nhật cửa hàng!" : "Lỗi khi cập nhật.";
        _shopEditSuccess = ok;
        if (ok) { _editingShop = false; await LoadData(); }
    }

    private async void ShowComingSoon(string feature)
    {
        _toastMessage = $"{feature} — tính năng sắp ra mắt!";
        StateHasChanged();
        await Task.Delay(3000);
        _toastMessage = null;
        StateHasChanged();
    }
}
