@*
    EN: Café POS Mobile — Single column: categories, product grid, floating cart button.
        All data fetched from API — no hardcoded demo data.
    VI: POS Café Mobile — Một cột: danh mục, lưới sản phẩm, nút giỏ hàng nổi.
        Toàn bộ dữ liệu lấy từ API — không có dữ liệu demo cứng.
*@
@page "/pos/{ShopId:guid}/cafe/mobile"
@layout PosLayout
@inherits PosBase
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject IJSRuntime JS

<div style="display:flex;flex-direction:column;width:100%;height:100%;overflow:hidden;">
    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;height:100%;color:var(--pos-text-tertiary);">
            Không thể tải dữ liệu
        </div>
    }
    else
    {
    @* EN: Category tabs / VI: Tab danh mục *@
    <div class="pos-category-tabs" style="padding:8px 12px;">
        @foreach (var cat in _categories)
        {
            <button class="pos-category-tab @(cat == _selectedCategory ? "pos-category-tab--active" : "")"
                    style="padding:10px 16px;font-size:14px;"
                    @onclick="() => _selectedCategory = cat">
                @cat
            </button>
        }
    </div>

    @* EN: Product grid / VI: Lưới sản phẩm *@
    <div class="pos-product-grid" style="grid-template-columns:repeat(2, 1fr);gap:10px;padding:12px;">
        @foreach (var product in FilteredProducts)
        {
            <div class="pos-product-card" style="padding:10px;" @onclick="() => AddToCart(product)">
                <div class="pos-product-card__image" style="aspect-ratio:1.2;display:flex;align-items:center;justify-content:center;">
                    <i data-lucide="coffee" style="width:28px;height:28px;color:var(--pos-text-tertiary);"></i>
                </div>
                <span class="pos-product-card__name" style="font-size:12px;">@product.Name</span>
                <span class="pos-product-card__price" style="font-size:13px;">@FormatPrice(product.Price)</span>
            </div>
        }
    </div>

    @* EN: Floating cart button / VI: Nút giỏ hàng nổi *@
    @if (_cartItems.Any())
    {
        <button style="position:fixed;bottom:20px;right:20px;width:64px;height:64px;border-radius:50%;background:var(--pos-orange-primary);border:none;color:#fff;font-size:20px;cursor:pointer;box-shadow:0 4px 20px rgba(255,92,0,0.4);display:flex;align-items:center;justify-content:center;z-index:100;"
                @onclick="() => _showCart = !_showCart">
            <i data-lucide="shopping-cart" style="width:24px;height:24px;"></i>
            <span style="position:absolute;top:-4px;right:-4px;background:var(--pos-danger);color:#fff;font-size:11px;font-weight:700;width:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;">
                @_cartItems.Sum(i => i.Qty)
            </span>
        </button>
    }

    @* EN: Bottom sheet cart / VI: Giỏ hàng dạng sheet dưới *@
    @if (_showCart)
    {
        <div class="pos-dialog-overlay" @onclick="() => _showCart = false">
            <div style="position:fixed;bottom:0;left:0;right:0;max-height:70vh;background:var(--pos-bg-elevated);border-radius:20px 20px 0 0;display:flex;flex-direction:column;overflow:hidden;"
                 @onclick:stopPropagation="true">
                @* EN: Handle bar / VI: Thanh kéo *@
                <div style="padding:12px;display:flex;justify-content:center;">
                    <div style="width:40px;height:4px;border-radius:2px;background:var(--pos-border-default);"></div>
                </div>

                @if (_paymentStep == PayStep.None)
                {
                    @* ─── NORMAL CART MODE ─── *@
                    <div class="pos-cart-header">
                        <span class="pos-cart-header__title">Giỏ hàng</span>
                        <button style="background:none;border:none;color:var(--pos-danger);font-size:13px;cursor:pointer;"
                                @onclick="ClearCart">Xóa</button>
                    </div>

                    <div class="pos-cart-items" style="max-height:40vh;">
                        @foreach (var item in _cartItems)
                        {
                            <div class="pos-cart-item">
                                <div class="pos-cart-item__info">
                                    <span class="pos-cart-item__name">@item.Name</span>
                                    <span class="pos-cart-item__price">@FormatPrice(item.Price)</span>
                                </div>
                                <div class="pos-cart-item__qty">
                                    <button @onclick="() => ChangeQty(item, -1)">−</button>
                                    <span style="font-size:14px;font-weight:600;">@item.Qty</span>
                                    <button @onclick="() => ChangeQty(item, 1)">+</button>
                                </div>
                            </div>
                        }
                    </div>

                    <div class="pos-cart-footer">
                        <!-- Voucher input -->
                        <div style="display:flex;gap:6px;margin-bottom:8px;">
                            <input type="text" @bind="_voucherCode" placeholder="Mã voucher..." style="flex:1;padding:8px 10px;border:1px solid var(--pos-border);border-radius:8px;font-size:12px;background:var(--pos-bg-elevated);color:var(--pos-text-primary);" />
                            <button @onclick="ValidateVoucher" style="padding:6px 12px;border-radius:8px;border:none;background:rgba(139,92,246,0.1);color:#8B5CF6;font-size:11px;font-weight:600;cursor:pointer;">Áp dụng</button>
                            @if (_appliedVoucher != null)
                            {
                                <button @onclick="ClearVoucher" style="padding:6px 8px;border-radius:8px;border:none;background:rgba(239,68,68,0.1);color:#EF4444;font-size:11px;cursor:pointer;" title="Xóa voucher"><i data-lucide="x" style="width:12px;height:12px;"></i></button>
                            }
                        </div>
                        @if (_voucherMessage != null)
                        {
                            <div style="font-size:11px;margin-bottom:6px;color:@(_appliedVoucher != null ? "#16A34A" : "#EF4444");">@_voucherMessage</div>
                        }
                        @if (_appliedVoucher != null)
                        {
                            <div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:12px;">
                                <span style="color:var(--pos-text-tertiary);">Giảm giá (@_appliedVoucher.CampaignName)</span>
                                <span style="color:#16A34A;font-weight:600;">-@FormatPrice(_discountAmount)</span>
                            </div>
                        }
                        <div class="pos-cart-total">
                            <span class="pos-cart-total__label">Tổng cộng</span>
                            <span class="pos-cart-total__value">@FormatPrice(FinalTotal)</span>
                        </div>
                        @if (!string.IsNullOrEmpty(_orderError))
                        {
                            <div style="font-size:11px;margin-bottom:6px;color:#EF4444;">@_orderError</div>
                        }
                        <button class="pos-btn-checkout" @onclick="StartPayment" disabled="@(!_cartItems.Any() || _orderCreating)">
                            @if (_orderCreating)
                            {
                                <span>Đang tạo đơn...</span>
                            }
                            else
                            {
                                <span>Thanh toán</span>
                            }
                        </button>
                    </div>
                }
                else if (_paymentStep == PayStep.MethodSelect)
                {
                    @* ─── PAYMENT: METHOD SELECT ─── *@
                    <div class="pos-payment-panel" style="flex:1;display:flex;flex-direction:column;">
                        <div class="pos-payment-header">
                            <button class="pos-payment-header__back" @onclick="CancelPayment">
                                <i data-lucide="arrow-left" style="width:16px;height:16px;"></i>
                            </button>
                            <span style="font-weight:600;">Thanh toán</span>
                            <span style="margin-left:auto;font-size:18px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(FinalTotal)</span>
                        </div>
                        <div class="pos-payment-methods" style="padding:16px;">
                            <button class="pos-payment-method-btn" @onclick='() => SelectPaymentMethod("cash")'>
                                <span class="pos-payment-method-btn__icon"><i data-lucide="wallet" style="width:28px;height:28px;"></i></span>
                                <span class="pos-payment-method-btn__label">Tiền mặt</span>
                            </button>
                            @if (_payCardEnabled)
                            {
                            <button class="pos-payment-method-btn" @onclick='() => SelectPaymentMethod("card")'>
                                <span class="pos-payment-method-btn__icon"><i data-lucide="credit-card" style="width:28px;height:28px;"></i></span>
                                <span class="pos-payment-method-btn__label">Thẻ</span>
                            </button>
                            }
                            @if (_payQrEnabled)
                            {
                            <button class="pos-payment-method-btn" @onclick='() => SelectPaymentMethod("qr")'>
                                <span class="pos-payment-method-btn__icon"><i data-lucide="smartphone" style="width:28px;height:28px;"></i></span>
                                <span class="pos-payment-method-btn__label">Mã QR</span>
                            </button>
                            }
                            @if (_payTransferEnabled)
                            {
                            <button class="pos-payment-method-btn" @onclick='() => SelectPaymentMethod("transfer")'>
                                <span class="pos-payment-method-btn__icon"><i data-lucide="building-2" style="width:28px;height:28px;"></i></span>
                                <span class="pos-payment-method-btn__label">Chuyển khoản</span>
                            </button>
                            }
                        </div>
                    </div>
                }
                else if (_paymentStep == PayStep.AmountInput)
                {
                    @* ─── PAYMENT: CASH AMOUNT INPUT ─── *@
                    <div class="pos-payment-panel" style="flex:1;display:flex;flex-direction:column;">
                        <div class="pos-payment-header">
                            <button class="pos-payment-header__back" @onclick="() => _paymentStep = PayStep.MethodSelect">
                                <i data-lucide="arrow-left" style="width:16px;height:16px;"></i>
                            </button>
                            <span style="font-weight:600;display:flex;align-items:center;gap:6px;"><i data-lucide="wallet" style="width:16px;height:16px;"></i> Tiền mặt</span>
                            <span style="margin-left:auto;font-size:16px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(FinalTotal)</span>
                        </div>
                        <div class="pos-payment-amount-section" style="flex:1;overflow-y:auto;padding:16px;">
                            <div style="font-size:13px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:10px;">Số tiền nhanh</div>
                            <div class="pos-payment-quick-amounts">
                                @foreach (var qa in GetQuickAmounts())
                                {
                                    <button class="pos-payment-quick-btn @(_receivedAmount == qa.Value ? "pos-payment-quick-btn--selected" : "")"
                                            @onclick="() => _receivedAmount = qa.Value">
                                        @qa.Label
                                    </button>
                                }
                            </div>
                            <div style="font-size:13px;font-weight:600;color:var(--pos-text-secondary);margin-bottom:8px;">Nhập số tiền</div>
                            <input type="number" class="pos-payment-input" placeholder="Nhập số tiền..."
                                   @bind="_customAmountInput" @bind:event="oninput" />
                            @if (!string.IsNullOrEmpty(_customAmountInput))
                            {
                                <button style="width:100%;padding:10px;border-radius:var(--pos-radius);border:none;background:var(--pos-bg-interactive);color:var(--pos-text-primary);cursor:pointer;font-size:13px;font-weight:600;margin-bottom:16px;"
                                        @onclick="ApplyCustomAmount">Áp dụng</button>
                            }
                            <div class="pos-payment-change">
                                <div class="pos-payment-change__row">
                                    <span style="color:var(--pos-text-tertiary);">Khách đưa</span>
                                    <span style="font-weight:600;">@FormatPrice(_receivedAmount)</span>
                                </div>
                                <div class="pos-payment-change__row" style="padding-top:8px;border-top:1px dashed var(--pos-border-subtle);">
                                    <span style="color:var(--pos-text-tertiary);">Tiền thối</span>
                                    <span style="font-size:18px;font-weight:700;color:@(ChangeAmount >= 0 ? "var(--pos-success)" : "var(--pos-danger)");">
                                        @FormatPrice(ChangeAmount)
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div style="padding:16px;border-top:1px solid var(--pos-border-subtle);">
                            <button class="pos-btn-checkout" @onclick="ConfirmPayment" disabled="@(_receivedAmount < FinalTotal)">
                                Xác nhận thanh toán
                            </button>
                        </div>
                    </div>
                }
                else if (_paymentStep == PayStep.Processing)
                {
                    @* ─── PAYMENT: QR/CARD/TRANSFER — Confirm ─── *@
                    <div class="pos-payment-panel" style="flex:1;display:flex;flex-direction:column;">
                        <div class="pos-payment-header">
                            <button class="pos-payment-header__back" @onclick="() => _paymentStep = PayStep.MethodSelect">
                                <i data-lucide="arrow-left" style="width:16px;height:16px;"></i>
                            </button>
                            <span style="font-weight:600;">@GetMethodLabel()</span>
                        </div>
                        <div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;padding:24px;">
                            <div style="font-size:32px;font-weight:700;color:var(--pos-orange-primary);">@FormatPrice(FinalTotal)</div>
                            @if (_selectedMethod == "qr")
                            {
                                <div style="width:160px;height:160px;background:white;border-radius:12px;display:flex;align-items:center;justify-content:center;">
                                    <div style="color:#333;font-size:14px;font-weight:600;text-align:center;">QR Code<br/>VietQR</div>
                                </div>
                                <div style="font-size:12px;color:var(--pos-text-tertiary);">Quét mã bằng app Ngân hàng / MoMo / ZaloPay</div>
                            }
                            else if (_selectedMethod == "card")
                            {
                                <div><i data-lucide="credit-card" style="width:48px;height:48px;color:var(--pos-text-secondary);"></i></div>
                                <div style="font-size:14px;color:var(--pos-text-secondary);">Chạm, quẹt hoặc cắm thẻ</div>
                            }
                            else
                            {
                                <div><i data-lucide="building-2" style="width:48px;height:48px;color:var(--pos-text-secondary);"></i></div>
                                <div style="font-size:14px;color:var(--pos-text-secondary);">Xác nhận đã nhận chuyển khoản</div>
                            }
                        </div>
                        <div style="padding:16px;border-top:1px solid var(--pos-border-subtle);">
                            <button class="pos-btn-checkout" @onclick="ConfirmPayment">
                                Xác nhận đã thanh toán
                            </button>
                        </div>
                    </div>
                }
                else if (_paymentStep == PayStep.Success)
                {
                    @* ─── PAYMENT: SUCCESS ─── *@
                    <div class="pos-payment-success" style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:24px;">
                        <div class="pos-payment-success__circle">
                            <div class="pos-payment-success__inner">
                                <i data-lucide="check" style="width:28px;height:28px;color:#fff;stroke-width:3;"></i>
                            </div>
                        </div>
                        <div style="font-size:18px;font-weight:700;color:var(--pos-success);">Thanh toán thành công!</div>
                        <div style="font-size:14px;color:var(--pos-text-tertiary);">@FormatPrice(_lastOrderTotal)</div>
                        <div style="font-size:12px;color:var(--pos-text-tertiary);">Mã: @_lastTransactionId</div>
                        <div style="display:flex;gap:10px;margin-top:8px;">
                            <button style="padding:10px 20px;border-radius:var(--pos-radius);border:1px solid var(--pos-border-default);background:transparent;color:var(--pos-text-primary);cursor:pointer;font-size:13px;font-weight:600;"
                                    @onclick="PrintReceipt">
                                <i data-lucide="printer" style="width:14px;height:14px;vertical-align:middle;margin-right:4px;"></i>In hóa đơn
                            </button>
                            <button style="padding:10px 20px;border-radius:var(--pos-radius);border:none;background:var(--pos-orange-primary);color:#fff;cursor:pointer;font-size:13px;font-weight:600;"
                                    @onclick="ResetAfterPayment">
                                <i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-right:4px;"></i>Đơn mới
                            </button>
                        </div>
                    </div>
                }
            </div>
        </div>
    }
    }
