@*
    EN: End-of-Day Report — Covers, revenue, avg check, tip total, by-section breakdown.
    VI: Báo cáo cuối ngày — Lượt khách, doanh thu, hóa đơn TB, tổng tip, phân tích theo khu vực.
*@
@page "/pos/{ShopId:guid}/restaurant/eod-report"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

<div style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
    @* ═══ HEADER / TIÊU ĐỀ ═══ *@
    <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);display:flex;align-items:center;gap:12px;">
        <button class="pos-category-tab" @onclick="@(() => NavigateTo("restaurant"))">
            <i data-lucide="arrow-left" style="width:14px;"></i> Quay lại
        </button>
        <span style="font-size:16px;font-weight:700;">Báo cáo cuối ngày</span>
        <span style="flex:1;"></span>
        <span style="font-size:13px;color:var(--pos-text-tertiary);">@DateTime.Today.ToString("dd/MM/yyyy")</span>
        <button class="pos-category-tab"><i data-lucide="printer" style="width:14px;"></i> In báo cáo</button>
    </div>

    @if (_isLoading)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Đang tải báo cáo...
        </div>
    }
    else if (_loadError)
    {
        <div style="flex:1;display:flex;align-items:center;justify-content:center;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu báo cáo
        </div>
    }
    else
    {
    <div style="flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:16px;">
        @* ═══ SUMMARY CARDS / THẺ TỔNG QUAN ═══ *@
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;">
            @foreach (var card in _summaryCards)
            {
                <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;
                            display:flex;flex-direction:column;gap:6px;">
                    <div style="display:flex;align-items:center;gap:8px;">
                        <i data-lucide="@card.Icon" style="width:16px;color:@card.Color;"></i>
                        <span style="font-size:12px;color:var(--pos-text-tertiary);">@card.Label</span>
                    </div>
                    <span style="font-size:22px;font-weight:700;color:@card.Color;">@card.Value</span>
                    <span style="font-size:11px;color:var(--pos-text-tertiary);">@card.Comparison</span>
                </div>
            }
        </div>

        @* ═══ SECTION BREAKDOWN / PHÂN TÍCH THEO KHU VỰC ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;">
            <div style="font-size:14px;font-weight:700;margin-bottom:12px;">Doanh thu theo khu vực</div>
            <div style="display:flex;flex-direction:column;gap:10px;">
                @foreach (var s in _sectionData)
                {
                    <div>
                        <div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:4px;">
                            <span style="font-weight:500;">@s.Name</span>
                            <span style="font-weight:600;">@FormatPrice(s.Revenue) (@s.Covers lượt khách)</span>
                        </div>
                        @* EN: Progress bar / VI: Thanh tiến trình *@
                        <div style="height:8px;border-radius:4px;background:var(--pos-bg-interactive);overflow:hidden;">
                            <div style="height:100%;width:@(s.Percent)%;border-radius:4px;background:@s.Color;transition:width .3s ease;"></div>
                        </div>
                    </div>
                }
            </div>
        </div>

        @* ═══ HOURLY BREAKDOWN / PHÂN TÍCH THEO GIỜ ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;">
            <div style="font-size:14px;font-weight:700;margin-bottom:12px;">Doanh thu theo giờ</div>
            <div style="display:flex;align-items:flex-end;gap:6px;height:120px;">
                @foreach (var h in _hourlyData)
                {
                    <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px;">
                        <div style="width:100%;border-radius:4px 4px 0 0;background:var(--pos-orange-primary);
                                    height:@(h.Percent)%;min-height:4px;transition:height .3s ease;"></div>
                        <span style="font-size:10px;color:var(--pos-text-tertiary);">@h.Hour</span>
                    </div>
                }
            </div>
        </div>

        @* ═══ PAYMENT METHODS / PHƯƠNG THỨC THANH TOÁN ═══ *@
        <div style="background:var(--pos-bg-elevated);border-radius:var(--pos-radius);padding:16px;">
            <div style="font-size:14px;font-weight:700;margin-bottom:12px;">Phương thức thanh toán</div>
            <div style="display:flex;flex-direction:column;gap:8px;">
                @foreach (var p in _paymentData)
                {
                    <div style="display:flex;align-items:center;gap:12px;padding:8px 0;border-bottom:1px solid var(--pos-border-subtle);">
                        <i data-lucide="@p.Icon" style="width:16px;color:var(--pos-text-tertiary);"></i>
                        <span style="flex:1;font-size:13px;">@p.Method</span>
                        <span style="font-size:13px;font-weight:600;">@p.Count đơn</span>
                        <span style="font-size:14px;font-weight:700;color:var(--pos-orange-primary);min-width:100px;text-align:right;">
                            @FormatPrice(p.Amount)
                        </span>
                    </div>
                }
            </div>
        </div>
    </div>
    }
