@*
    EN: Retail POS Tablet — Touch-optimized 2-column: products + cart sidebar (340px), larger elements.
    VI: POS Bán lẻ Tablet — 2 cột tối ưu cảm ứng: sản phẩm + giỏ hàng bên (340px), phần tử lớn hơn.
*@
@page "/pos/{ShopId:guid}/retail/tablet"
@layout PosLayout
@inherits PosBase
@inject WebClientTpos.Client.Services.PosDataService DataService

@* ═══ PRODUCT PANEL ═══ *@
<div class="pos-product-panel">
    @* EN: Barcode input / VI: Ô nhập mã vạch *@
    <div style="padding:12px 16px;border-bottom:1px solid var(--pos-border-subtle);">
        <div style="display:flex;align-items:center;gap:8px;background:var(--pos-bg-interactive);border-radius:var(--pos-radius);padding:0 14px;">
            <i data-lucide="scan-barcode" style="width:18px;height:18px;color:var(--pos-text-tertiary);"></i>
            <input type="text" @bind="_barcodeInput" @bind:event="oninput" placeholder="Quét mã vạch hoặc nhập SKU..."
                   style="flex:1;background:transparent;border:none;color:var(--pos-text-primary);font-size:15px;
                          padding:12px 0;outline:none;font-family:inherit;" />
        </div>
    </div>

    @if (_isLoading)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;color:var(--pos-text-tertiary);">
            Đang tải...
        </div>
    }
    else if (_loadError)
    {
        <div style="display:flex;align-items:center;justify-content:center;flex:1;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">
            @foreach (var cat in _categories)
            {
                <button class="pos-category-tab @(cat == _selectedCategory ? "pos-category-tab--active" : "")"
                        style="padding:12px 20px;font-size:15px;"
                        @onclick="() => _selectedCategory = cat">
                    @cat
                </button>
            }
        </div>

        @* EN: Product grid (larger for tablet) / VI: Lưới sản phẩm (lớn hơn cho tablet) *@
        <div class="pos-product-grid" style="grid-template-columns:repeat(auto-fill, minmax(160px, 1fr));gap:16px;padding:20px;">
            @foreach (var product in FilteredProducts)
            {
                <div class="pos-product-card" style="padding:16px;" @onclick="() => AddToCart(product)">
                    <div class="pos-product-card__image" style="display:flex;align-items:center;justify-content:center;">
                        <i data-lucide="@product.Icon" style="width:36px;height:36px;color:var(--pos-text-tertiary);"></i>
                    </div>
                    <span class="pos-product-card__name" style="font-size:15px;">@product.Name</span>
                    <span class="pos-product-card__price" style="font-size:16px;">@FormatPrice(product.Price)</span>
                    <span style="font-size:11px;color:var(--pos-text-tertiary);">@product.Sku</span>
                </div>
            }
        </div>
    }
</div>

@* ═══ CART SIDEBAR ═══ *@
<div class="pos-cart-panel" style="width:340px;min-width:340px;">
    <div class="pos-cart-header">
        <span class="pos-cart-header__title" style="font-size:17px;">Giỏ hàng</span>
        <button style="background:none;border:none;color:var(--pos-danger);font-size:13px;cursor:pointer;"
                @onclick="() => _cartItems.Clear()">Xóa tất cả</button>
    </div>

    <div class="pos-cart-items">
        @foreach (var item in _cartItems)
        {
            <div class="pos-cart-item" style="padding:14px 12px;">
                <div class="pos-cart-item__info">
                    <span class="pos-cart-item__name" style="font-size:15px;">@item.Name</span>
                    <span style="font-size:11px;color:var(--pos-text-tertiary);">@item.Sku</span>
                    <span class="pos-cart-item__price">@FormatPrice(item.Price)</span>
                </div>
                <div class="pos-cart-item__qty">
                    <button style="width:36px;height:36px;border-radius:10px;border:1px solid var(--pos-border-default);background:transparent;color:var(--pos-text-primary);font-size:18px;cursor:pointer;"
                            @onclick="() => ChangeQty(item, -1)">−</button>
                    <span style="font-size:16px;font-weight:600;min-width:24px;text-align:center;">@item.Qty</span>
                    <button style="width:36px;height:36px;border-radius:10px;border:1px solid var(--pos-border-default);background:transparent;color:var(--pos-text-primary);font-size:18px;cursor:pointer;"
                            @onclick="() => ChangeQty(item, 1)">+</button>
                </div>
            </div>
        }
    </div>

    <div class="pos-cart-footer">
        <div style="padding:0 12px 8px;font-size:13px;">
            <div style="display:flex;justify-content:space-between;color:var(--pos-text-tertiary);margin-bottom:4px;">
                <span>Tạm tính</span>
                <span>@FormatPrice(CartTotal)</span>
            </div>
            <div style="display:flex;justify-content:space-between;color:var(--pos-text-tertiary);">
                <span>VAT (10%)</span>
                <span>@FormatPrice(CartTotal * 0.1m)</span>
            </div>
        </div>
        <div class="pos-cart-total">
            <span class="pos-cart-total__label">Tổng cộng</span>
            <span class="pos-cart-total__value">@FormatPrice(CartTotal * 1.1m)</span>
        </div>
        <button class="pos-btn-checkout" style="height:56px;font-size:17px;" @onclick="Checkout">
            Thanh toán — @FormatPrice(CartTotal * 1.1m)
        </button>
    </div>
</div>

@code {

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

    // EN: Categories / VI: Danh mục
    private string[] _categories = { "Tất cả" };
    private string _selectedCategory = "Tất cả";
    private string _barcodeInput = "";

    // EN: Product list from API / VI: Danh sách sản phẩm từ API
    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);

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

        try
        {
            var apiProducts = await DataService.GetProductsAsync(ShopId);

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

            var cats = _products.Select(p => p.Category).Distinct().ToList();
            _categories = new[] { "Tất cả" }.Concat(cats).ToArray();
        }
        catch
        {
            _loadError = true;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void AddToCart(Product product)
    {
        var existing = _cartItems.FirstOrDefault(i => i.Sku == product.Sku);
        if (existing != null) existing.Qty++;
        else _cartItems.Add(new CartItem(product.Name, product.Sku, product.Price));
    }

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

    private void Checkout() => NavigateTo("payment-method-select");

    private static string GetCategoryIcon(string category) => category switch
    {
        "Thời trang" => "shirt", "Phụ kiện" => "shopping-bag", "Điện tử" => "headphones",
        "Gia dụng" => "cooking-pot", "Mỹ phẩm" => "sparkles", _ => "package"
    };

    // EN: Models / VI: Mô hình dữ liệu
    private record Product(string Name, string Sku, decimal Price, string Category, string Icon);
    private class CartItem(string name, string sku, decimal price)
    {
        public string Name { get; set; } = name;
        public string Sku { get; set; } = sku;
        public decimal Price { get; set; } = price;
        public int Qty { get; set; } = 1;
    }
}
