@page "/table/{Token}"
@layout WebClientTpos.Client.Layout.CustomerLayout
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject NavigationManager Nav

@if (_loading)
{
    <div style="display:flex;align-items:center;justify-content:center;min-height:100vh;">
        <div style="text-align:center;color:#6B7280;">
            <div style="width:48px;height:48px;border:3px solid #E5E7EB;border-top-color:#F59E0B;border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 16px;"></div>
            <p>Đang tải menu...</p>
        </div>
    </div>
}
else if (_error != null)
{
    <div style="display:flex;align-items:center;justify-content:center;min-height:100vh;">
        <div style="text-align:center;padding:40px;">
            <div style="width:64px;height:64px;border-radius:50%;background:#FEF2F2;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
                <span style="font-size:28px;">!</span>
            </div>
            <h2 style="font-size:20px;font-weight:700;color:#1F2937;margin:0 0 8px;">Không tìm thấy bàn</h2>
            <p style="color:#6B7280;font-size:14px;">@_error</p>
        </div>
    </div>
}
else
{
    @* ═══ HEADER ═══ *@
    <div style="background:white;box-shadow:0 1px 3px rgba(0,0,0,0.1);position:sticky;top:0;z-index:50;">
        <div style="max-width:640px;margin:0 auto;padding:16px 20px;">
            <div style="display:flex;align-items:center;justify-content:space-between;">
                <div>
                    <h1 style="font-size:18px;font-weight:700;color:#1F2937;margin:0;">@_shopName</h1>
                    <p style="font-size:13px;color:#6B7280;margin:4px 0 0;">Bàn @_tableNumber</p>
                </div>
                <div style="display:flex;gap:8px;">
                    @if (_cart.Any())
                    {
                        <button @onclick='() => _showCart = !_showCart' style="position:relative;padding:8px 16px;border-radius:10px;border:none;background:#F59E0B;color:white;font-weight:600;font-size:14px;cursor:pointer;">
                            Giỏ hàng (@_cart.Sum(c => c.Qty))
                        </button>
                    }
                    <button @onclick="CallStaff" style="padding:8px 16px;border-radius:10px;border:2px solid #F59E0B;background:transparent;color:#F59E0B;font-weight:600;font-size:14px;cursor:pointer;">
                        @(_staffCalled ? "Đã gọi!" : "Gọi NV")
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div style="max-width:640px;margin:0 auto;padding:20px;">
        @* ═══ CATEGORY TABS ═══ *@
        @if (_categories.Any())
        {
            <div style="display:flex;gap:8px;overflow-x:auto;padding-bottom:12px;margin-bottom:16px;-webkit-overflow-scrolling:touch;">
                <button @onclick='() => _selectedCategory = null'
                    style="white-space:nowrap;padding:8px 16px;border-radius:20px;border:none;font-size:13px;font-weight:600;cursor:pointer;@(_selectedCategory == null ? "background:#F59E0B;color:white;" : "background:#F3F4F6;color:#6B7280;")">
                    Tất cả
                </button>
                @foreach (var cat in _categories)
                {
                    <button @onclick='() => _selectedCategory = cat.Id'
                        style="white-space:nowrap;padding:8px 16px;border-radius:20px;border:none;font-size:13px;font-weight:600;cursor:pointer;@(_selectedCategory == cat.Id ? "background:#F59E0B;color:white;" : "background:#F3F4F6;color:#6B7280;")">
                        @cat.Name
                    </button>
                }
            </div>
        }

        @* ═══ PRODUCTS ═══ *@
        @if (!FilteredProducts.Any())
        {
            <div style="text-align:center;padding:40px;color:#9CA3AF;">
                <p style="font-size:48px;margin:0;">🍽️</p>
                <p style="margin-top:8px;">Chưa có sản phẩm nào</p>
            </div>
        }
        else
        {
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:12px;">
                @foreach (var product in FilteredProducts)
                {
                    var inCart = _cart.FirstOrDefault(c => c.ProductId == product.Id);
                    <div style="background:white;border-radius:14px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.08);border:1px solid #F3F4F6;">
                        <div style="padding:16px;text-align:center;">
                            <div style="font-size:14px;font-weight:600;color:#1F2937;margin-bottom:4px;line-height:1.3;">@product.Name</div>
                            @if (!string.IsNullOrEmpty(product.Description))
                            {
                                <div style="font-size:11px;color:#9CA3AF;margin-bottom:8px;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">@product.Description</div>
                            }
                            <div style="font-size:15px;font-weight:700;color:#F59E0B;margin-bottom:10px;">@FormatVND(product.Price)</div>
                            @if (inCart != null)
                            {
                                <div style="display:flex;align-items:center;justify-content:center;gap:12px;">
                                    <button @onclick='() => UpdateCartQty(product.Id, -1)' style="width:32px;height:32px;border-radius:50%;border:2px solid #E5E7EB;background:white;color:#374151;font-size:16px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;">−</button>
                                    <span style="font-size:16px;font-weight:700;color:#1F2937;min-width:20px;text-align:center;">@inCart.Qty</span>
                                    <button @onclick='() => UpdateCartQty(product.Id, 1)' style="width:32px;height:32px;border-radius:50%;border:none;background:#F59E0B;color:white;font-size:16px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;">+</button>
                                </div>
                            }
                            else
                            {
                                <button @onclick='() => AddToCart(product)' style="width:100%;padding:8px;border-radius:10px;border:none;background:#FEF3C7;color:#92400E;font-weight:600;font-size:13px;cursor:pointer;">
                                    + Thêm
                                </button>
                            }
                        </div>
                    </div>
                }
            </div>
        }
    </div>

    @* ═══ CART PANEL ═══ *@
    @if (_showCart && _cart.Any())
    {
        <div style="position:fixed;bottom:0;left:0;right:0;background:white;box-shadow:0 -4px 16px rgba(0,0,0,0.1);border-radius:20px 20px 0 0;z-index:100;max-height:60vh;overflow-y:auto;">
            <div style="max-width:640px;margin:0 auto;padding:20px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
                    <h3 style="font-size:18px;font-weight:700;color:#1F2937;margin:0;">Giỏ hàng</h3>
                    <button @onclick='() => _showCart = false' style="background:none;border:none;font-size:20px;color:#9CA3AF;cursor:pointer;">✕</button>
                </div>
                @foreach (var item in _cart)
                {
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 0;border-bottom:1px solid #F3F4F6;">
                        <div>
                            <div style="font-size:14px;font-weight:600;color:#1F2937;">@item.Name</div>
                            <div style="font-size:12px;color:#9CA3AF;">@FormatVND(item.Price) × @item.Qty</div>
                        </div>
                        <div style="font-size:14px;font-weight:700;color:#1F2937;">@FormatVND(item.Price * item.Qty)</div>
                    </div>
                }
                <div style="display:flex;justify-content:space-between;align-items:center;padding-top:16px;margin-top:8px;">
                    <span style="font-size:16px;font-weight:700;color:#1F2937;">Tổng cộng</span>
                    <span style="font-size:20px;font-weight:700;color:#F59E0B;">@FormatVND(_cart.Sum(c => c.Price * c.Qty))</span>
                </div>
                <button @onclick="PlaceOrder" disabled="@_ordering" style="width:100%;padding:14px;border-radius:12px;border:none;background:#F59E0B;color:white;font-size:16px;font-weight:700;cursor:pointer;margin-top:16px;">
                    @(_ordering ? "Đang gửi..." : "Đặt món")
                </button>
                @if (_orderMessage != null)
                {
                    <div style="margin-top:8px;text-align:center;font-size:14px;color:@(_orderSuccess ? "#059669" : "#DC2626");">@_orderMessage</div>
                }
            </div>
        </div>
    }

    @* ═══ STAFF CALLED TOAST ═══ *@
    @if (_staffCalled)
    {
        <div style="position:fixed;top:80px;left:50%;transform:translateX(-50%);background:#059669;color:white;padding:12px 24px;border-radius:12px;font-size:14px;font-weight:600;z-index:200;box-shadow:0 4px 12px rgba(0,0,0,0.15);">
            Đã thông báo nhân viên!
        </div>
    }
}

