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

@if (SubSection == "tables")
{
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
        <div style="display:flex;gap:8px;">
            <span class="admin-status-badge admin-status-badge--online" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Trống: @_tables.Count(t => t.Status == "available")</span>
            <span class="admin-status-badge admin-status-badge--paused" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Đang dùng: @_tables.Count(t => t.Status == "occupied")</span>
            <span class="admin-status-badge admin-status-badge--setup" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Đã đặt: @_tables.Count(t => t.Status == "reserved")</span>
        </div>
        <div style="display:flex;gap:8px;align-items:center;">
            <div style="display:flex;background:var(--admin-bg-elevated);border-radius:8px;padding:2px;">
                <button @onclick='() => _floorPlanView = false'
                    style="padding:5px 12px;border-radius:6px;border:none;font-size:11px;font-weight:600;cursor:pointer;@(!_floorPlanView ? "background:var(--admin-orange-primary);color:white;" : "background:transparent;color:var(--admin-text-secondary);")">
                    <i data-lucide="grid-3x3" style="width:12px;height:12px;vertical-align:middle;margin-right:3px;"></i>Lưới
                </button>
                <button @onclick='() => _floorPlanView = true'
                    style="padding:5px 12px;border-radius:6px;border:none;font-size:11px;font-weight:600;cursor:pointer;@(_floorPlanView ? "background:var(--admin-orange-primary);color:white;" : "background:transparent;color:var(--admin-text-secondary);")">
                    <i data-lucide="map" style="width:12px;height:12px;vertical-align:middle;margin-right:3px;"></i>Sơ đồ
                </button>
            </div>
            <a href="/admin/shop/@ShopId/qr-codes" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid rgba(139,92,246,0.4);background:rgba(139,92,246,0.08);color:#8B5CF6;text-decoration:none;font-size:12px;font-weight:600;">
                <i data-lucide="qr-code" style="width:14px;height:14px;"></i>Mã QR hàng loạt
            </a>
            <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick='() => { _editingTableId = null; _newTableNumber = ""; _newTableCapacity = 4; _newTableZone = ""; _tableFormMessage = null; _showTableForm = !_showTableForm; }'>
                <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>Thêm bàn
            </button>
        </div>
    </div>
    @if (_showTableForm)
    {
        <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(245,158,11,0.3);">
            <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingTableId.HasValue ? "Chỉnh sửa bàn" : "Thêm bàn mới")</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ố bàn *</label><input type="text" @bind="_newTableNumber" placeholder="VD: 01, A1" 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;font-weight:600;display:block;margin-bottom:4px;">Sức chứa</label><input type="number" @bind="_newTableCapacity" min="1" 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;font-weight:600;display:block;margin-bottom:4px;">Khu vực</label><select @bind="_newTableZone" 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);"><option value="">— Chưa chọn —</option>@foreach (var z in AllZoneNames) { <option value="@z">@z</option> }</select></div>
                </div>
                <div style="display:flex;gap:8px;margin-top:12px;">
                    <button class="admin-btn-primary" @onclick="@(_editingTableId.HasValue ? SaveTable : AddTable)" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>@(_editingTableId.HasValue ? "Cập nhật" : "Lưu")</button>
                    <button @onclick='() => _showTableForm = 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 (_tableFormMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_tableFormSuccess ? "#22C55E" : "#EF4444");">@_tableFormMessage</div> }
            </div>
        </div>
    }
    @if (!_tables.Any())
    {
        @RenderEmpty("grid-3x3", "#F59E0B", "Chưa có bàn nào", "Thêm bàn để quản lý sơ đồ phục vụ")
    }
    else if (!_floorPlanView)
    {
        @* ═══ GRID VIEW ═══ *@
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px;">
            @foreach (var table in _tables)
            {
                var bgColor = table.Status switch { "available" => "rgba(34,197,94,0.08)", "occupied" => "rgba(239,68,68,0.08)", "reserved" => "rgba(245,158,11,0.08)", _ => "rgba(107,107,111,0.08)" };
                var borderColor = table.Status switch { "available" => "rgba(34,197,94,0.3)", "occupied" => "rgba(239,68,68,0.3)", "reserved" => "rgba(245,158,11,0.3)", _ => "rgba(107,107,111,0.3)" };
                var statusColor = table.Status switch { "available" => "#22C55E", "occupied" => "#EF4444", "reserved" => "#F59E0B", _ => "#6B6B6F" };
                var statusText = table.Status switch { "available" => "Trống", "occupied" => "Đang dùng", "reserved" => "Đã đặt", "cleaning" => "Dọn dẹp", _ => table.Status };
                <div style="background:@bgColor;border:1px solid @borderColor;border-radius:14px;padding:20px;text-align:center;position:relative;">
                    <div style="position:absolute;top:8px;right:8px;display:flex;gap:4px;">
                        <button @onclick='() => ShowQrModal(table)' style="background:rgba(139,92,246,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Mã QR"><i data-lucide="qr-code" style="color:#8B5CF6;width:12px;height:12px;"></i></button>
                        <button @onclick='() => EditTable(table)' style="background:rgba(59,130,246,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;"><i data-lucide="pencil" style="color:#3B82F6;width:12px;height:12px;"></i></button>
                        <button @onclick='() => DeleteTableItem(table.Id)' style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;"><i data-lucide="trash-2" style="color:#EF4444;width:12px;height:12px;"></i></button>
                    </div>
                    <div style="font-size:22px;font-weight:700;margin-bottom:4px;">@table.TableNumber</div>
                    <div style="font-size:12px;color:var(--admin-text-tertiary);margin-bottom:8px;">@(table.Zone ?? "Chung") • @table.Capacity chỗ</div>
                    <div style="display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:600;color:@statusColor;">
                        <span style="width:6px;height:6px;border-radius:50%;background:@statusColor;"></span>
                        @statusText
                    </div>
                    @if (table.SessionId.HasValue)
                    {
                        <div style="margin-top:8px;padding-top:8px;border-top:1px solid @borderColor;font-size:11px;color:var(--admin-text-tertiary);">
                            @table.GuestCount khách • @(table.StartedAt?.ToString("HH:mm") ?? "—")
                        </div>
                    }
                </div>
            }
        </div>
    }
    else
    {
        @* ═══ FLOOR PLAN VIEW ═══ *@
        <div style="position:relative;width:100%;height:600px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);border-radius:14px;overflow:hidden;
                    background-image:radial-gradient(circle,rgba(255,255,255,.06) 1px,transparent 1px);background-size:24px 24px;"
             @onpointermove="OnCanvasPointerMove" @onpointerup="OnCanvasPointerUp" @onpointerleave="OnCanvasPointerUp"
             @onpointermove:preventDefault @onpointerup:preventDefault>

            @* Zone labels *@
            @{
                var zones = _tables.Where(t => t.PositionX.HasValue).GroupBy(t => t.Zone ?? "Chung").ToList();
                foreach (var zone in zones)
                {
                    var firstTable = zone.First();
                    <div style="position:absolute;left:@(GetPosition(firstTable.Id).X)px;top:@(Math.Max(0, GetPosition(firstTable.Id).Y - 28))px;
                                font-size:10px;font-weight:700;color:var(--admin-text-tertiary);text-transform:uppercase;letter-spacing:1px;pointer-events:none;">
                        @zone.Key
                    </div>
                }
            }

            @* Legend *@
            <div style="position:absolute;bottom:12px;right:12px;display:flex;gap:12px;font-size:10px;color:var(--admin-text-tertiary);background:rgba(0,0,0,.4);padding:6px 12px;border-radius:8px;">
                <span><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#22C55E;margin-right:3px;"></span>Trống</span>
                <span><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#EF4444;margin-right:3px;"></span>Đang dùng</span>
                <span><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#F59E0B;margin-right:3px;"></span>Đã đặt</span>
            </div>

            @* Drag hint *@
            <div style="position:absolute;top:12px;left:12px;font-size:10px;color:var(--admin-text-tertiary);background:rgba(0,0,0,.4);padding:4px 10px;border-radius:6px;">
                <i data-lucide="move" style="width:10px;height:10px;vertical-align:middle;margin-right:3px;"></i>Kéo bàn để sắp xếp
            </div>

            @foreach (var table in _tables)
            {
                var pos = GetPosition(table.Id);
                var isDragging = _draggingTableId == table.Id;
                var statusColor = table.Status switch { "available" => "#22C55E", "occupied" => "#EF4444", "reserved" => "#F59E0B", _ => "#6B6B6F" };
                var bgColor = table.Status switch { "available" => "rgba(34,197,94,0.12)", "occupied" => "rgba(239,68,68,0.12)", "reserved" => "rgba(245,158,11,0.12)", _ => "rgba(107,107,111,0.12)" };

                <div @onpointerdown="(e) => OnTablePointerDown(e, table)"
                     @onpointerdown:preventDefault
                     style="position:absolute;left:@(pos.X)px;top:@(pos.Y)px;
                            width:90px;text-align:center;cursor:grab;user-select:none;touch-action:none;
                            background:@bgColor;border:2px solid @(isDragging ? "var(--admin-orange-primary)" : statusColor);
                            border-radius:@(table.Capacity <= 2 ? "50%" : table.Capacity <= 4 ? "12px" : "16px");
                            padding:@(table.Capacity <= 2 ? "18px 8px" : "12px 8px");
                            transition:@(isDragging ? "none" : "box-shadow .2s");
                            box-shadow:@(isDragging ? "0 8px 24px rgba(0,0,0,.3)" : "0 2px 8px rgba(0,0,0,.15)");
                            z-index:@(isDragging ? "100" : "1");">
                    <div style="font-size:15px;font-weight:700;color:var(--admin-text-primary);">@table.TableNumber</div>
                    <div style="font-size:10px;color:var(--admin-text-tertiary);margin-top:2px;">@table.Capacity chỗ</div>
                    <div style="width:6px;height:6px;border-radius:50%;background:@statusColor;margin:4px auto 0;"></div>
                </div>
            }
        </div>
    }
}
else if (SubSection == "rooms")
{
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
        <div style="display:flex;gap:8px;">
            <span class="admin-status-badge admin-status-badge--online" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Trống: @_tables.Count(t => t.Status == "available")</span>
            <span class="admin-status-badge admin-status-badge--paused" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Đang hát: @_tables.Count(t => t.Status == "occupied")</span>
            <span class="admin-status-badge admin-status-badge--setup" style="font-size:11px;"><span class="admin-status-badge__dot"></span>Đã đặt: @_tables.Count(t => t.Status == "reserved")</span>
        </div>
        <a href="/admin/shop/@ShopId/qr-codes" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid rgba(139,92,246,0.4);background:rgba(139,92,246,0.08);color:#8B5CF6;text-decoration:none;font-size:12px;font-weight:600;">
            <i data-lucide="qr-code" style="width:14px;height:14px;"></i>Mã QR hàng loạt
        </a>
        <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick='() => { _editingTableId = null; _newTableNumber = ""; _newTableCapacity = 8; _newTableZone = ""; _newHourlyRate = 0; _tableFormMessage = null; _showTableForm = !_showTableForm; }'>
            <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>Thêm phòng
        </button>
    </div>
    @if (_showTableForm)
    {
        <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(139,92,246,0.3);">
            <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingTableId.HasValue ? "Chỉnh sửa phòng" : "Thêm phòng mới")</h3></div>
            <div class="admin-panel__body">
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px;">
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Số phòng *</label><input type="text" @bind="_newTableNumber" placeholder="VD: 01, A1" 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;font-weight:600;display:block;margin-bottom:4px;">Sức chứa</label><input type="number" @bind="_newTableCapacity" min="1" 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;font-weight:600;display:block;margin-bottom:4px;">Loại phòng</label><select @bind="_newTableZone" 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);"><option value="Standard">Standard</option><option value="VIP">VIP</option><option value="Party">Party</option><option value="Deluxe">Deluxe</option></select></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giá/giờ (VND)</label><input type="number" @bind="_newHourlyRate" min="0" step="10000" 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:12px;">
                    <button class="admin-btn-primary" @onclick="@(_editingTableId.HasValue ? SaveTable : AddTable)" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>@(_editingTableId.HasValue ? "Cập nhật" : "Lưu")</button>
                    <button @onclick='() => _showTableForm = 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 (_tableFormMessage != null) { <div style="margin-top:8px;font-size:13px;color:@(_tableFormSuccess ? "#22C55E" : "#EF4444");">@_tableFormMessage</div> }
            </div>
        </div>
    }
    @if (!_tables.Any())
    {
        @RenderEmpty("door-open", "#8B5CF6", "Chưa có phòng nào", "Nhấn 'Thêm phòng' ở trên để tạo phòng đầu tiên")
    }
    else
    {
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:16px;">
            @foreach (var room in _tables)
            {
                var bgColor = room.Status switch { "available" => "rgba(139,92,246,0.08)", "occupied" => "rgba(239,68,68,0.08)", "reserved" => "rgba(245,158,11,0.08)", _ => "rgba(107,107,111,0.08)" };
                var borderColor = room.Status switch { "available" => "rgba(139,92,246,0.3)", "occupied" => "rgba(239,68,68,0.3)", "reserved" => "rgba(245,158,11,0.3)", _ => "rgba(107,107,111,0.3)" };
                var statusColor = room.Status switch { "available" => "#8B5CF6", "occupied" => "#EF4444", "reserved" => "#F59E0B", _ => "#6B6B6F" };
                var statusText = room.Status switch { "available" => "Trống", "occupied" => "Đang hát", "reserved" => "Đã đặt", "cleaning" => "Dọn dẹp", _ => room.Status };
                var roomType = (room.Zone ?? "").ToLower() switch { var z when z.Contains("vip") => ("VIP", "#F59E0B"), var z when z.Contains("party") => ("Party", "#EC4899"), _ => ("Standard", "#8B5CF6") };
                <div style="background:@bgColor;border:1px solid @borderColor;border-radius:14px;padding:20px;position:relative;">
                    <div style="position:absolute;top:8px;right:8px;display:flex;gap:4px;">
                        <button @onclick='() => ShowQrModal(room)' style="background:rgba(139,92,246,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Mã QR"><i data-lucide="qr-code" style="color:#8B5CF6;width:12px;height:12px;"></i></button>
                        <button @onclick='() => EditTable(room)' style="background:rgba(59,130,246,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;"><i data-lucide="pencil" style="color:#3B82F6;width:12px;height:12px;"></i></button>
                        <button @onclick='() => DeleteTableItem(room.Id)' style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:26px;height:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;"><i data-lucide="trash-2" style="color:#EF4444;width:12px;height:12px;"></i></button>
                    </div>
                    <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;margin-top:4px;">
                        <i data-lucide="door-open" style="width:20px;height:20px;color:@statusColor;"></i>
                        <span style="font-size:18px;font-weight:700;">Phòng @room.TableNumber</span>
                    </div>
                    <div style="font-size:12px;color:var(--admin-text-tertiary);margin-bottom:4px;">@(room.Zone ?? "Standard") • @room.Capacity chỗ</div>
                    <div style="font-size:12px;font-weight:600;color:var(--admin-orange-primary);margin-bottom:8px;">@ShopHelpers.FormatVND(room.HourlyRate)/giờ</div>
                    <div style="display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:600;color:@statusColor;">
                        <span style="width:6px;height:6px;border-radius:50%;background:@statusColor;"></span>
                        @statusText
                    </div>
                    @if (room.SessionId.HasValue)
                    {
                        var elapsed = DateTime.UtcNow - (room.StartedAt ?? DateTime.UtcNow);
                        var hours = Math.Max(1, (int)Math.Ceiling(elapsed.TotalHours));
                        var bill = hours * room.HourlyRate;
                        <div style="margin-top:8px;padding-top:8px;border-top:1px solid @borderColor;">
                            <div style="font-size:11px;color:var(--admin-text-tertiary);margin-bottom:4px;">@room.GuestCount khách • Bắt đầu @(room.StartedAt?.ToString("HH:mm") ?? "—")</div>
                            <div style="display:flex;justify-content:space-between;align-items:center;">
                                <span style="font-size:11px;color:var(--admin-text-tertiary);"><i data-lucide="clock" style="width:12px;height:12px;vertical-align:middle;"></i> @hours giờ</span>
                                <span style="font-size:13px;font-weight:700;color:var(--admin-orange-primary);">@ShopHelpers.FormatVND(bill)</span>
                            </div>
                        </div>
                    }
                </div>
            }
        </div>
    }
}
else if (SubSection == "zones")
{
    var tableZones = _tables.GroupBy(t => t.Zone ?? "Chung").Select(g => new { Name = g.Key, Count = g.Count() }).ToList();
    var allZones = tableZones.Select(z => z.Name).Union(_customZones).Distinct().OrderBy(z => z).ToList();
    var zoneGroups = allZones.Select((z, i) => new { Name = z, Count = tableZones.FirstOrDefault(tz => tz.Name == z)?.Count ?? 0, Color = _zoneColors[i % _zoneColors.Length], Icon = _zoneIcons[i % _zoneIcons.Length] }).ToList();
    <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="map-pin" style="width:16px;height:16px;vertical-align:middle;margin-right:4px;"></i>Quản lý khu vực</h3>
            <button class="admin-btn-primary" style="font-size:12px;padding:6px 14px;" @onclick='() => { _showZoneForm = !_showZoneForm; _editingZoneOriginalName = null; _newZoneName = ""; _zoneFormMessage = null; }'>
                <i data-lucide="plus" style="width:14px;height:14px;margin-right:4px;"></i>Thêm khu vực
            </button>
        </div>
        <div class="admin-panel__body">
            @if (_showZoneForm)
            {
                <div style="margin-bottom:16px;padding:16px;border-radius:10px;border:1px solid rgba(245,158,11,0.3);background:var(--admin-bg-elevated);">
                    <div style="font-weight:600;font-size:13px;margin-bottom:8px;">@(_editingZoneOriginalName != null ? "Đổi tên khu vực" : "Thêm khu vực mới")</div>
                    <div style="display:flex;gap:8px;align-items:center;">
                        <input type="text" @bind="_newZoneName" placeholder="VD: Sảnh chính, VIP, Sân vườn" style="flex:1;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:13px;" />
                        <button class="admin-btn-primary" style="padding:8px 16px;font-size:12px;" @onclick="SaveZone"><i data-lucide="check" style="width:14px;height:14px;margin-right:4px;"></i>Lưu</button>
                        <button @onclick='() => _showZoneForm = false' style="padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;font-size:12px;"><i data-lucide="x" style="width:14px;height:14px;"></i></button>
                    </div>
                    @if (_zoneFormMessage != null) { <div style="margin-top:6px;font-size:12px;color:@(_zoneFormSuccess ? "#22C55E" : "#EF4444");">@_zoneFormMessage</div> }
                </div>
            }
            @if (!zoneGroups.Any())
            {
                @RenderEmpty("map-pin", "#F59E0B", "Chưa có khu vực nào", "Nhấn 'Thêm khu vực' ở trên để tạo khu vực đầu tiên", "", "", "")
            }
            else
            {
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:16px;">
                @foreach (var zone in zoneGroups)
                {
                    var rgbVal = zone.Color switch { "#3B82F6" => "59,130,246", "#A855F7" => "168,85,247", "#22C55E" => "34,197,94", "#F59E0B" => "245,158,11", "#EC4899" => "236,72,153", _ => "99,102,241" };
                    <div style="padding:20px;border-radius:12px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);">
                        <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                            <div style="width:40px;height:40px;border-radius:10px;background:rgba(@(rgbVal),0.15);display:flex;align-items:center;justify-content:center;">
                                <i data-lucide="@zone.Icon" style="width:20px;height:20px;color:@zone.Color;"></i>
                            </div>
                            <div>
                                <div style="font-weight:700;font-size:15px;">@zone.Name</div>
                                <div style="font-size:12px;color:var(--admin-text-tertiary);">@zone.Count bàn</div>
                            </div>
                        </div>
                        <div style="display:flex;gap:8px;margin-bottom:12px;">
                            <span style="font-size:11px;padding:3px 10px;border-radius:6px;background:rgba(34,197,94,0.12);color:#22C55E;">Đang hoạt động</span>
                        </div>
                        <div style="display:flex;gap:12px;border-top:1px solid var(--admin-border-subtle);padding-top:12px;">
                            <button @onclick='() => { _editingZoneOriginalName = zone.Name; _newZoneName = zone.Name; _showZoneForm = true; _zoneFormMessage = null; }' style="font-size:12px;color:var(--admin-orange-primary);background:none;border:none;cursor:pointer;display:flex;align-items:center;gap:4px;"><i data-lucide="pencil" style="width:12px;height:12px;"></i>Đổi tên</button>
                        </div>
                    </div>
                }
            </div>
            }
        </div>
    </div>
}

@* ═══ QR MODAL ═══ *@
@if (_showQrModal && _qrTable != null)
{
    <div style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.6);z-index:1000;display:flex;align-items:center;justify-content:center;" @onclick="() => _showQrModal = false">
        <div style="background:var(--admin-bg-elevated);border-radius:20px;padding:32px;width:400px;max-width:90vw;text-align:center;box-shadow:0 24px 48px rgba(0,0,0,0.3);" @onclick:stopPropagation>
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
                <h3 style="margin:0;font-size:18px;font-weight:700;">QR Code — Bàn @_qrTable.TableNumber</h3>
                <button @onclick="() => _showQrModal = false" style="background:none;border:none;cursor:pointer;color:var(--admin-text-tertiary);"><i data-lucide="x" style="width:20px;height:20px;"></i></button>
            </div>
            @if (_qrGenerating)
            {
                <div style="padding:40px;color:var(--admin-text-tertiary);">
                    <i data-lucide="loader" style="width:24px;height:24px;animation:spin 1s linear infinite;"></i>
                    <p style="margin-top:8px;">Đang tạo mã QR...</p>
                </div>
            }
            else if (!string.IsNullOrEmpty(_qrToken))
            {
                var qrUrl = $"{Nav.BaseUri}table/{_qrToken}";
                <div id="qr-code-container" style="background:white;border-radius:16px;padding:24px;margin-bottom:16px;display:inline-block;">
                    <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=@(Uri.EscapeDataString(qrUrl))" alt="QR Code" style="width:200px;height:200px;" />
                </div>
                <div style="margin-bottom:16px;">
                    <div style="font-size:12px;color:var(--admin-text-tertiary);margin-bottom:4px;">URL khách hàng:</div>
                    <div style="font-size:13px;padding:8px 12px;border-radius:8px;background:var(--admin-bg-main);border:1px solid var(--admin-border-subtle);word-break:break-all;color:var(--admin-text-primary);">@qrUrl</div>
                </div>
                <div style="display:flex;gap:8px;justify-content:center;">
                    <button @onclick='() => CopyQrUrl(qrUrl)' style="padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;font-size:12px;font-weight:600;display:flex;align-items:center;gap:6px;">
                        <i data-lucide="copy" style="width:14px;height:14px;"></i>Sao chép URL
                    </button>
                    <button @onclick='() => PrintQr(qrUrl)' style="padding:8px 16px;border-radius:8px;border:none;background:var(--admin-orange-primary);color:white;cursor:pointer;font-size:12px;font-weight:600;display:flex;align-items:center;gap:6px;">
                        <i data-lucide="printer" style="width:14px;height:14px;"></i>In QR
                    </button>
                </div>
                @if (_qrCopied)
                {
                    <div style="margin-top:8px;font-size:12px;color:#22C55E;">Đã sao chép!</div>
                }
            }
            else
            {
                <div style="padding:20px;">
                    <p style="color:var(--admin-text-tertiary);margin-bottom:16px;">Bàn chưa có mã QR. Tạo mã QR để khách hàng quét đặt món.</p>
                    <button class="admin-btn-primary" @onclick="GenerateQr" style="display:inline-flex;align-items:center;gap:8px;">
                        <i data-lucide="qr-code" style="width:16px;height:16px;"></i>Tạo mã QR
                    </button>
                </div>
            }
        </div>
    </div>
}

