@*
    EN: Queue Display — Public-facing queue board: preparing list, ready list, large order numbers.
        Connected to kitchen tickets API with auto-refresh.
    VI: Bang hien thi hang doi — Bang cong khai: danh sach dang pha, san sang, so don lon.
        Ket noi API kitchen tickets voi tu dong lam moi.
*@
@page "/pos/{ShopId:guid}/cafe/queue-display"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService
@implements IDisposable

<div style="display:flex;height:100%;gap:2px;padding:16px;">
    @* EN: Preparing column / VI: Cot dang pha *@
    <div style="flex:1;display:flex;flex-direction:column;gap:16px;">
        <div style="text-align:center;padding:16px;background:var(--pos-bg-elevated);border-radius:var(--pos-radius);">
            <div style="font-size:14px;color:var(--pos-warning);font-weight:600;text-transform:uppercase;letter-spacing:1px;">
                <i data-lucide="coffee" style="width:16px;height:16px;display:inline;"></i> Dang pha che
            </div>
            <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:4px;">Preparing (@_preparingGroups.Count)</div>
        </div>

        <div style="flex:1;display:grid;grid-template-columns:repeat(2, 1fr);gap:12px;align-content:start;">
            @{ int prepIdx = 0; }
            @foreach (var group in _preparingGroups)
            {
                prepIdx++;
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;text-align:center;border:1px solid rgba(245,158,11,0.3);">
                    <div style="font-size:42px;font-weight:800;color:var(--pos-warning);line-height:1;">#@prepIdx</div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:8px;">@string.Join(", ", group.Items)</div>
                    <div style="display:flex;align-items:center;justify-content:center;gap:4px;margin-top:8px;">
                        <span style="width:6px;height:6px;border-radius:50%;background:var(--pos-warning);animation:pulse 1.5s infinite;"></span>
                        <span style="font-size:11px;color:var(--pos-warning);">@GetElapsed(group.CreatedAt)</span>
                    </div>
                </div>
            }
        </div>
    </div>

    @* EN: Divider / VI: Duong phan cach *@
    <div style="width:2px;background:var(--pos-border-subtle);margin:0 8px;"></div>

    @* EN: Ready column / VI: Cot san sang *@
    <div style="flex:1;display:flex;flex-direction:column;gap:16px;">
        <div style="text-align:center;padding:16px;background:var(--pos-bg-elevated);border-radius:var(--pos-radius);">
            <div style="font-size:14px;color:var(--pos-success);font-weight:600;text-transform:uppercase;letter-spacing:1px;">
                <i data-lucide="check-circle" style="width:16px;height:16px;display:inline;"></i> San sang
            </div>
            <div style="font-size:11px;color:var(--pos-text-tertiary);margin-top:4px;">Ready for pickup (@_readyGroups.Count)</div>
        </div>

        <div style="flex:1;display:grid;grid-template-columns:repeat(2, 1fr);gap:12px;align-content:start;">
            @{ int readyIdx = 0; }
            @foreach (var group in _readyGroups)
            {
                readyIdx++;
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:20px;text-align:center;border:1px solid rgba(34,197,94,0.3);animation:readyGlow 2s ease-in-out infinite alternate;">
                    <div style="font-size:42px;font-weight:800;color:var(--pos-success);line-height:1;">#@readyIdx</div>
                    <div style="font-size:12px;color:var(--pos-text-tertiary);margin-top:8px;">@string.Join(", ", group.Items)</div>
                    <div style="font-size:11px;color:var(--pos-success);margin-top:6px;">Moi nhan do</div>
                </div>
            }
        </div>
    </div>
</div>

@* EN: Pulse animation / VI: Hieu ung nhap nhay *@
<style>
    @@keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.3; }
    }
    @@keyframes readyGlow {
        from { box-shadow: 0 0 8px rgba(34, 197, 94, 0.1); }
        to { box-shadow: 0 0 16px rgba(34, 197, 94, 0.25); }
    }
</style>

@code {
    private List<TicketGroup> _preparingGroups = new();
    private List<TicketGroup> _readyGroups = new();
    private System.Threading.Timer? _refreshTimer;

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

        _refreshTimer = new System.Threading.Timer(async _ =>
        {
            await LoadTickets();
            await InvokeAsync(StateHasChanged);
        }, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
    }

    private async Task LoadTickets()
    {
        try
        {
            var tickets = await DataService.GetKitchenTicketsAsync(ShopId);
            _preparingGroups = tickets
                .Where(t => t.Status?.ToLower() is "pending" or "preparing" or "in-progress")
                .GroupBy(t => t.SessionId)
                .Select(g => new TicketGroup(g.Select(t => t.ItemName ?? "Mon").ToList(), g.Min(t => t.CreatedAt)))
                .OrderBy(g => g.CreatedAt)
                .ToList();

            _readyGroups = tickets
                .Where(t => t.Status?.ToLower() is "ready" or "completed")
                .GroupBy(t => t.SessionId)
                .Select(g => new TicketGroup(g.Select(t => t.ItemName ?? "Mon").ToList(), g.Min(t => t.CreatedAt)))
                .OrderByDescending(g => g.CreatedAt)
                .Take(10)
                .ToList();
        }
        catch { /* silent for display screen */ }
    }

    private static string GetElapsed(DateTime createdAt)
    {
        var elapsed = DateTime.Now - createdAt;
        if (elapsed.TotalMinutes < 1) return "vua xong";
        return $"{(int)elapsed.TotalMinutes} phut";
    }

    public void Dispose() => _refreshTimer?.Dispose();

    private record TicketGroup(List<string> Items, DateTime CreatedAt);
}