<style>
    @@keyframes spin { to { transform: rotate(360deg); } }
</style>

@code {
    [Parameter] public string Token { get; set; } = "";

    private bool _loading = true;
    private string? _error;
    private Guid _shopId;
    private Guid _tableId;
    private string _tableNumber = "";
    private string _shopName = "";

    private List<PosDataService.ProductInfo> _products = new();
    private List<PosDataService.CategoryInfo> _categories = new();
    private Guid? _selectedCategory;

    private readonly List<CartItem> _cart = new();
    private bool _showCart;
    private bool _ordering;
    private string? _orderMessage;
    private bool _orderSuccess;
    private bool _staffCalled;

    private IEnumerable<PosDataService.ProductInfo> FilteredProducts =>
        _selectedCategory == null ? _products : _products.Where(p => p.CategoryId == _selectedCategory);

    protected override async Task OnInitializedAsync()
    {
        try
        {
            var tableInfo = await DataService.GetTableByTokenAsync(Token);
            if (tableInfo == null)
            {
                _error = "Mã QR không hợp lệ hoặc đã hết hạn.";
                _loading = false;
                return;
            }

            _tableId = tableInfo.Id;
            _shopId = tableInfo.ShopId;
            _tableNumber = tableInfo.TableNumber;

            var shop = await DataService.GetShopByIdAsync(_shopId);
            _shopName = shop?.Name ?? "Nhà hàng";

            _products = await DataService.GetProductsAsync(_shopId);
            _categories = await DataService.GetCategoriesAsync(_shopId);
        }
        catch
        {
            _error = "Không thể tải menu. Vui lòng thử lại.";
        }
        _loading = false;
    }

    private void AddToCart(PosDataService.ProductInfo product)
    {
        _cart.Add(new CartItem(product.Id, product.Name, product.Price, 1));
    }

    private void UpdateCartQty(Guid productId, int delta)
    {
        var item = _cart.FirstOrDefault(c => c.ProductId == productId);
        if (item == null) return;
        item.Qty += delta;
        if (item.Qty <= 0) _cart.Remove(item);
    }

    private async Task PlaceOrder()
    {
        _ordering = true;
        _orderMessage = null;
        try
        {
            var items = _cart.Select(c => new PosDataService.PosOrderItemRequest(
                c.ProductId, c.Name, c.Qty, c.Price, "PreparedFood")).ToList();
            var req = new PosDataService.CreatePosOrderRequest(
                _shopId, null, items, null, null, null, _tableId);
            var result = await DataService.CreatePosOrderAsync(req);
            if (result != null)
            {
                _orderMessage = "Đặt món thành công! Món sẽ được phục vụ sớm nhất.";
                _orderSuccess = true;
                _cart.Clear();
                _showCart = false;
            }
            else
            {
                _orderMessage = "Không thể đặt món. Vui lòng thử lại.";
                _orderSuccess = false;
            }
        }
        catch
        {
            _orderMessage = "Lỗi khi đặt món. Vui lòng thử lại.";
            _orderSuccess = false;
        }
        _ordering = false;
    }

    private async Task CallStaff()
    {
        _staffCalled = true;
        StateHasChanged();
        await Task.Delay(3000);
        _staffCalled = false;
        StateHasChanged();
    }

    private static string FormatVND(decimal amount) => $"{amount:N0}đ";

    private class CartItem
    {
        public Guid ProductId { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Qty { get; set; }
        public CartItem(Guid productId, string name, decimal price, int qty)
        { ProductId = productId; Name = name; Price = price; Qty = qty; }
    }
}