</div>

@code {
    // EN: Loading state / VI: Trạng thái tải
    private bool _isLoading = true;
    private bool _loadError;

    // EN: Summary cards / VI: Thẻ tổng quan
    private List<SummaryCard> _summaryCards = new();

    // EN: Section breakdown / VI: Phân tích khu vực
    private List<SectionReport> _sectionData = new();

    // EN: Hourly data / VI: Dữ liệu theo giờ
    private List<HourData> _hourlyData = new();

    // EN: Payment methods / VI: Phương thức thanh toán
    private List<PaymentReport> _paymentData = new();

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

        try
        {
            // EN: Load dashboard data for today / VI: Tải dữ liệu dashboard cho hôm nay
            var dashboard = await DataService.GetPosDashboardAsync(ShopId, "today");

            // EN: Map dashboard response to summary cards / VI: Ánh xạ response dashboard sang thẻ tổng quan
            _summaryCards = new()
            {
                new("Doanh thu", FormatPrice(dashboard.Revenue), "trending-up", "var(--pos-orange-primary)", $"{dashboard.OrderCount} đơn hôm nay"),
                new("Số đơn", dashboard.OrderCount.ToString(), "shopping-bag", "var(--pos-info)", $"TB {FormatPrice(dashboard.AvgOrderValue)}/đơn"),
                new("Hóa đơn TB", FormatPrice(dashboard.AvgOrderValue), "receipt", "var(--pos-success)", $"Tổng {dashboard.ItemsSold} món"),
                new("Sản phẩm bán", dashboard.ItemsSold.ToString(), "package", "var(--pos-warning)", $"Doanh thu {FormatPrice(dashboard.Revenue)}"),
            };

            // EN: Map hourly revenue data / VI: Ánh xạ dữ liệu doanh thu theo giờ
            if (dashboard.HourlyRevenue?.Any() == true)
            {
                var maxRevenue = dashboard.HourlyRevenue.Max(h => h.Revenue);
                _hourlyData = dashboard.HourlyRevenue.Select(h => new HourData(
                    h.HourLabel,
                    maxRevenue > 0 ? (int)(h.Revenue / maxRevenue * 100) : 0
                )).ToList();
            }

            // EN: Map payment breakdown / VI: Ánh xạ phân tích PTTT
            if (dashboard.PaymentBreakdown?.Any() == true)
            {
                static string MapIcon(string method) => method.ToLowerInvariant() switch
                {
                    "cash" or "tiền mặt" => "banknote",
                    "card" or "thẻ" => "credit-card",
                    "transfer" or "chuyển khoản" or "bank_transfer" => "smartphone",
                    "qr" => "smartphone",
                    _ => "wallet"
                };
                static string MapMethodName(string method) => method.ToLowerInvariant() switch
                {
                    "cash" => "Tiền mặt",
                    "card" => "Thẻ ngân hàng",
                    "transfer" or "bank_transfer" => "Chuyển khoản",
                    "qr" => "QR Code",
                    _ => method
                };
                _paymentData = dashboard.PaymentBreakdown.Select(p =>
                    new PaymentReport(MapMethodName(p.Method), MapIcon(p.Method), p.Count, p.Amount)).ToList();
            }

            // EN: Section breakdown — use popular items as proxy if no section data
            // VI: Phân tích khu vực — dùng sản phẩm phổ biến thay thế nếu không có dữ liệu khu vực
            if (dashboard.PopularItems?.Any() == true)
            {
                var maxRev = dashboard.PopularItems.Max(p => p.Revenue);
                var colors = new[] { "var(--pos-orange-primary)", "var(--pos-warning)", "var(--pos-success)", "var(--pos-info)", "var(--pos-danger)" };
                _sectionData = dashboard.PopularItems.Take(5).Select((p, i) => new SectionReport(
                    p.Name,
                    p.Revenue,
                    p.Qty,
                    maxRev > 0 ? (int)(p.Revenue / maxRev * 100) : 0,
                    colors[i % colors.Length]
                )).ToList();
            }
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private record SummaryCard(string Label, string Value, string Icon, string Color, string Comparison);
    private record SectionReport(string Name, decimal Revenue, int Covers, int Percent, string Color);
    private record HourData(string Hour, int Percent);
    private record PaymentReport(string Method, string Icon, int Count, decimal Amount);
}