@code {
    [Parameter] public Guid ShopId { get; set; }
    [Parameter] public string SubSection { get; set; } = "tables";

    // Tables state
    private List<PosDataService.TableInfo> _tables = new();
    // View mode
    private bool _floorPlanView;
    // QR modal state
    private bool _showQrModal;
    private PosDataService.TableInfo? _qrTable;
    private string? _qrToken;
    private bool _qrGenerating;
    private bool _qrCopied;
    // Table form state
    private bool _showTableForm;
    private Guid? _editingTableId;
    private string _newTableNumber = "";
    private int _newTableCapacity = 4;
    private string _newTableZone = "";
    private decimal _newHourlyRate;
    private string? _tableFormMessage;
    private bool _tableFormSuccess;
    // Zone form state
    private bool _showZoneForm;
    private string _newZoneName = "";
    private string? _editingZoneOriginalName;
    private string? _zoneFormMessage;
    private bool _zoneFormSuccess;
    private readonly List<string> _customZones = new();
    private static readonly string[] _zoneColors = { "#3B82F6", "#A855F7", "#22C55E", "#F59E0B", "#EC4899", "#6366F1" };
    private static readonly string[] _zoneIcons = { "building", "crown", "trees", "wine", "coffee", "map-pin" };
    private List<string> AllZoneNames => _tables.Select(t => t.Zone ?? "Chung").Distinct()
        .Union(_customZones).Distinct().OrderBy(z => z).ToList();

    // ═══ FLOOR PLAN DRAG STATE ═══
    private Guid? _draggingTableId;
    private double _dragStartClientX, _dragStartClientY;
    private int _dragStartPosX, _dragStartPosY;
    private readonly Dictionary<Guid, (int X, int Y)> _localPositions = new();

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
            _tables = await DataService.GetTablesAsync(ShopId);
    }

    // ═══ FLOOR PLAN HELPERS ═══
    private (int X, int Y) GetPosition(Guid tableId)
    {
        if (_localPositions.TryGetValue(tableId, out var local))
            return local;
        var table = _tables.FirstOrDefault(t => t.Id == tableId);
        if (table?.PositionX != null && table.PositionY != null)
            return (table.PositionX.Value, table.PositionY.Value);
        // Auto-layout for tables without positions
        var idx = _tables.FindIndex(t => t.Id == tableId);
        var col = idx % 6;
        var row = idx / 6;
        return (40 + col * 120, 50 + row * 120);
    }

    private void OnTablePointerDown(Microsoft.AspNetCore.Components.Web.PointerEventArgs e, PosDataService.TableInfo table)
    {
        _draggingTableId = table.Id;
        var pos = GetPosition(table.Id);
        _dragStartClientX = e.ClientX;
        _dragStartClientY = e.ClientY;
        _dragStartPosX = pos.X;
        _dragStartPosY = pos.Y;
    }

    private void OnCanvasPointerMove(Microsoft.AspNetCore.Components.Web.PointerEventArgs e)
    {
        if (_draggingTableId == null) return;
        var newX = Math.Max(0, (int)(_dragStartPosX + (e.ClientX - _dragStartClientX)));
        var newY = Math.Max(0, (int)(_dragStartPosY + (e.ClientY - _dragStartClientY)));
        _localPositions[_draggingTableId.Value] = (newX, newY);
    }

    private async Task OnCanvasPointerUp(Microsoft.AspNetCore.Components.Web.PointerEventArgs e)
    {
        if (_draggingTableId == null) return;
        var tableId = _draggingTableId.Value;
        _draggingTableId = null;

        if (_localPositions.TryGetValue(tableId, out var pos))
        {
            try
            {
                await DataService.UpdateTablePositionAsync(tableId, pos.X, pos.Y);
            }
            catch { /* silently fail — position is still in local state */ }
        }
    }

    // ═══ TABLE CRUD ═══
    private void EditTable(PosDataService.TableInfo table)
    {
        _editingTableId = table.Id;
        _newTableNumber = table.TableNumber;
        _newTableCapacity = table.Capacity;
        _newTableZone = table.Zone ?? "";
        _newHourlyRate = table.HourlyRate;
        _tableFormMessage = null;
        _showTableForm = true;
    }

    private async Task AddTable()
    {
        _tableFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newTableNumber) || ShopId == Guid.Empty)
        {
            _tableFormMessage = "Vui lòng nhập số bàn."; _tableFormSuccess = false; return;
        }
        try
        {
            await DataService.CreateTableAsync(new PosDataService.CreateTableRequest(ShopId, _newTableNumber, _newTableCapacity, _newTableZone, _newHourlyRate > 0 ? _newHourlyRate : null));
            _tableFormMessage = $"Đã thêm bàn '{_newTableNumber}' thành công!"; _tableFormSuccess = true;
            _newTableNumber = ""; _newTableCapacity = 4; _newTableZone = ""; _newHourlyRate = 0;
            if (ShopId != Guid.Empty) _tables = await DataService.GetTablesAsync(ShopId);
        }
        catch (Exception ex) { _tableFormMessage = $"Lỗi: {ex.Message}"; _tableFormSuccess = false; }
    }

    private async Task SaveTable()
    {
        _tableFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newTableNumber) || ShopId == Guid.Empty || !_editingTableId.HasValue)
        {
            _tableFormMessage = "Vui lòng nhập số bàn."; _tableFormSuccess = false; return;
        }
        try
        {
            await DataService.UpdateTableAsync(_editingTableId.Value, new PosDataService.CreateTableRequest(ShopId, _newTableNumber, _newTableCapacity, _newTableZone, _newHourlyRate > 0 ? _newHourlyRate : null));
            _tableFormMessage = $"Đã cập nhật bàn '{_newTableNumber}' thành công!"; _tableFormSuccess = true;
            _editingTableId = null;
            if (ShopId != Guid.Empty) _tables = await DataService.GetTablesAsync(ShopId);
        }
        catch (Exception ex) { _tableFormMessage = $"Lỗi: {ex.Message}"; _tableFormSuccess = false; }
    }

    private async Task DeleteTableItem(Guid id)
    {
        try
        {
            await DataService.DeleteTableAsync(id);
            if (ShopId != Guid.Empty) _tables = await DataService.GetTablesAsync(ShopId);
        }
        catch (Exception ex) { Console.Error.WriteLine($"Không thể xóa bàn: {ex.Message}"); }
    }

    // ═══ ZONE MANAGEMENT ═══
    private async Task SaveZone()
    {
        _zoneFormMessage = null;
        if (string.IsNullOrWhiteSpace(_newZoneName) || ShopId == Guid.Empty)
        {
            _zoneFormMessage = "Vui lòng nhập tên khu vực."; _zoneFormSuccess = false; return;
        }
        if (_editingZoneOriginalName != null)
        {
            // Rename: update all tables in old zone to new zone name
            var tablesInZone = _tables.Where(t => (t.Zone ?? "Chung") == _editingZoneOriginalName).ToList();
            try
            {
                foreach (var t in tablesInZone)
                    await DataService.UpdateTableAsync(t.Id, new PosDataService.CreateTableRequest(ShopId, t.TableNumber, t.Capacity, _newZoneName.Trim()));
                _tables = await DataService.GetTablesAsync(ShopId);
                _zoneFormMessage = $"Đã đổi tên '{_editingZoneOriginalName}' → '{_newZoneName.Trim()}'"; _zoneFormSuccess = true;
                _editingZoneOriginalName = null; _newZoneName = ""; _showZoneForm = false;
            }
            catch (Exception ex) { _zoneFormMessage = $"Lỗi: {ex.Message}"; _zoneFormSuccess = false; }
        }
        else
        {
            var zoneName = _newZoneName.Trim();
            if (!_customZones.Contains(zoneName) && !_tables.Any(t => (t.Zone ?? "Chung") == zoneName))
                _customZones.Add(zoneName);
            _zoneFormMessage = $"Đã thêm khu vực '{zoneName}'."; _zoneFormSuccess = true;
            _newTableZone = zoneName;
            _newZoneName = "";
            _showZoneForm = false;
        }
    }

    // ═══ QR METHODS ═══
    private void ShowQrModal(PosDataService.TableInfo table)
    {
        _qrTable = table;
        _qrToken = table.QrToken;
        _qrGenerating = false;
        _qrCopied = false;
        _showQrModal = true;
    }

    private async Task GenerateQr()
    {
        if (_qrTable == null) return;
        _qrGenerating = true;
        try
        {
            var token = await DataService.GenerateTableQrTokenAsync(_qrTable.Id);
            if (token != null)
            {
                _qrToken = token;
                _tables = await DataService.GetTablesAsync(ShopId);
            }
        }
        catch (Exception ex) { Console.Error.WriteLine($"QR generation failed: {ex.Message}"); }
        finally { _qrGenerating = false; }
    }

    private async Task CopyQrUrl(string url)
    {
        try
        {
            await JS.InvokeVoidAsync("navigator.clipboard.writeText", url);
            _qrCopied = true;
            StateHasChanged();
        }
        catch { }
    }

    private async Task PrintQr(string url)
    {
        try
        {
            await JS.InvokeVoidAsync("eval", $"var w=window.open('','_blank','width=400,height=500');w.document.write('<html><body style=\"text-align:center;font-family:sans-serif;padding:40px\"><h2>Bàn {_qrTable?.TableNumber}</h2><img src=\"https://api.qrserver.com/v1/create-qr-code/?size=300x300&data='+encodeURIComponent('{url}')+'\" /><p style=\"font-size:12px;color:#666;margin-top:16px\">{url}</p></body></html>');w.document.close();w.print();");
        }
        catch { }
    }

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