@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService
@inject NavigationManager Nav

<div>
    <div style="padding:8px 14px;border-radius:8px;background:rgba(59,130,246,.08);border:1px solid rgba(59,130,246,.15);margin-bottom:12px;display:flex;align-items:center;gap:8px;font-size:12px;color:var(--admin-text-secondary);">
        <i data-lucide="info" style="width:14px;height:14px;color:#3B82F6;flex-shrink:0;"></i>
        Dữ liệu khách hàng chung cho tất cả cửa hàng trong thương hiệu
    </div>
    <div style="display:flex;gap:8px;margin-bottom:16px;border-bottom:2px solid var(--admin-border-subtle);padding-bottom:8px;">
        @foreach (var (tab, label) in new[] { ("members","Khách hàng"), ("levels","Cấp bậc"), ("exp","Điểm EXP") })
        {
            <button @onclick="@(() => _customerSubTab = tab)"
                style="padding:8px 16px;border-radius:8px 8px 0 0;border:none;font-size:13px;font-weight:600;cursor:pointer;background:@(_customerSubTab == tab ? "var(--admin-orange-primary)" : "transparent");color:@(_customerSubTab == tab ? "#FFF" : "var(--admin-text-secondary)");">
                @label
            </button>
        }
    </div>
    @if (_customerSubTab == "levels")
    {
        @* ─── Level CRUD ─── *@
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
            <h3 style="margin:0;font-size:16px;font-weight:700;">@_memberLevels.Count cấp bậc</h3>
            <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick='() => { _showLevelForm = !_showLevelForm; _editingLevelId = null; _newLevelNumber = _memberLevels.Count + 1; _newLevelName = ""; _newLevelRequiredExp = 0; _newLevelDescription = ""; _newLevelBadgeColor = "#CD7F32"; }'>
                <i data-lucide="plus" style="width:14px;height:14px;margin-right:4px;"></i>Thêm cấp bậc
            </button>
        </div>
        @if (_showLevelForm)
        {
            <div class="admin-panel" style="margin-bottom:16px;">
                <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingLevelId.HasValue ? "Sửa cấp bậc" : "Thêm cấp bậc")</h3></div>
                <div class="admin-panel__body">
                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;">
                        <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Số level *</label><input type="number" @bind="_newLevelNumber" min="1" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                        <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên cấp bậc *</label><input type="text" @bind="_newLevelName" placeholder="Bronze" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                        <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">EXP cần *</label><input type="number" @bind="_newLevelRequiredExp" min="0" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                        <div style="grid-column:span 2;"><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Mô tả</label><input type="text" @bind="_newLevelDescription" placeholder="Mô tả quyền lợi..." style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                        <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Màu badge</label><input type="color" @bind="_newLevelBadgeColor" style="width:100%;height:36px;padding:2px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);cursor:pointer;" /></div>
                    </div>
                    @if (_levelFormMessage != null)
                    {
                        <div style="margin-top:8px;padding:8px 12px;border-radius:8px;background:@(_levelFormSuccess ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)");color:@(_levelFormSuccess ? "#22C55E" : "#EF4444");font-size:13px;">@_levelFormMessage</div>
                    }
                    <div style="display:flex;gap:8px;margin-top:12px;">
                        <button class="admin-btn-primary" style="font-size:12px;padding:6px 16px;" @onclick="SaveLevel">Lưu</button>
                        <button style="padding:6px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;cursor:pointer;" @onclick="() => _showLevelForm = false">Hủy</button>
                    </div>
                </div>
            </div>
        }
        <div class="admin-panel">
            <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);">Level</th>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tên</th>
                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">EXP cần</th>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Mô tả</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Màu</th>
                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Thành viên</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);"></th>
                </tr></thead><tbody>
                    @foreach (var lvl in _memberLevels.OrderBy(l => l.Level))
                    {
                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                            <td style="padding:12px 16px;font-weight:700;color:var(--admin-orange-primary);">@lvl.Level</td>
                            <td style="padding:12px 16px;font-weight:600;">@lvl.Name</td>
                            <td style="padding:12px 16px;text-align:right;font-size:13px;">@lvl.RequiredExp.ToString("N0")</td>
                            <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-secondary);">@(lvl.Description ?? "—")</td>
                            <td style="padding:12px 16px;text-align:center;"><span style="display:inline-block;width:20px;height:20px;border-radius:50%;background:@(lvl.BadgeColor ?? "#CCC");"></span></td>
                            <td style="padding:12px 16px;text-align:right;font-weight:600;">@lvl.MemberCount</td>
                            <td style="padding:12px 16px;text-align:center;">
                                <button @onclick="@(() => EditLevel(lvl))" style="padding:4px 8px;border-radius:6px;border:none;background:rgba(59,130,246,0.1);color:#3B82F6;font-size:11px;cursor:pointer;margin-right:4px;">Sửa</button>
                                <button @onclick="@(() => DeleteLevel(lvl.Id))" style="padding:4px 8px;border-radius:6px;border:none;background:rgba(239,68,68,0.1);color:#EF4444;font-size:11px;cursor:pointer;">Xóa</button>
                            </td>
                        </tr>
                    }
                </tbody></table>
            </div>
        </div>
    }
    else if (_customerSubTab == "exp")
    {
        @* ─── EXP Management ─── *@
        <div class="admin-panel" style="margin-bottom:16px;">
            <div class="admin-panel__header"><h3 class="admin-panel__title">Cộng điểm EXP</h3></div>
            <div class="admin-panel__body">
                <div style="display:grid;grid-template-columns:2fr 1fr 1fr;gap:12px;">
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Thành viên</label>
                        <select @bind="_expMemberId" @bind:after="LoadMemberProgress" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);">
                            <option value="">-- Chọn --</option>
                            @foreach (var m in _members)
                            {
                                <option value="@m.Id">@(m.DisplayName ?? m.Id.ToString()[..8]) (@m.TotalExpEarned EXP)</option>
                            }
                        </select>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Số điểm</label><input type="number" @bind="_expPoints" min="1" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Nguồn</label>
                        <select @bind="_expSourceId" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);">
                            <option value="1">Mua hàng</option><option value="2">Giới thiệu</option><option value="3">Hoạt động</option>
                            <option value="4">Khuyến mãi</option><option value="5">Đánh giá</option><option value="6">Check-in</option><option value="7">Admin</option>
                        </select>
                    </div>
                </div>
                @if (_expFormMessage != null)
                {
                    <div style="margin-top:8px;padding:8px 12px;border-radius:8px;background:@(_expFormSuccess ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)");color:@(_expFormSuccess ? "#22C55E" : "#EF4444");font-size:13px;">@_expFormMessage</div>
                }
                <button class="admin-btn-primary" style="font-size:12px;padding:6px 16px;margin-top:12px;" @onclick="AddExpToMember">Cộng EXP</button>
            </div>
        </div>
        @if (_memberProgress != null)
        {
            <div class="admin-panel" style="margin-bottom:16px;">
                <div class="admin-panel__header"><h3 class="admin-panel__title">Tiến trình: @(_memberProgress.CurrentLevelName ?? "Level") @_memberProgress.CurrentLevel</h3></div>
                <div class="admin-panel__body">
                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:16px;margin-bottom:16px;">
                        <div><span style="font-size:11px;color:var(--admin-text-tertiary);">EXP hiện tại</span><div style="font-weight:700;font-size:18px;color:var(--admin-orange-primary);">@_memberProgress.CurrentExp.ToString("N0")</div></div>
                        <div><span style="font-size:11px;color:var(--admin-text-tertiary);">Tổng EXP</span><div style="font-weight:700;font-size:18px;">@_memberProgress.TotalExpEarned.ToString("N0")</div></div>
                        <div><span style="font-size:11px;color:var(--admin-text-tertiary);">Cần thêm</span><div style="font-weight:700;font-size:18px;">@_memberProgress.ExpToNextLevel.ToString("N0")</div></div>
                        <div><span style="font-size:11px;color:var(--admin-text-tertiary);">Level kế</span><div style="font-weight:700;font-size:18px;">@(_memberProgress.NextLevelName ?? "Max")</div></div>
                    </div>
                    <div style="background:var(--admin-border-subtle);border-radius:8px;height:12px;overflow:hidden;">
                        <div style="background:var(--admin-orange-primary);height:100%;border-radius:8px;width:@(_memberProgress.ProgressPercent)%;transition:width 0.3s;"></div>
                    </div>
                    <div style="text-align:right;font-size:12px;color:var(--admin-text-tertiary);margin-top:4px;">@_memberProgress.ProgressPercent%</div>
                </div>
            </div>
        }
        @if (_expHistory.Any())
        {
            <div class="admin-panel">
                <div class="admin-panel__header"><h3 class="admin-panel__title">Lịch sử EXP</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);">Ngày</th>
                        <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Điểm</th>
                        <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Nguồn</th>
                        <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tham chiếu</th>
                        <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Level</th>
                    </tr></thead><tbody>
                        @foreach (var tx in _expHistory)
                        {
                            <tr style="border-top:1px solid var(--admin-border-subtle);">
                                <td style="padding:12px 16px;font-size:13px;">@tx.CreatedAt.ToString("dd/MM/yyyy HH:mm")</td>
                                <td style="padding:12px 16px;text-align:right;font-weight:600;color:@(tx.Points > 0 ? "#22C55E" : "#EF4444");">@(tx.Points > 0 ? "+" : "")@tx.Points</td>
                                <td style="padding:12px 16px;font-size:13px;">@(tx.Source ?? "—")</td>
                                <td style="padding:12px 16px;font-size:12px;color:var(--admin-text-tertiary);font-family:monospace;">@(tx.ReferenceId ?? "—")</td>
                                <td style="padding:12px 16px;text-align:right;">@tx.LevelAtTime</td>
                            </tr>
                        }
                    </tbody></table>
                </div>
            </div>
        }
    }
    else
    {
    @* ─── Members list ─── *@
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
        <h3 style="margin:0;font-size:16px;font-weight:700;">@_members.Count khách hàng</h3>
        <div style="display:flex;gap:8px;align-items:center;">
            <div style="position:relative;">
                <i data-lucide="search" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);width:16px;height:16px;color:var(--admin-text-tertiary);"></i>
                <input type="text" placeholder="Tìm theo ID..." @bind="_customerSearch" @bind:event="oninput"
                    style="padding:8px 12px 8px 36px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);width:200px;" />
            </div>
            <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick='() => { _showMemberForm = !_showMemberForm; _editingMemberId = null; _newMemberGender = ""; _newMemberCountry = "VN"; _newMemberName = ""; _newMemberPhone = ""; }'>
                <i data-lucide="plus" style="width:14px;height:14px;margin-right:4px;"></i>Thêm khách hàng
            </button>
        </div>
    </div>
    @if (_showMemberForm)
    {
        <div class="admin-panel" style="margin-bottom:16px;">
            <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingMemberId.HasValue ? "Sửa khách hàng" : "Thêm khách hàng")</h3></div>
            <div class="admin-panel__body">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên khách hàng *</label><input type="text" @bind="_newMemberName" placeholder="Nguyễn Văn A" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Số điện thoại</label><input type="tel" @bind="_newMemberPhone" placeholder="0901234567" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giới tính</label>
                        <select @bind="_newMemberGender" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);">
                            <option value="">-- Chọn --</option>
                            <option value="male">Nam</option>
                            <option value="female">Nữ</option>
                            <option value="other">Khác</option>
                        </select>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Mã quốc gia</label><input type="text" @bind="_newMemberCountry" maxlength="2" placeholder="VN" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);font-size:13px;color:var(--admin-text-primary);" /></div>
                </div>
                @if (_memberFormMessage != null)
                {
                    <div style="margin-top:8px;padding:8px 12px;border-radius:8px;background:@(_memberFormSuccess ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)");color:@(_memberFormSuccess ? "#22C55E" : "#EF4444");font-size:13px;">@_memberFormMessage</div>
                }
                <div style="display:flex;gap:8px;margin-top:12px;">
                    <button class="admin-btn-primary" style="font-size:12px;padding:6px 16px;" @onclick="SaveMember">Lưu</button>
                    <button style="padding:6px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;cursor:pointer;" @onclick='() => { _showMemberForm = false; _memberFormMessage = null; }'>Hủy</button>
                </div>
            </div>
        </div>
    }
    var filteredMembers = string.IsNullOrWhiteSpace(_customerSearch)
        ? _members
        : _members.Where(m => m.Id.ToString().Contains(_customerSearch, StringComparison.OrdinalIgnoreCase)
            || (m.DisplayName ?? "").Contains(_customerSearch, StringComparison.OrdinalIgnoreCase)
            || (m.Phone ?? "").Contains(_customerSearch, StringComparison.OrdinalIgnoreCase)
            || (m.LevelName ?? "").Contains(_customerSearch, StringComparison.OrdinalIgnoreCase)).ToList();
    @if (!filteredMembers.Any())
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:rgba(239,68,68,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="heart" style="width:36px;height:36px;color:#EF4444;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">Chưa có khách hàng</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Khách hàng sẽ hiển thị khi có giao dịch</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 bán hàng
            </a>
        </div>
    }
    else
    {
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
            <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(255,92,0,0.1);"><i data-lucide="users" style="color:#FF5C00;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@filteredMembers.Count</span><span class="admin-stat-card__label">Tổng khách hàng</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="crown" style="color:#8B5CF6;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@_memberLevels.Count</span><span class="admin-stat-card__label">Cấp bậc</span></div></div>
            <div class="admin-stat-card"><div class="admin-stat-card__icon" style="background:rgba(34,197,94,0.1);"><i data-lucide="star" style="color:#22C55E;"></i></div><div class="admin-stat-card__content"><span class="admin-stat-card__value">@(filteredMembers.Any() ? filteredMembers.Max(m => m.TotalExpEarned).ToString("N0") : "0")</span><span class="admin-stat-card__label">EXP cao nhất</span></div></div>
        </div>
        @if (_memberLevels.Any())
        {
            <div class="admin-panel" style="margin-top:16px;">
                <div class="admin-panel__header"><h3 class="admin-panel__title">Cấp bậc thành viên</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);">Level</th>
                        <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tên</th>
                        <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">EXP cần</th>
                        <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Thành viên</th>
                    </tr></thead><tbody>
                        @foreach (var lvl in _memberLevels.OrderBy(l => l.Level))
                        {
                            <tr style="border-top:1px solid var(--admin-border-subtle);">
                                <td style="padding:12px 16px;font-weight:700;color:var(--admin-orange-primary);">@lvl.Level</td>
                                <td style="padding:12px 16px;font-weight:600;">@lvl.Name</td>
                                <td style="padding:12px 16px;text-align:right;font-size:13px;color:var(--admin-text-tertiary);">@lvl.MinExp.ToString("N0") — @lvl.MaxExp.ToString("N0")</td>
                                <td style="padding:12px 16px;text-align:right;font-weight:600;">@lvl.MemberCount</td>
                            </tr>
                        }
                    </tbody></table>
                </div>
            </div>
        }
        <div class="admin-panel" style="margin-top:16px;">
            <div class="admin-panel__header"><h3 class="admin-panel__title">Danh sách khách hàng</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);">Tên</th>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">SĐT</th>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Cấp bậc</th>
                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">EXP</th>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Ngày tham gia</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);"></th>
                </tr></thead><tbody>
                    @foreach (var m in filteredMembers)
                    {
                        var isExpanded = _selectedCustomerId == m.Id;
                        <tr style="border-top:1px solid var(--admin-border-subtle);cursor:pointer;transition:background 0.15s;@(isExpanded ? "background:rgba(255,92,0,0.05);" : "")" @onclick='() => { _selectedCustomerId = isExpanded ? null : m.Id; StateHasChanged(); }'>
                            <td style="padding:12px 16px;font-weight:600;">@(m.DisplayName ?? m.Id.ToString()[..8])</td>
                            <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-secondary);">@(m.Phone ?? "—")</td>
                            <td style="padding:12px 16px;"><span class="admin-status-badge admin-status-badge--online" style="font-size:11px;padding:2px 10px;">@(m.LevelName ?? "—")</span></td>
                            <td style="padding:12px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@m.TotalExpEarned.ToString("N0")</td>
                            <td style="padding:12px 16px;font-size:13px;color:var(--admin-text-tertiary);">@m.CreatedAt.ToString("dd/MM/yyyy")</td>
                            <td style="padding:12px 16px;text-align:center;"><i data-lucide="@(isExpanded ? "chevron-up" : "chevron-down")" style="width:14px;height:14px;color:var(--admin-text-tertiary);"></i></td>
                        </tr>
                        @if (isExpanded)
                        {
                            <tr><td colspan="6" style="padding:0;">
                                <div style="padding:16px 20px;background:rgba(255,92,0,0.03);border-top:2px solid var(--admin-orange-primary);">
                                    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
                                        <div>
                                            <label style="font-size:11px;font-weight:600;color:var(--admin-text-tertiary);display:block;margin-bottom:4px;">Mã KH</label>
                                            <div style="font-family:monospace;font-size:12px;">@m.Id.ToString()</div>
                                        </div>
                                        <div>
                                            <label style="font-size:11px;font-weight:600;color:var(--admin-text-tertiary);display:block;margin-bottom:4px;">Cấp bậc hiện tại</label>
                                            <div style="font-weight:600;">@(m.LevelName ?? "Chưa xếp hạng") - @m.TotalExpEarned.ToString("N0") EXP</div>
                                        </div>
                                        <div>
                                            <label style="font-size:11px;font-weight:600;color:var(--admin-text-tertiary);display:block;margin-bottom:4px;">Tham gia từ</label>
                                            <div style="font-size:13px;">@m.CreatedAt.ToString("dd/MM/yyyy HH:mm")</div>
                                        </div>
                                    </div>
                                    <div style="display:flex;gap:8px;margin-top:12px;">
                                        <button @onclick="ShowComingSoonPromo" @onclick:stopPropagation style="padding:6px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;cursor:pointer;display:flex;align-items:center;gap:6px;">
                                            <i data-lucide="gift" style="width:12px;height:12px;"></i> Tặng ưu đãi
                                        </button>
                                        <button @onclick="ShowComingSoonMessage" @onclick:stopPropagation style="padding:6px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;cursor:pointer;display:flex;align-items:center;gap:6px;">
                                            <i data-lucide="message-square" style="width:12px;height:12px;"></i> Gửi tin
                                        </button>
                                        <button @onclick="GoToOrderHistory" @onclick:stopPropagation style="padding:6px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;cursor:pointer;display:flex;align-items:center;gap:6px;">
                                            <i data-lucide="history" style="width:12px;height:12px;"></i> Lịch sử đơn
                                        </button>
                                        <button @onclick="@(() => EditMember(m))" @onclick:stopPropagation style="padding:6px 14px;border-radius:8px;border:none;background:rgba(59,130,246,0.1);color:#3B82F6;font-size:12px;cursor:pointer;display:flex;align-items:center;gap:6px;">
                                            <i data-lucide="pencil" style="width:12px;height:12px;"></i> Sửa
                                        </button>
                                        <button @onclick="@(() => DeleteMemberItem(m.Id))" @onclick:stopPropagation style="padding:6px 14px;border-radius:8px;border:none;background:rgba(239,68,68,0.1);color:#EF4444;font-size:12px;cursor:pointer;display:flex;align-items:center;gap:6px;">
                                            <i data-lucide="trash-2" style="width:12px;height:12px;"></i> Xóa
                                        </button>
                                    </div>
                                </div>
                            </td></tr>
                        }
                    }
                </tbody></table>
            </div>
        </div>
    }
    }
