@page "/admin/settings"
@layout AdminLayout
@inherits AdminBase
@inject WebClientTpos.Client.Services.AuthStateService AuthState
@inject WebClientTpos.Client.Services.PosDataService DataService
@inject IJSRuntime JS
@inject NavigationManager Nav

@*
    EN: Admin settings page — account, security, subscription, notifications, system overview.
    VI: Trang cài đặt admin — tài khoản, bảo mật, gói dịch vụ, thông báo, tổng quan hệ thống.
*@

<PageTitle>Cài đặt — aPOS Admin</PageTitle>

@* ═══ TOP BAR ═══ *@
<div class="admin-topbar">
    <div class="admin-topbar__left">
        <h1 class="admin-topbar__title">Cài đặt</h1>
        <p class="admin-topbar__subtitle">Quản lý tài khoản và cấu hình hệ thống</p>
    </div>
</div>

@* ═══ TABS ═══ *@
<div class="admin-tabs">
    <button class="admin-tab @(_tab == "account" ? "admin-tab--active" : "")" @onclick="@(() => SwitchTab("account"))">
        <i data-lucide="user" style="width:14px;height:14px;"></i> Tài khoản
    </button>
    <button class="admin-tab @(_tab == "security" ? "admin-tab--active" : "")" @onclick="@(() => SwitchTab("security"))">
        <i data-lucide="lock" style="width:14px;height:14px;"></i> Bảo mật
    </button>
    <button class="admin-tab @(_tab == "subscription" ? "admin-tab--active" : "")" @onclick="@(() => SwitchTab("subscription"))">
        <i data-lucide="crown" style="width:14px;height:14px;"></i> Gói dịch vụ
    </button>
    <button class="admin-tab @(_tab == "notifications" ? "admin-tab--active" : "")" @onclick="@(() => SwitchTab("notifications"))">
        <i data-lucide="bell" style="width:14px;height:14px;"></i> Thông báo
    </button>
    <button class="admin-tab @(_tab == "general" ? "admin-tab--active" : "")" @onclick="@(() => SwitchTab("general"))">
        <i data-lucide="settings" style="width:14px;height:14px;"></i> Hệ thống
    </button>