</div>

@code {

    // ═══════════════ SALE — Product & Cart ═══════════════
    private bool _isLoading = true;
    private bool _loadError;
    private string[] _categories = { "Tất cả" };
    private string _selectedCategory = "Tất cả";
    private bool _showCart;
    private List<Product> _products = new();
    private readonly List<CartItem> _cartItems = new();
    private IEnumerable<Product> FilteredProducts =>
        _selectedCategory == "Tất cả" ? _products : _products.Where(p => p.Category == _selectedCategory);
    private decimal CartTotal => _cartItems.Sum(i => i.Price * i.Qty);
    private decimal FinalTotal => Math.Max(0, CartTotal - _discountAmount);

    // Voucher state
    private string _voucherCode = "";
    private string? _voucherMessage;
    private PosDataService.VoucherValidationInfo? _appliedVoucher;
    private decimal _discountAmount;

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

        try
        {
            var productsTask = DataService.GetProductsAsync(ShopId);
            var categoriesTask = DataService.GetCategoriesAsync(ShopId);
            await Task.WhenAll(productsTask, categoriesTask);

            var apiProducts = await productsTask;
            var apiCategories = await categoriesTask;

            _products = apiProducts.Select(p => new Product(
                p.Id,
                p.Name,
                p.Price,
                p.CategoryName ?? "Khác"
            )).ToList();

            var catNames = apiCategories.Select(c => c.Name).ToList();
            if (catNames.Count > 0)
                _categories = new[] { "Tất cả" }.Concat(catNames).ToArray();
            else
            {
                var productCats = _products.Select(p => p.Category).Distinct().ToList();
                _categories = new[] { "Tất cả" }.Concat(productCats).ToArray();
            }
        }
        catch { _loadError = true; }
        finally { _isLoading = false; }

        await LoadPaymentSettings();
        await RestoreCartFromLocalStorage();
    }

    private async Task AddToCart(Product product)
    {
        if (_paymentStep != PayStep.None) return;
        var existing = _cartItems.FirstOrDefault(i => i.ProductId == product.Id);
        if (existing != null) existing.Qty++;
        else _cartItems.Add(new CartItem(product.Id, product.Name, product.Price));
        await SaveCartToLocalStorage();
    }

    private async Task ChangeQty(CartItem item, int delta)
    {
        item.Qty += delta;
        if (item.Qty <= 0) _cartItems.Remove(item);
        await SaveCartToLocalStorage();
    }

    private async Task ClearCart()
    {
        _cartItems.Clear();
        _showCart = false;
        await SaveCartToLocalStorage();
    }

    // ═══════════════ VOUCHER ═══════════════
    private async Task ValidateVoucher()
    {
        _voucherMessage = null; _appliedVoucher = null; _discountAmount = 0;
        if (string.IsNullOrWhiteSpace(_voucherCode)) { _voucherMessage = "Vui lòng nhập mã voucher."; return; }
        var info = await DataService.ValidateVoucherAsync(_voucherCode.Trim());
        if (info == null) { _voucherMessage = "Không thể kiểm tra voucher."; return; }
        if (!info.IsValid) { _voucherMessage = info.ErrorMessage ?? "Mã voucher không hợp lệ."; return; }
        _appliedVoucher = info;
        var isPercentage = (info.CampaignName ?? "").Contains("[percentage]", StringComparison.OrdinalIgnoreCase);
        if (isPercentage)
        {
            var pct = Math.Min(info.RemainingValue ?? 0, 100);
            _discountAmount = Math.Round(CartTotal * pct / 100, 0);
            _voucherMessage = $"Voucher {info.CampaignName?.Replace("[percentage]","").Trim()}: giảm {pct}% = {FormatPrice(_discountAmount)}";
        }
        else
        {
            _discountAmount = Math.Min(info.RemainingValue ?? 0, CartTotal);
            _voucherMessage = $"Voucher {info.CampaignName}: giảm {FormatPrice(_discountAmount)}";
        }
    }
    private void ClearVoucher() { _appliedVoucher = null; _discountAmount = 0; _voucherCode = ""; _voucherMessage = null; }

    // ═══════════════ INLINE PAYMENT ═══════════════
    private enum PayStep { None, MethodSelect, AmountInput, Processing, Success }
    private PayStep _paymentStep = PayStep.None;
    private string _selectedMethod = "";
    private decimal _receivedAmount;
    private string _customAmountInput = "";
    private decimal _lastOrderTotal;
    private string _lastTransactionId = "";
    private string _lastPaymentMethod = "";
    private List<(string Name, int Qty, decimal Price)> _lastReceiptItems = new();
    private decimal ChangeAmount => _receivedAmount - FinalTotal;

    // EN: Created order ID — set when order is submitted to API before payment
    // VI: ID đơn hàng đã tạo — gán khi đơn được gửi lên API trước thanh toán
    private Guid? _createdOrderId;
    private string? _orderError;
    private bool _orderCreating;

    private async Task StartPayment()
    {
        if (!_cartItems.Any()) return;
        if (_orderCreating) return;
        _orderCreating = true;
        _orderError = null;
        StateHasChanged();

        try
        {
            var orderReq = new PosDataService.CreatePosOrderRequest(
                ShopId,
                null,
                _cartItems.Select(i => new PosDataService.PosOrderItemRequest(
                    i.ProductId, i.Name, i.Qty, i.Price)).ToList(),
                _discountAmount > 0 ? _discountAmount : null,
                _appliedVoucher != null ? "voucher" : null,
                _appliedVoucher?.VoucherCode);

            var result = await DataService.CreatePosOrderAsync(orderReq);
            if (result != null)
            {
                _createdOrderId = result.OrderId;
                _paymentStep = PayStep.MethodSelect;
            }
            else
            {
                _orderError = "Không thể tạo đơn hàng. Vui lòng thử lại.";
            }
        }
        catch (Exception ex)
        {
            _orderError = $"Lỗi tạo đơn: {ex.Message}";
        }
        finally
        {
            _orderCreating = false;
            StateHasChanged();
        }
    }

    private async Task CancelPayment()
    {
        if (_createdOrderId.HasValue)
        {
            try { await DataService.CancelOrderAsync(_createdOrderId.Value); } catch { }
            _createdOrderId = null;
        }
        _paymentStep = PayStep.None;
        _selectedMethod = "";
        _receivedAmount = 0;
        _customAmountInput = "";
    }

    private void SelectPaymentMethod(string method)
    {
        _selectedMethod = method;
        _receivedAmount = 0;
        _customAmountInput = "";

        if (method == "cash")
            _paymentStep = PayStep.AmountInput;
        else
            _paymentStep = PayStep.Processing;
    }

    private string GetMethodLabel() => _selectedMethod switch
    {
        "cash" => "Tiền mặt",
        "card" => "Thẻ",
        "qr" => "Mã QR",
        "transfer" => "Chuyển khoản",
        _ => "Thanh toán"
    };

    private List<(string Label, decimal Value)> GetQuickAmounts()
    {
        var total = FinalTotal;
        var amounts = new List<(string, decimal)>();
        var roundUp = Math.Ceiling(total / 50_000) * 50_000;
        if (roundUp == total) roundUp += 50_000;
        amounts.Add(("Đúng tiền", total));
        amounts.Add((FormatPrice(roundUp), roundUp));
        amounts.Add((FormatPrice(roundUp + 50_000), roundUp + 50_000));
        amounts.Add((FormatPrice(500_000), 500_000));
        amounts.Add((FormatPrice(200_000), 200_000));
        amounts.Add((FormatPrice(1_000_000), 1_000_000));
        return amounts;
    }

    private void ApplyCustomAmount()
    {
        if (decimal.TryParse(_customAmountInput, out var val))
            _receivedAmount = val;
    }

    private bool _paymentProcessing;
    private string? _paymentError;

    private async Task ConfirmPayment()
    {
        if (_paymentProcessing) return;
        _paymentProcessing = true;
        _paymentError = null;
        StateHasChanged();

        _lastOrderTotal = FinalTotal;
        _lastPaymentMethod = _selectedMethod;
        _lastReceiptItems = _cartItems.Select(i => (i.Name, i.Qty, i.Price)).ToList();

        bool paymentSuccess = false;
        try
        {
            if (_createdOrderId.HasValue)
            {
                var amount = _selectedMethod == "cash" ? _receivedAmount : FinalTotal;
                var result = await DataService.PayOrderWithDetailsAsync(
                    _createdOrderId.Value, ShopId, _selectedMethod, amount);
                paymentSuccess = result?.Success ?? false;
                _lastTransactionId = _createdOrderId.Value.ToString()[..8].ToUpper();
            }

            if (!paymentSuccess)
            {
                _paymentError = "Thanh toán thất bại. Vui lòng thử lại.";
                _paymentProcessing = false;
                StateHasChanged();
                return;
            }

            if (_appliedVoucher?.VoucherId != null && _discountAmount > 0)
            {
                try { await DataService.RedeemVoucherAsync(_appliedVoucher.VoucherId.Value, _discountAmount); } catch { }
            }
        }
        catch (Exception ex)
        {
            _paymentError = $"Lỗi thanh toán: {ex.Message}. Vui lòng thử lại.";
            _paymentProcessing = false;
            StateHasChanged();
            return;
        }

        _paymentProcessing = false;
        _paymentStep = PayStep.Success;
        StateHasChanged();
    }

    private async Task ResetAfterPayment()
    {
        _cartItems.Clear();
        _paymentStep = PayStep.None;
        _selectedMethod = "";
        _receivedAmount = 0;
        _customAmountInput = "";
        _createdOrderId = null;
        _orderError = null;
        _showCart = false;
        ClearVoucher();
        await SaveCartToLocalStorage();
    }

    private async Task PrintReceipt()
    {
        var payLabel = _lastPaymentMethod switch { "cash" => "Tiền mặt", "card" => "Thẻ", "qr" => "QR Code", _ => "Chuyển khoản" };
        var now = DateTime.Now;

        var sb = new System.Text.StringBuilder();
        foreach (var item in _lastReceiptItems)
        {
            sb.AppendLine($"<tr><td style='text-align:left;padding:3px 0;'>{System.Net.WebUtility.HtmlEncode(item.Name)}</td>");
            sb.AppendLine($"<td style='text-align:center;padding:3px 4px;'>{item.Qty}</td>");
            sb.AppendLine($"<td style='text-align:right;padding:3px 0;'>{item.Price:N0}</td>");
            sb.AppendLine($"<td style='text-align:right;padding:3px 0;font-weight:600;'>{item.Qty * item.Price:N0}</td></tr>");
        }

        var receiptHtml = "<!DOCTYPE html><html><head><meta charset='utf-8'>" +
            $"<title>Hóa đơn - {_lastTransactionId}</title>" +
            "<style>" +
            "@page { margin: 4mm; size: 80mm auto; }" +
            "body { font-family: 'Courier New', monospace; font-size: 12px; width: 72mm; margin: 0 auto; color: #000; }" +
            ".c { text-align: center; } .b { font-weight: bold; }" +
            ".d { border-top: 1px dashed #000; margin: 6px 0; }" +
            "table { width: 100%; border-collapse: collapse; }" +
            "th { text-align: left; font-size: 11px; border-bottom: 1px solid #000; padding: 2px 0; }" +
            ".f { font-size: 10px; text-align: center; margin-top: 8px; color: #555; }" +
            "</style></head><body>" +
            "<div class='c b' style='font-size:16px;'>aPOS POS</div>" +
            "<div class='c' style='font-size:10px;margin-bottom:4px;'>Hệ thống quản lý bán hàng thông minh</div>" +
            "<div class='d'></div>" +
            $"<div><b>Mã đơn:</b> {_lastTransactionId}</div>" +
            $"<div><b>Ngày:</b> {now:dd/MM/yyyy} — {now:HH:mm:ss}</div>" +
            $"<div><b>Thanh toán:</b> {payLabel}</div>" +
            "<div class='d'></div>" +
            "<table><tr><th>Sản phẩm</th><th style='text-align:center;'>SL</th><th style='text-align:right;'>Đ.Giá</th><th style='text-align:right;'>T.Tiền</th></tr>" +
            sb.ToString() +
            "</table><div class='d'></div>" +
            $"<div style='display:flex;justify-content:space-between;font-size:14px;font-weight:bold;'><span>TỔNG CỘNG</span><span>{_lastOrderTotal:N0}₫</span></div>" +
            "<div class='d'></div>" +
            "<div class='f'>Cảm ơn quý khách! Hẹn gặp lại</div>" +
            "<div class='f'>Powered by aPOS Platform</div>" +
            "<script>window.onload=function(){window.print();window.onafterprint=function(){window.close();}}</script>" +
            "</body></html>";

        await JS.InvokeVoidAsync("printPosReceipt", receiptHtml);
    }

    // ═══════════════ PAYMENT SETTINGS ═══════════════
    private bool _payCardEnabled = true;
    private bool _payQrEnabled = true;
    private bool _payTransferEnabled = true;

    private async Task LoadPaymentSettings()
    {
        try
        {
            var json = await JS.InvokeAsync<string?>("localStorage.getItem", "pos_payment_settings");
            if (!string.IsNullOrEmpty(json))
            {
                var doc = System.Text.Json.JsonDocument.Parse(json);
                var r = doc.RootElement;
                if (r.TryGetProperty("cardEnabled", out var ce)) _payCardEnabled = ce.GetBoolean();
                if (r.TryGetProperty("qrEnabled", out var qe)) _payQrEnabled = qe.GetBoolean();
                if (r.TryGetProperty("transferEnabled", out var te)) _payTransferEnabled = te.GetBoolean();
            }
        }
        catch { /* first load — no settings yet */ }
    }

    // ═══════════════ LOCALSTORAGE PERSISTENCE ═══════════════
    private string CartStorageKey => $"pos_cafe_cart_{ShopId}";

    private async Task SaveCartToLocalStorage()
    {
        try
        {
            var cartData = _cartItems.Select(i => new { i.ProductId, i.Name, i.Price, i.Qty }).ToList();
            await JS.InvokeVoidAsync("localStorage.setItem", CartStorageKey,
                System.Text.Json.JsonSerializer.Serialize(cartData));
        }
        catch { }
    }

    private async Task RestoreCartFromLocalStorage()
    {
        try
        {
            var cartJson = await JS.InvokeAsync<string?>("localStorage.getItem", CartStorageKey);
            if (!string.IsNullOrEmpty(cartJson))
            {
                var items = System.Text.Json.JsonSerializer.Deserialize<List<StoredCartItem>>(cartJson, _lsJsonOptions);
                if (items != null)
                    foreach (var i in items)
                        _cartItems.Add(new CartItem(i.ProductId, i.Name, i.Price) { Qty = i.Qty });
            }
        }
        catch { }
    }

    private static readonly System.Text.Json.JsonSerializerOptions _lsJsonOptions = new()
    {
        PropertyNameCaseInsensitive = true
    };

    private record StoredCartItem(Guid ProductId, string Name, decimal Price, int Qty);

    // ═══════════════ RECORDS ═══════════════
    private record Product(Guid Id, string Name, decimal Price, string Category);
    private class CartItem(Guid productId, string name, decimal price)
    {
        public Guid ProductId { get; set; } = productId;
        public string Name { get; set; } = name;
        public decimal Price { get; set; } = price;
        public int Qty { get; set; } = 1;
    }
}