</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 Guid ShopGuid { get; set; }
    [Parameter] public string ShopId { get; set; } = "";
    [Parameter] public string PosVertical { get; set; } = "cafe";

    // Members data
    private List<PosDataService.MemberInfo> _members = new();
    private List<PosDataService.LevelDefinitionInfo> _memberLevels = new();

    // Customer sub-tab
    private string _customerSubTab = "members";
    private string _customerSearch = "";
    private Guid? _selectedCustomerId;

    // Member form
    private bool _showMemberForm;
    private Guid? _editingMemberId;
    private string _newMemberGender = "";
    private string _newMemberCountry = "VN";
    private string _newMemberName = "";
    private string _newMemberPhone = "";
    private string? _memberFormMessage;
    private bool _memberFormSuccess;

    // Level form
    private bool _showLevelForm;
    private Guid? _editingLevelId;
    private int _newLevelNumber;
    private string _newLevelName = "";
    private int _newLevelRequiredExp;
    private string _newLevelDescription = "";
    private string _newLevelBadgeColor = "#CD7F32";
    private string? _levelFormMessage;
    private bool _levelFormSuccess;

    // EXP management
    private Guid? _expMemberId;
    private int _expPoints = 100;
    private int _expSourceId = 7;
    private string? _expFormMessage;
    private bool _expFormSuccess;
    private PosDataService.MemberProgressInfo? _memberProgress;
    private List<PosDataService.ExpTransactionInfo> _expHistory = new();

    // Toast
    private string? _toastMessage;

    protected override async Task OnInitializedAsync()
    {
        await RefreshMembersAndLevels();
    }

    private async Task RefreshMembersAndLevels()
    {
        var rm = await DataService.GetMembersAsync();
        var rl = await DataService.GetMembershipLevelsAsync();
        _memberLevels = PosDataService.EnrichLevelDefinitions(rl, rm);
        _members = PosDataService.ResolveMemberLevelNames(rm, rl);
    }

    private async Task SaveMember()
    {
        _memberFormMessage = null;
        if (_editingMemberId.HasValue)
        {
            var ok = await DataService.UpdateMemberAsync(_editingMemberId.Value, new PosDataService.UpdateMemberRequest(_newMemberGender, null));
            if (ok) { _showMemberForm = false; _editingMemberId = null; _newMemberName = ""; _newMemberPhone = ""; await RefreshMembersAndLevels(); }
        }
        else
        {
            var (ok, err) = await DataService.CreateMemberAsync(new PosDataService.CreateMemberRequest(_newMemberGender, _newMemberCountry,
                string.IsNullOrWhiteSpace(_newMemberName) ? null : _newMemberName,
                string.IsNullOrWhiteSpace(_newMemberPhone) ? null : _newMemberPhone));
            if (ok) { _showMemberForm = false; _editingMemberId = null; _newMemberName = ""; _newMemberPhone = ""; _memberFormMessage = null; await RefreshMembersAndLevels(); }
            else { _memberFormMessage = err ?? "Lỗi tạo khách hàng."; _memberFormSuccess = false; }
        }
    }

    private void EditMember(PosDataService.MemberInfo m)
    {
        _editingMemberId = m.Id; _newMemberGender = m.Gender ?? ""; _newMemberCountry = m.CountryCode ?? "VN";
        _newMemberName = m.DisplayName ?? ""; _newMemberPhone = m.Phone ?? "";
        _showMemberForm = true;
    }

    private async Task DeleteMemberItem(Guid memberId)
    {
        await DataService.DeleteMemberAsync(memberId);
        await RefreshMembersAndLevels();
    }

    private async Task SaveLevel()
    {
        _levelFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newLevelName) || _newLevelNumber <= 0)
        { _levelFormMessage = "Nhập tên và số level."; _levelFormSuccess = false; return; }
        var req = new PosDataService.CreateLevelRequest(_newLevelNumber, _newLevelName, _newLevelRequiredExp, _newLevelDescription, _newLevelBadgeColor);
        if (_editingLevelId.HasValue)
        {
            var (ok, err) = await DataService.UpdateLevelAsync(_editingLevelId.Value, req);
            _levelFormSuccess = ok; _levelFormMessage = ok ? "Đã cập nhật!" : err ?? "Lỗi.";
        }
        else
        {
            var (ok, err) = await DataService.CreateLevelAsync(req);
            _levelFormSuccess = ok; _levelFormMessage = ok ? "Đã thêm!" : err ?? "Lỗi.";
        }
        if (_levelFormSuccess) { _showLevelForm = false; await RefreshMembersAndLevels(); }
    }

    private void EditLevel(PosDataService.LevelDefinitionInfo lvl)
    {
        _editingLevelId = lvl.Id; _newLevelNumber = lvl.LevelNumber; _newLevelName = lvl.Name;
        _newLevelRequiredExp = lvl.RequiredExp; _newLevelDescription = lvl.Description ?? "";
        _newLevelBadgeColor = lvl.BadgeColor ?? "#CD7F32"; _showLevelForm = true;
    }

    private async Task DeleteLevel(Guid id)
    {
        await DataService.DeleteLevelAsync(id);
        await RefreshMembersAndLevels();
    }

    private async Task AddExpToMember()
    {
        _expFormMessage = null;
        if (!_expMemberId.HasValue || _expPoints <= 0)
        { _expFormMessage = "Chọn thành viên và nhập số điểm > 0."; _expFormSuccess = false; return; }
        var result = await DataService.AddExperienceAsync(_expMemberId.Value, new PosDataService.AddExpRequest(_expPoints, _expSourceId, null));
        if (result != null)
        {
            _expFormSuccess = true;
            _expFormMessage = result.LeveledUp ? $"Đã cộng {result.PointsAdded} EXP! Lên level {result.CurrentLevel}!" : $"Đã cộng {result.PointsAdded} EXP! Tổng: {result.TotalExpEarned}";
            _memberProgress = await DataService.GetMemberProgressAsync(_expMemberId.Value);
            _expHistory = await DataService.GetExperienceHistoryAsync(_expMemberId.Value);
            await RefreshMembersAndLevels();
        }
        else { _expFormMessage = "Lỗi khi cộng EXP."; _expFormSuccess = false; }
    }

    private async Task LoadMemberProgress()
    {
        if (_expMemberId.HasValue)
        {
            _memberProgress = await DataService.GetMemberProgressAsync(_expMemberId.Value);
            _expHistory = await DataService.GetExperienceHistoryAsync(_expMemberId.Value);
        }
        else { _memberProgress = null; _expHistory = new(); }
    }

    private void ShowComingSoonPromo() => ShowComingSoon("Tặng ưu đãi");
    private void ShowComingSoonMessage() => ShowComingSoon("Gửi tin nhắn");
    private void GoToOrderHistory() => Nav.NavigateTo($"/admin/shop/{ShopId}/finance");

    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();
    }
}