</div>

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

    @* ════════════════════════════════════════════════════════════════════
       TAB: TÀI KHOẢN — Profile + Merchant Info
       ════════════════════════════════════════════════════════════════════ *@
    @if (_tab == "account")
    {
        @* ── Profile Info ── *@
        <div class="admin-panel">
            <div class="admin-panel__header" style="display:flex;justify-content:space-between;align-items:center;">
                <h3 class="admin-panel__title">
                    <i data-lucide="user" style="color:var(--admin-orange-primary);"></i>
                    Thông tin cá nhân
                </h3>
                @if (!_editingProfile)
                {
                    <button class="admin-btn-secondary" style="font-size:12px;padding:6px 14px;" @onclick="StartEditProfile">
                        <i data-lucide="pencil" style="width:12px;height:12px;"></i> Chỉnh sửa
                    </button>
                }
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
                @if (_loadingAccount)
                {
                    <div style="text-align:center;padding:24px;"><MudProgressCircular Indeterminate="true" Size="Size.Small" Color="Color.Primary" /></div>
                }
                else
                {
                    <div style="display:flex;align-items:center;gap:20px;padding-bottom:16px;border-bottom:1px solid var(--admin-border-subtle);">
                        <div style="width:72px;height:72px;border-radius:50%;background:linear-gradient(135deg,var(--admin-orange-primary),#F59E0B);display:flex;align-items:center;justify-content:center;font-size:28px;font-weight:700;color:white;">
                            @(string.IsNullOrEmpty(_firstName) ? (AuthState.UserEmail?[..1].ToUpper() ?? "U") : _firstName[..1].ToUpper())
                        </div>
                        <div>
                            <div style="font-size:18px;font-weight:700;color:var(--admin-text-primary);">
                                @(string.IsNullOrEmpty(_firstName) && string.IsNullOrEmpty(_lastName)
                                    ? (AuthState.UserEmail ?? "—")
                                    : $"{_firstName} {_lastName}".Trim())
                            </div>
                            <div style="font-size:13px;color:var(--admin-text-tertiary);">@(AuthState.UserEmail ?? "—")</div>
                            <div class="admin-status-badge admin-status-badge--online" style="width:fit-content;margin-top:4px;">
                                <span class="admin-status-badge__dot"></span> Chủ doanh nghiệp
                            </div>
                        </div>
                    </div>

                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                        <div class="admin-form-group">
                            <label class="admin-form-label">Họ</label>
                            <input class="admin-form-input" @bind="_lastName" readonly="@(!_editingProfile)" />
                        </div>
                        <div class="admin-form-group">
                            <label class="admin-form-label">Tên</label>
                            <input class="admin-form-input" @bind="_firstName" readonly="@(!_editingProfile)" />
                        </div>
                        <div class="admin-form-group">
                            <label class="admin-form-label">Email</label>
                            <input class="admin-form-input" value="@(AuthState.UserEmail ?? "—")" readonly />
                        </div>
                        <div class="admin-form-group">
                            <label class="admin-form-label">Múi giờ</label>
                            <input class="admin-form-input" @bind="_timezone" readonly="@(!_editingProfile)" />
                        </div>
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Giới thiệu</label>
                        <textarea class="admin-form-input" rows="2" @bind="_bio" readonly="@(!_editingProfile)" style="resize:vertical;"></textarea>
                    </div>

                    @if (_editingProfile)
                    {
                        <div style="display:flex;gap:8px;justify-content:flex-end;">
                            <button class="admin-btn-secondary" style="font-size:12px;padding:6px 14px;" @onclick="CancelEditProfile">Hủy</button>
                            <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick="SaveProfile" disabled="@_saving">
                                @if (_saving) { <MudProgressCircular Indeterminate="true" Size="Size.Small" Color="Color.Surface" Style="width:14px;height:14px;" /> }
                                else { <span>Lưu thay đổi</span> }
                            </button>
                        </div>
                    }

                    @if (!string.IsNullOrEmpty(_profileMsg))
                    {
                        <div style="padding:8px 12px;border-radius:8px;font-size:12px;background:@(_profileMsgOk ? "rgba(34,197,94,0.12)" : "rgba(239,68,68,0.12)");color:@(_profileMsgOk ? "#22C55E" : "#EF4444");">
                            @_profileMsg
                        </div>
                    }
                }
            </div>
        </div>

        @* ── Merchant Info ── *@
        <div class="admin-panel">
            <div class="admin-panel__header" style="display:flex;justify-content:space-between;align-items:center;">
                <h3 class="admin-panel__title">
                    <i data-lucide="building-2" style="color:#8B5CF6;"></i>
                    Thông tin doanh nghiệp
                </h3>
                @if (!_editingMerchant)
                {
                    <button class="admin-btn-secondary" style="font-size:12px;padding:6px 14px;" @onclick="() => _editingMerchant = true">
                        <i data-lucide="pencil" style="width:12px;height:12px;"></i> Chỉnh sửa
                    </button>
                }
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                    <div class="admin-form-group">
                        <label class="admin-form-label">Tên doanh nghiệp</label>
                        <input class="admin-form-input" @bind="_businessName" readonly="@(!_editingMerchant)" />
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Loại hình</label>
                        <input class="admin-form-input" value="@_merchantType" readonly />
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Mã số thuế</label>
                        <input class="admin-form-input" @bind="_taxId" readonly="@(!_editingMerchant)" placeholder="Nhập MST..." />
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Trạng thái xác minh</label>
                        <div class="admin-status-badge @(_verificationStatus == "Verified" ? "admin-status-badge--online" : "admin-status-badge--warning")" style="width:fit-content;">
                            <span class="admin-status-badge__dot"></span>
                            @(_verificationStatus == "Verified" ? "Đã xác minh" : _verificationStatus == "Pending" ? "Đang chờ" : "Chưa xác minh")
                        </div>
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Số cửa hàng</label>
                        <input class="admin-form-input" value="@_shopCount" readonly />
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Ngày đăng ký</label>
                        <input class="admin-form-input" value="@_merchantCreatedAt" readonly />
                    </div>
                </div>

                @if (_editingMerchant)
                {
                    <div style="display:flex;gap:8px;justify-content:flex-end;">
                        <button class="admin-btn-secondary" style="font-size:12px;padding:6px 14px;" @onclick="() => _editingMerchant = false">Hủy</button>
                        <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick="SaveMerchant" disabled="@_saving">Lưu</button>
                    </div>
                }

                @if (!string.IsNullOrEmpty(_merchantMsg))
                {
                    <div style="padding:8px 12px;border-radius:8px;font-size:12px;background:@(_merchantMsgOk ? "rgba(34,197,94,0.12)" : "rgba(239,68,68,0.12)");color:@(_merchantMsgOk ? "#22C55E" : "#EF4444");">
                        @_merchantMsg
                    </div>
                }
            </div>
        </div>
    }

    @* ════════════════════════════════════════════════════════════════════
       TAB: BẢO MẬT — Password, 2FA, Sessions
       ════════════════════════════════════════════════════════════════════ *@
    else if (_tab == "security")
    {
        @* ── Change Password ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">
                    <i data-lucide="key" style="color:var(--admin-orange-primary);"></i>
                    Đổi mật khẩu
                </h3>
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                    <div class="admin-form-group">
                        <label class="admin-form-label">Mật khẩu hiện tại</label>
                        <input class="admin-form-input" type="password" @bind="_currentPassword" placeholder="••••••••" />
                    </div>
                    <div></div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Mật khẩu mới</label>
                        <input class="admin-form-input" type="password" @bind="_newPassword" placeholder="Tối thiểu 8 ký tự" />
                    </div>
                    <div class="admin-form-group">
                        <label class="admin-form-label">Xác nhận mật khẩu mới</label>
                        <input class="admin-form-input" type="password" @bind="_confirmPassword" placeholder="Nhập lại mật khẩu mới" />
                    </div>
                </div>
                <div style="display:flex;justify-content:flex-end;">
                    <button class="admin-btn-primary" style="font-size:12px;padding:8px 20px;" @onclick="ChangePassword" disabled="@_saving">
                        Đổi mật khẩu
                    </button>
                </div>
                @if (!string.IsNullOrEmpty(_pwMsg))
                {
                    <div style="padding:8px 12px;border-radius:8px;font-size:12px;background:@(_pwMsgOk ? "rgba(34,197,94,0.12)" : "rgba(239,68,68,0.12)");color:@(_pwMsgOk ? "#22C55E" : "#EF4444");">@_pwMsg</div>
                }
            </div>
        </div>

        @* ── 2FA ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">
                    <i data-lucide="shield-check" style="color:#22C55E;"></i>
                    Xác thực 2 bước (2FA)
                </h3>
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
                <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 14px;background:var(--admin-bg-interactive);border-radius:10px;">
                    <div>
                        <span style="font-size:13px;font-weight:600;">Trạng thái 2FA</span>
                        <p style="font-size:11px;color:var(--admin-text-tertiary);margin:0;">Bảo mật tài khoản bằng mã OTP từ ứng dụng Authenticator</p>
                    </div>
                    @if (_twoFactorEnabled)
                    {
                        <div style="display:flex;align-items:center;gap:8px;">
                            <div class="admin-status-badge admin-status-badge--online"><span class="admin-status-badge__dot"></span> Đã bật</div>
                            <button class="admin-btn-secondary" style="font-size:11px;padding:4px 10px;color:#EF4444;" @onclick="StartDisable2FA">Tắt 2FA</button>
                        </div>
                    }
                    else
                    {
                        <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick="StartEnable2FA" disabled="@_saving">Bật 2FA</button>
                    }
                </div>

                @if (_show2FASetup)
                {
                    <div style="padding:16px;background:var(--admin-bg-interactive);border-radius:10px;display:flex;flex-direction:column;gap:12px;">
                        <p style="font-size:13px;color:var(--admin-text-secondary);margin:0;">Quét mã QR bằng Google Authenticator hoặc Authy:</p>
                        @if (!string.IsNullOrEmpty(_qrCodeBase64))
                        {
                            <div style="text-align:center;">
                                <img src="@_qrCodeBase64" alt="QR Code" style="width:180px;height:180px;border-radius:8px;background:white;padding:8px;" />
                            </div>
                        }
                        @if (!string.IsNullOrEmpty(_manualKey))
                        {
                            <div style="font-size:11px;color:var(--admin-text-tertiary);text-align:center;">
                                Mã thủ công: <code style="background:var(--admin-bg-elevated);padding:2px 6px;border-radius:4px;">@_manualKey</code>
                            </div>
                        }
                        <div class="admin-form-group" style="max-width:300px;margin:0 auto;">
                            <label class="admin-form-label">Nhập mã 6 số từ app:</label>
                            <input class="admin-form-input" @bind="_totpCode" placeholder="000000" maxlength="6" style="text-align:center;font-size:20px;letter-spacing:8px;" />
                        </div>
                        <div style="display:flex;gap:8px;justify-content:center;">
                            <button class="admin-btn-secondary" style="font-size:12px;" @onclick="() => _show2FASetup = false">Hủy</button>
                            <button class="admin-btn-primary" style="font-size:12px;" @onclick="Verify2FA" disabled="@_saving">Xác nhận</button>
                        </div>
                    </div>
                }

                @if (_showDisable2FA)
                {
                    <div style="padding:16px;background:var(--admin-bg-interactive);border-radius:10px;display:flex;flex-direction:column;gap:12px;">
                        <p style="font-size:13px;color:var(--admin-text-secondary);margin:0;">Nhập mã OTP hiện tại để tắt 2FA:</p>
                        <div class="admin-form-group" style="max-width:300px;margin:0 auto;">
                            <input class="admin-form-input" @bind="_totpCode" placeholder="000000" maxlength="6" style="text-align:center;font-size:20px;letter-spacing:8px;" />
                        </div>
                        <div style="display:flex;gap:8px;justify-content:center;">
                            <button class="admin-btn-secondary" style="font-size:12px;" @onclick="() => _showDisable2FA = false">Hủy</button>
                            <button class="admin-btn-primary" style="font-size:12px;background:#EF4444;" @onclick="Disable2FA" disabled="@_saving">Tắt 2FA</button>
                        </div>
                    </div>
                }

                @if (!string.IsNullOrEmpty(_tfaMsg))
                {
                    <div style="padding:8px 12px;border-radius:8px;font-size:12px;background:@(_tfaMsgOk ? "rgba(34,197,94,0.12)" : "rgba(239,68,68,0.12)");color:@(_tfaMsgOk ? "#22C55E" : "#EF4444");">@_tfaMsg</div>
                }
            </div>
        </div>

        @* ── Linked Accounts ── *@
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">
                    <i data-lucide="link" style="color:#3B82F6;"></i>
                    Tài khoản liên kết
                </h3>
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:10px;">
                <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 14px;background:var(--admin-bg-interactive);border-radius:10px;">
                    <div style="display:flex;align-items:center;gap:10px;">
                        <div style="width:28px;height:28px;border-radius:6px;background:#4285F4;display:flex;align-items:center;justify-content:center;">
                            <span style="color:white;font-weight:700;font-size:14px;">G</span>
                        </div>
                        <span style="font-size:13px;font-weight:500;">Google</span>
                    </div>
                    <span style="font-size:12px;color:var(--admin-text-tertiary);">@(_linkedGoogle ? "Đã liên kết" : "Chưa liên kết")</span>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 14px;background:var(--admin-bg-interactive);border-radius:10px;">
                    <div style="display:flex;align-items:center;gap:10px;">
                        <div style="width:28px;height:28px;border-radius:6px;background:#1877F2;display:flex;align-items:center;justify-content:center;">
                            <span style="color:white;font-weight:700;font-size:14px;">f</span>
                        </div>
                        <span style="font-size:13px;font-weight:500;">Facebook</span>
                    </div>
                    <span style="font-size:12px;color:var(--admin-text-tertiary);">@(_linkedFacebook ? "Đã liên kết" : "Chưa liên kết")</span>
                </div>
            </div>
        </div>

        @* ── Danger Zone ── *@
        <div class="admin-panel" style="border:1px solid rgba(239,68,68,0.3);">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title" style="color:#EF4444;">
                    <i data-lucide="alert-triangle" style="color:#EF4444;"></i>
                    Vùng nguy hiểm
                </h3>
            </div>
            <div class="admin-panel__body">
                <div style="display:flex;justify-content:space-between;align-items:center;">
                    <div>
                        <span style="font-size:13px;font-weight:600;">Xóa tài khoản</span>
                        <p style="font-size:11px;color:var(--admin-text-tertiary);margin:0;">Xóa vĩnh viễn tài khoản và toàn bộ dữ liệu</p>
                    </div>
                    <button class="admin-btn-secondary" style="font-size:12px;padding:6px 12px;color:#EF4444;border-color:rgba(239,68,68,0.3);">Xóa tài khoản</button>
                </div>
            </div>
        </div>
    }

    @* ════════════════════════════════════════════════════════════════════
       TAB: GÓI DỊCH VỤ — Subscription plans
       ════════════════════════════════════════════════════════════════════ *@
    else if (_tab == "subscription")
    {
        @* ── Current Plan ── *@
        <div class="admin-panel" style="border:2px solid var(--admin-orange-primary);">
            <div class="admin-panel__header" style="display:flex;justify-content:space-between;align-items:center;">
                <h3 class="admin-panel__title">
                    <i data-lucide="crown" style="color:var(--admin-orange-primary);"></i>
                    Gói hiện tại
                </h3>
                <div style="padding:4px 12px;border-radius:20px;background:var(--admin-orange-primary);color:white;font-size:11px;font-weight:700;">
                    @_currentPlanName
                </div>
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
                <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;">
                    <div style="padding:12px;background:var(--admin-bg-interactive);border-radius:10px;text-align:center;">
                        <div style="font-size:22px;font-weight:700;color:var(--admin-text-primary);">@_usageShops/@(FormatLimit(_limitShops))</div>
                        <div style="font-size:11px;color:var(--admin-text-tertiary);">Cửa hàng</div>
                    </div>
                    <div style="padding:12px;background:var(--admin-bg-interactive);border-radius:10px;text-align:center;">
                        <div style="font-size:22px;font-weight:700;color:var(--admin-text-primary);">@_usageStaff/@(FormatLimit(_limitStaff))</div>
                        <div style="font-size:11px;color:var(--admin-text-tertiary);">Nhân viên/shop</div>
                    </div>
                    <div style="padding:12px;background:var(--admin-bg-interactive);border-radius:10px;text-align:center;">
                        <div style="font-size:22px;font-weight:700;color:var(--admin-text-primary);">@_usageVerticals/@(FormatLimit(_limitVerticals))</div>
                        <div style="font-size:11px;color:var(--admin-text-tertiary);">Ngành nghề</div>
                    </div>
                    <div style="padding:12px;background:var(--admin-bg-interactive);border-radius:10px;text-align:center;">
                        <div style="font-size:22px;font-weight:700;color:var(--admin-text-primary);">@_usageProducts/@(FormatLimit(_limitProducts))</div>
                        <div style="font-size:11px;color:var(--admin-text-tertiary);">Sản phẩm</div>
                    </div>
                </div>
            </div>
        </div>

        @* ── Plan Comparison ── *@
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;">
            @foreach (var plan in _plans)
            {
                var isCurrent = plan.Id == _currentPlanId;
                <div class="admin-panel" style="@(isCurrent ? "border:2px solid var(--admin-orange-primary);" : "") display:flex;flex-direction:column;">
                    <div class="admin-panel__header" style="text-align:center;">
                        @if (plan.Id == 2)
                        {
                            <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--admin-orange-primary);margin-bottom:4px;">Phổ biến nhất</div>
                        }
                        <h3 style="font-size:16px;font-weight:700;margin:0;">@plan.Name</h3>
                        <div style="font-size:24px;font-weight:800;color:var(--admin-orange-primary);margin:8px 0;">
                            @(plan.Price == 0 ? "Miễn phí" : $"{plan.Price:N0}₫")
                        </div>
                        <div style="font-size:11px;color:var(--admin-text-tertiary);">@(plan.Price > 0 ? "/tháng" : "mãi mãi")</div>
                    </div>
                    <div class="admin-panel__body" style="flex:1;display:flex;flex-direction:column;gap:8px;font-size:12px;">
                        @foreach (var f in plan.Features)
                        {
                            <div style="display:flex;align-items:center;gap:6px;">
                                <i data-lucide="@(f.Included ? "check" : "x")" style="width:14px;height:14px;color:@(f.Included ? "#22C55E" : "var(--admin-text-tertiary)");flex-shrink:0;"></i>
                                <span style="color:@(f.Included ? "var(--admin-text-primary)" : "var(--admin-text-tertiary)");">@f.Label</span>
                            </div>
                        }
                        <div style="margin-top:auto;padding-top:12px;">
                            @if (isCurrent)
                            {
                                <button class="admin-btn-secondary" style="width:100%;justify-content:center;font-size:12px;" disabled>Gói hiện tại</button>
                            }
                            else if (plan.Id > _currentPlanId)
                            {
                                <button class="admin-btn-primary" style="width:100%;justify-content:center;font-size:12px;" @onclick="() => UpgradePlan(plan.Id)">
                                    Nâng cấp
                                </button>
                            }
                        </div>
                    </div>
                </div>
            }
        </div>
    }

    @* ════════════════════════════════════════════════════════════════════
       TAB: THÔNG BÁO
       ════════════════════════════════════════════════════════════════════ *@
    else if (_tab == "notifications")
    {
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">
                    <i data-lucide="bell" style="color:#F59E0B;"></i>
                    Cài đặt thông báo
                </h3>
            </div>
            <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:12px;">
                @foreach (var notif in _notifSettings)
                {
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 14px;background:var(--admin-bg-interactive);border-radius:10px;">
                        <div style="display:flex;flex-direction:column;">
                            <span style="font-size:13px;font-weight:600;">@notif.Label</span>
                            <span style="font-size:11px;color:var(--admin-text-tertiary);">@notif.Desc</span>
                        </div>
                        <MudSwitch T="bool" Value="notif.Enabled" Color="Color.Primary" />
                    </div>
                }
            </div>
        </div>
    }

    @* ════════════════════════════════════════════════════════════════════
       TAB: HỆ THỐNG
       ════════════════════════════════════════════════════════════════════ *@
    else if (_tab == "general")
    {
        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">
                    <i data-lucide="info" style="color:var(--admin-orange-primary);"></i>
                    Thông tin hệ thống
                </h3>
            </div>
            <div class="admin-panel__body" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div class="admin-form-group">
                    <label class="admin-form-label">Phiên bản</label>
                    <input class="admin-form-input" value="aPOS Admin v1.0.0" readonly />
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label">Môi trường</label>
                    <input class="admin-form-input" value="Development" readonly />
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label">Số cửa hàng</label>
                    <input class="admin-form-input" value="@_shopCount cửa hàng" readonly />
                </div>
                <div class="admin-form-group">
                    <label class="admin-form-label">Múi giờ</label>
                    <input class="admin-form-input" value="Asia/Ho_Chi_Minh (UTC+7)" readonly />
                </div>
            </div>
        </div>

        <div class="admin-panel">
            <div class="admin-panel__header">
                <h3 class="admin-panel__title">
                    <i data-lucide="activity" style="color:#22C55E;"></i>
                    Trạng thái dịch vụ
                </h3>
            </div>
            <div class="admin-panel__body" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;">
                @foreach (var svc in _services)
                {
                    <div style="display:flex;align-items:center;gap:10px;padding:12px 14px;background:var(--admin-bg-interactive);border-radius:10px;">
                        <i data-lucide="@svc.Icon" style="width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                        <span style="font-size:13px;font-weight:500;flex:1;">@svc.Name</span>
                        <div class="admin-status-badge admin-status-badge--online">
                            <span class="admin-status-badge__dot"></span>
                            Online
                        </div>
                    </div>
                }
            </div>
        </div>
    }
</div>

@code {
    private string _tab = "account";
    private int _shopCount = 0;
    private bool _loadingAccount = true;
    private bool _saving = false;

    // ═══ Account/Profile state ═══
    private string _firstName = "";
    private string _lastName = "";
    private string _bio = "";
    private string _timezone = "Asia/Ho_Chi_Minh";
    private bool _editingProfile = false;
    private string? _profileMsg;
    private bool _profileMsgOk;

    // ═══ Merchant state ═══
    private string _businessName = "";
    private string _merchantType = "Individual";
    private string _taxId = "";
    private string _verificationStatus = "Unverified";
    private string _merchantCreatedAt = "—";
    private bool _editingMerchant = false;
    private string? _merchantMsg;
    private bool _merchantMsgOk;

    // ═══ Security state ═══
    private string _currentPassword = "";
    private string _newPassword = "";
    private string _confirmPassword = "";
    private string? _pwMsg;
    private bool _pwMsgOk;
    private bool _twoFactorEnabled = false;
    private bool _show2FASetup = false;
    private bool _showDisable2FA = false;
    private string? _qrCodeBase64;
    private string? _manualKey;
    private string _totpCode = "";
    private string? _tfaMsg;
    private bool _tfaMsgOk;
    private bool _linkedGoogle = false;
    private bool _linkedFacebook = false;

    // ═══ Subscription state ═══
    private int _currentPlanId = 0;
    private string _currentPlanName = "Starter";
    private int _usageShops = 0, _limitShops = 1;
    private int _usageStaff = 0, _limitStaff = 3;
    private int _usageVerticals = 0, _limitVerticals = 1;
    private int _usageProducts = 0, _limitProducts = 50;

    /// <summary>
    /// EN: Format limit value, showing ∞ for unlimited (>= 9999).
    /// VI: Định dạng giới hạn, hiển thị ∞ cho không giới hạn (>= 9999).
    /// </summary>
    private string FormatLimit(int limit) => limit >= 9999 ? "∞" : limit.ToString();

    private readonly (string Name, string Icon)[] _services = new[]
    {
        ("IAM Service", "shield"), ("Merchant Service", "store"), ("Catalog Service", "package"),
        ("Order Service", "shopping-bag"), ("Inventory Service", "warehouse"), ("Wallet Service", "wallet"),
        ("Membership Service", "users"), ("Promotion Service", "tag"), ("Booking Service", "calendar"),
        ("F&B Engine", "utensils"), ("Storage Service", "hard-drive"),
    };

    private record NotifSetting(string Label, string Desc, bool Enabled);
    private readonly NotifSetting[] _notifSettings = new[]
    {
        new NotifSetting("Đơn hàng mới", "Thông báo khi có đơn hàng mới", true),
        new NotifSetting("Đơn hàng hủy", "Thông báo khi đơn hàng bị hủy", true),
        new NotifSetting("Hàng sắp hết", "Tồn kho dưới mức tối thiểu", true),
        new NotifSetting("Nhân viên check-in", "Nhân viên bắt đầu ca", false),
        new NotifSetting("Doanh thu bất thường", "Cảnh báo doanh thu", true),
        new NotifSetting("Email hàng tuần", "Báo cáo doanh thu hàng tuần", true),
    };

    // ═══ Subscription Plans (static) ═══
    private record PlanFeature(string Label, bool Included);
    private record PlanInfo(int Id, string Name, decimal Price, PlanFeature[] Features);
    private readonly PlanInfo[] _plans = new[]
    {
        new PlanInfo(0, "Starter", 0, new[]
        {
            new PlanFeature("1 cửa hàng", true), new PlanFeature("3 nhân viên/shop", true),
            new PlanFeature("50 sản phẩm", true), new PlanFeature("POS cơ bản", true),
            new PlanFeature("1 ngành nghề", true), new PlanFeature("Báo cáo cơ bản", true),
            new PlanFeature("Kitchen Display", false), new PlanFeature("Booking", false),
            new PlanFeature("Marketing CRM", false),
        }),
        new PlanInfo(1, "Growth", 299000, new[]
        {
            new PlanFeature("3 cửa hàng", true), new PlanFeature("10 nhân viên/shop", true),
            new PlanFeature("500 sản phẩm", true), new PlanFeature("POS đa ngành", true),
            new PlanFeature("2 ngành nghề", true), new PlanFeature("Báo cáo tiêu chuẩn", true),
            new PlanFeature("Kitchen Display", true), new PlanFeature("Booking", true),
            new PlanFeature("Marketing CRM", false),
        }),
        new PlanInfo(2, "Pro", 799000, new[]
        {
            new PlanFeature("10 cửa hàng", true), new PlanFeature("50 nhân viên/shop", true),
            new PlanFeature("Sản phẩm không giới hạn", true), new PlanFeature("POS đa ngành", true),
            new PlanFeature("4 ngành nghề", true), new PlanFeature("Báo cáo nâng cao", true),
            new PlanFeature("Kitchen Display", true), new PlanFeature("Booking", true),
            new PlanFeature("Marketing CRM + Chatbot", true),
        }),
        new PlanInfo(3, "Enterprise", 0, new[]
        {
            new PlanFeature("Không giới hạn cửa hàng", true), new PlanFeature("Không giới hạn nhân viên", true),
            new PlanFeature("Không giới hạn sản phẩm", true), new PlanFeature("Tất cả ngành nghề", true),
            new PlanFeature("White-label", true), new PlanFeature("API Access", true),
            new PlanFeature("SLA & Support ưu tiên", true), new PlanFeature("Báo cáo tùy chỉnh", true),
            new PlanFeature("Mọi tính năng", true),
        }),
    };

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

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

    private async Task LoadAccountData()
    {
        _loadingAccount = true;
        try
        {
            var shops = await DataService.GetShopsAsync();
            _shopCount = shops.Count;
            _usageShops = shops.Count;
        }
        catch { _shopCount = 0; }

        // EN: Load user profile from BFF
        // VI: Tải profile user từ BFF
        try
        {
            var me = await DataService.GetFromApiAsync<AccountMeDto>("api/bff/account/me");
            if (me != null)
            {
                _firstName = me.FirstName ?? "";
                _lastName = me.LastName ?? "";
            }
        }
        catch { }

        try
        {
            var profile = await DataService.GetFromApiAsync<ProfileDto>("api/bff/account/profile");
            if (profile != null)
            {
                _bio = profile.Bio ?? "";
                _timezone = profile.Timezone ?? "Asia/Ho_Chi_Minh";
            }
        }
        catch { }

        // EN: Load merchant profile
        // VI: Tải thông tin merchant
        try
        {
            var merchant = await DataService.GetFromApiAsync<MerchantDto>("api/bff/account/merchant");
            if (merchant != null)
            {
                _businessName = merchant.BusinessName ?? "";
                _merchantType = merchant.Type ?? "Individual";
                _taxId = merchant.BusinessInfo?.TaxId ?? "";
                _verificationStatus = merchant.VerificationStatus ?? "Unverified";
                _merchantCreatedAt = merchant.CreatedAt?.ToString("dd/MM/yyyy") ?? "—";

                // EN: Set subscription plan from merchant data
                // VI: Thiết lập gói đăng ký từ dữ liệu merchant
                _currentPlanId = merchant.SubscriptionPlanId;
                _currentPlanName = _currentPlanId >= 0 && _currentPlanId < _plans.Length
                    ? _plans[_currentPlanId].Name
                    : "Starter";
                (_limitShops, _limitStaff, _limitVerticals, _limitProducts) = _currentPlanId switch
                {
                    1 => (3, 10, 2, 500),
                    2 => (10, 50, 4, 9999),
                    3 => (9999, 9999, 9999, 9999),
                    _ => (1, 3, 1, 50),
                };
            }
        }
        catch { }

        // EN: Load linked accounts
        // VI: Tải tài khoản liên kết
        try
        {
            var linked = await DataService.GetFromApiAsync<LinkedAccountsDto>("api/bff/account/linked-accounts");
            if (linked?.LinkedProviders != null)
            {
                _linkedGoogle = linked.LinkedProviders.Any(p => p.Provider == "Google");
                _linkedFacebook = linked.LinkedProviders.Any(p => p.Provider == "Facebook");
            }
        }
        catch { }

        _loadingAccount = false;
    }

    private void SwitchTab(string tab) { _tab = tab; _profileMsg = null; _merchantMsg = null; _pwMsg = null; _tfaMsg = null; }

    // ═══ Profile Edit ═══
    private string _origFirstName = "", _origLastName = "", _origBio = "", _origTimezone = "";
    private void StartEditProfile()
    {
        _origFirstName = _firstName; _origLastName = _lastName; _origBio = _bio; _origTimezone = _timezone;
        _editingProfile = true; _profileMsg = null;
    }
    private void CancelEditProfile()
    {
        _firstName = _origFirstName; _lastName = _origLastName; _bio = _origBio; _timezone = _origTimezone;
        _editingProfile = false; _profileMsg = null;
    }

    private async Task SaveProfile()
    {
        _saving = true; _profileMsg = null;
        try
        {
            var ok1 = await DataService.PutAsync("api/bff/account/me", new { firstName = _firstName, lastName = _lastName });
            var ok2 = await DataService.PutAsync("api/bff/account/profile", new { bio = _bio, timezone = _timezone });
            _profileMsg = ok1 || ok2 ? "Cập nhật thành công!" : "Không thể cập nhật";
            _profileMsgOk = ok1 || ok2;
            if (_profileMsgOk) _editingProfile = false;
        }
        catch (Exception ex) { _profileMsg = ex.Message; _profileMsgOk = false; }
        finally { _saving = false; }
    }

    private async Task SaveMerchant()
    {
        _saving = true; _merchantMsg = null;
        try
        {
            var ok = await DataService.PutAsync("api/bff/account/merchant", new { businessName = _businessName, taxId = _taxId });
            _merchantMsg = ok ? "Cập nhật doanh nghiệp thành công!" : "Không thể cập nhật";
            _merchantMsgOk = ok;
            if (ok) _editingMerchant = false;
        }
        catch (Exception ex) { _merchantMsg = ex.Message; _merchantMsgOk = false; }
        finally { _saving = false; }
    }

    // ═══ Change Password ═══
    private async Task ChangePassword()
    {
        _pwMsg = null;
        if (string.IsNullOrEmpty(_currentPassword) || string.IsNullOrEmpty(_newPassword))
        { _pwMsg = "Vui lòng nhập đầy đủ"; _pwMsgOk = false; return; }
        if (_newPassword != _confirmPassword)
        { _pwMsg = "Mật khẩu xác nhận không khớp"; _pwMsgOk = false; return; }
        if (_newPassword.Length < 8)
        { _pwMsg = "Mật khẩu mới phải ít nhất 8 ký tự"; _pwMsgOk = false; return; }

        _saving = true;
        try
        {
            var ok = await DataService.PostAsync("api/bff/account/change-password",
                new { currentPassword = _currentPassword, newPassword = _newPassword });
            _pwMsg = ok ? "Đổi mật khẩu thành công!" : "Mật khẩu hiện tại không đúng";
            _pwMsgOk = ok;
            if (ok) { _currentPassword = ""; _newPassword = ""; _confirmPassword = ""; }
        }
        catch (Exception ex) { _pwMsg = ex.Message; _pwMsgOk = false; }
        finally { _saving = false; }
    }

    // ═══ 2FA ═══
    private async Task StartEnable2FA()
    {
        _saving = true; _tfaMsg = null;
        try
        {
            var result = await DataService.PostAndGetAsync<TwoFASetupDto>("api/bff/account/2fa/enable", new { });
            if (result != null)
            {
                _qrCodeBase64 = result.QrCodeBase64;
                _manualKey = result.ManualEntryKey;
                _show2FASetup = true;
            }
            else { _tfaMsg = "Không thể khởi tạo 2FA"; _tfaMsgOk = false; }
        }
        catch (Exception ex) { _tfaMsg = ex.Message; _tfaMsgOk = false; }
        finally { _saving = false; }
    }

    private async Task Verify2FA()
    {
        if (string.IsNullOrEmpty(_totpCode) || _totpCode.Length != 6)
        { _tfaMsg = "Vui lòng nhập mã 6 số"; _tfaMsgOk = false; return; }
        _saving = true;
        try
        {
            var ok = await DataService.PostAsync("api/bff/account/2fa/verify", new { code = _totpCode });
            if (ok) { _twoFactorEnabled = true; _show2FASetup = false; _tfaMsg = "2FA đã được bật thành công!"; _tfaMsgOk = true; }
            else { _tfaMsg = "Mã OTP không hợp lệ"; _tfaMsgOk = false; }
        }
        catch (Exception ex) { _tfaMsg = ex.Message; _tfaMsgOk = false; }
        finally { _saving = false; _totpCode = ""; }
    }

    private void StartDisable2FA() { _showDisable2FA = true; _tfaMsg = null; _totpCode = ""; }

    private async Task Disable2FA()
    {
        if (string.IsNullOrEmpty(_totpCode))
        { _tfaMsg = "Vui lòng nhập mã OTP"; _tfaMsgOk = false; return; }
        _saving = true;
        try
        {
            var ok = await DataService.PostAsync("api/bff/account/2fa/disable", new { code = _totpCode });
            if (ok) { _twoFactorEnabled = false; _showDisable2FA = false; _tfaMsg = "2FA đã tắt"; _tfaMsgOk = true; }
            else { _tfaMsg = "Mã OTP không hợp lệ"; _tfaMsgOk = false; }
        }
        catch (Exception ex) { _tfaMsg = ex.Message; _tfaMsgOk = false; }
        finally { _saving = false; _totpCode = ""; }
    }

    // ═══ Subscription ═══
    private void UpgradePlan(int planId)
    {
        // EN: In production, this would redirect to payment flow
        // VI: Trong production, sẽ redirect đến luồng thanh toán
    }

    // ═══ DTOs ═══
    private record AccountMeDto { public string? Id { get; init; } public string? Email { get; init; } public string? FirstName { get; init; } public string? LastName { get; init; } public string? FullName { get; init; } public string[]? Roles { get; init; } }
    private record ProfileDto { public string? Bio { get; init; } public string? AvatarUrl { get; init; } public string? Timezone { get; init; } public string? Locale { get; init; } }
    private record MerchantDto { public string? BusinessName { get; init; } public string? Type { get; init; } public string? VerificationStatus { get; init; } public BusinessInfoDto? BusinessInfo { get; init; } public DateTime? CreatedAt { get; init; } public int SubscriptionPlanId { get; init; } }
    private record BusinessInfoDto { public string? TaxId { get; init; } }
    private record LinkedAccountsDto { public List<LinkedProviderDto>? LinkedProviders { get; init; } }
    private record LinkedProviderDto { public string? Provider { get; init; } }
    private record TwoFASetupDto { public string? QrCodeBase64 { get; init; } public string? ManualEntryKey { get; init; } public string[]? RecoveryCodes { get; init; } }
}
