@page "/menu/{ShopId:guid}"
@page "/menu/{ShopId:guid}/{TableId:guid}"
@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:#FF5C00;border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 16px;"></div>
            <p style="font-size:14px;">Đang tải thực đơn...</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;">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#EF4444" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
            </div>
            <h2 style="font-size:20px;font-weight:700;color:#1F2937;margin:0 0 8px;">Không tìm thấy thực đơn</h2>
            <p style="color:#6B7280;font-size:14px;">@_error</p>
        </div>
    </div>
}
else
{
    @* ═══ STICKY HEADER ═══ *@
    <div style="background:white;box-shadow:0 1px 3px rgba(0,0,0,0.08);position:sticky;top:0;z-index:50;">
        <div style="max-width:640px;margin:0 auto;padding:12px 16px;">
            <div style="display:flex;align-items:center;gap:12px;">
                @if (!string.IsNullOrEmpty(_shop?.LogoUrl))
                {
                    <img src="@_shop.LogoUrl" alt="@_shop.Name" style="width:40px;height:40px;border-radius:10px;object-fit:cover;" />
                }
                else
                {
                    <div style="width:40px;height:40px;border-radius:10px;background:linear-gradient(135deg,#FF5C00,#FF8A3D);display:flex;align-items:center;justify-content:center;">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2l2 7h14l2-7"/><path d="M3 9v11a2 2 0 002 2h14a2 2 0 002-2V9"/></svg>
                    </div>
                }
                <div style="flex:1;min-width:0;">
                    <h1 style="font-size:16px;font-weight:700;color:#1F2937;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">@(_shop?.Name ?? "Thực đơn")</h1>
                    @if (!string.IsNullOrEmpty(_shop?.Address))
                    {
                        <p style="font-size:12px;color:#9CA3AF;margin:2px 0 0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">@_shop.Address</p>
                    }
                </div>
            </div>

            @* ═══ SEARCH BAR ═══ *@
            <div style="margin-top:10px;position:relative;">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9CA3AF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);pointer-events:none;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                <input type="text" @bind="_searchQuery" @bind:event="oninput" placeholder="Tìm kiếm món ăn..."
                    style="width:100%;padding:10px 12px 10px 36px;border-radius:10px;border:1px solid #E5E7EB;background:#F9FAFB;font-size:14px;color:#1F2937;outline:none;box-sizing:border-box;" />
                @if (!string.IsNullOrEmpty(_searchQuery))
                {
                    <button @onclick='() => _searchQuery = ""' style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#9CA3AF;font-size:16px;line-height:1;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    </button>
                }
            </div>
        </div>
    </div>

    <div style="max-width:640px;margin:0 auto;padding:12px 16px 120px;">
        @* ═══ CATEGORY TABS ═══ *@
        @if (_categories.Count > 1 && string.IsNullOrEmpty(_searchQuery))
        {
            <div style="display:flex;gap:8px;overflow-x:auto;padding-bottom:12px;margin-bottom:8px;-webkit-overflow-scrolling:touch;scrollbar-width:none;">
                <button @onclick='() => _selectedCategoryId = null'
                    style="white-space:nowrap;padding:8px 16px;border-radius:20px;border:none;font-size:13px;font-weight:600;cursor:pointer;flex-shrink:0;transition:all .2s;@(_selectedCategoryId == null ? "background:#FF5C00;color:white;" : "background:#F3F4F6;color:#6B7280;")">
                    Tất cả
                </button>
                @foreach (var cat in _categories)
                {
                    var catId = cat.Id;
                    <button @onclick='() => _selectedCategoryId = catId'
                        style="white-space:nowrap;padding:8px 16px;border-radius:20px;border:none;font-size:13px;font-weight:600;cursor:pointer;flex-shrink:0;transition:all .2s;@(_selectedCategoryId == catId ? "background:#FF5C00;color:white;" : "background:#F3F4F6;color:#6B7280;")">
                        @cat.Name (@cat.Items.Count)
                    </button>
                }
            </div>
        }

        @* ═══ MENU ITEMS ═══ *@
        @if (!FilteredItems.Any())
        {
            <div style="text-align:center;padding:60px 20px;color:#9CA3AF;">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#D1D5DB" stroke-width="1.5" style="margin:0 auto 12px;display:block;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                <p style="font-size:15px;font-weight:600;color:#6B7280;margin:0 0 4px;">Không tìm thấy món nào</p>
                <p style="font-size:13px;margin:0;">Thử tìm kiếm với từ khóa khác</p>
            </div>
        }
        else if (!string.IsNullOrEmpty(_searchQuery))
        {
            @* ═══ SEARCH RESULTS — FLAT LIST ═══ *@
            <div style="display:grid;grid-template-columns:1fr;gap:12px;">
                @foreach (var item in FilteredItems)
                {
                    @RenderMenuItem(item)
                }
            </div>
        }
        else
        {
            @* ═══ CATEGORIZED VIEW ═══ *@
            @foreach (var category in DisplayCategories)
            {
                <div style="margin-bottom:20px;">
                    <h2 style="font-size:16px;font-weight:700;color:#1F2937;margin:0 0 12px;padding-bottom:8px;border-bottom:1px solid #F3F4F6;">
                        @category.Name
                        <span style="font-size:12px;font-weight:400;color:#9CA3AF;margin-left:6px;">@category.Items.Count món</span>
                    </h2>
                    <div style="display:grid;grid-template-columns:1fr;gap:12px;">
                        @foreach (var item in category.Items)
                        {
                            @RenderMenuItem(item)
                        }
                    </div>
                </div>
            }
        }
    </div>

    @* ═══ STICKY BOTTOM BAR ═══ *@
    @if (_cart.Any())
    {
        <div style="position:fixed;bottom:0;left:0;right:0;z-index:100;">
            <div style="max-width:640px;margin:0 auto;padding:0 16px 16px;">
                <button @onclick='() => _showCart = true'
                    style="width:100%;padding:14px 20px;border-radius:14px;border:none;background:#FF5C00;color:white;cursor:pointer;display:flex;align-items:center;justify-content:space-between;box-shadow:0 4px 20px rgba(255,92,0,0.35);box-sizing:border-box;">
                    <div style="display:flex;align-items:center;gap:10px;">
                        <div style="width:28px;height:28px;border-radius:8px;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;">
                            @_cart.Sum(c => c.Qty)
                        </div>
                        <span style="font-size:15px;font-weight:600;">Giỏ hàng</span>
                    </div>
                    <span style="font-size:16px;font-weight:700;">@FormatVND(_cart.Sum(c => c.Price * c.Qty))</span>
                </button>
            </div>
        </div>
    }

    @* ═══ CART PANEL ═══ *@
    @if (_showCart && _cart.Any())
    {
        <div @onclick='() => _showCart = false' style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.4);z-index:200;"></div>
        <div style="position:fixed;bottom:0;left:0;right:0;background:white;box-shadow:0 -4px 24px rgba(0,0,0,0.12);border-radius:20px 20px 0 0;z-index:201;max-height:70vh;overflow-y:auto;">
            <div style="max-width:640px;margin:0 auto;padding:20px 16px;">
                <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="width:32px;height:32px;border-radius:8px;background:#F3F4F6;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#6B7280" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    </button>
                </div>
                @foreach (var item in _cart)
                {
                    <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 0;border-bottom:1px solid #F3F4F6;">
                        <div style="flex:1;min-width:0;">
                            <div style="font-size:14px;font-weight:600;color:#1F2937;">@item.Name</div>
                            <div style="font-size:13px;color:#FF5C00;font-weight:600;margin-top:2px;">@FormatVND(item.Price)</div>
                        </div>
                        <div style="display:flex;align-items:center;gap:10px;margin-left:12px;">
                            <button @onclick='() => UpdateCartQty(item.ProductId, -1)' style="width:30px;height:30px;border-radius:8px;border:1px 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:15px;font-weight:700;color:#1F2937;min-width:20px;text-align:center;">@item.Qty</span>
                            <button @onclick='() => UpdateCartQty(item.ProductId, 1)' style="width:30px;height:30px;border-radius:8px;border:none;background:#FF5C00;color:white;font-size:16px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;">+</button>
                        </div>
                    </div>
                }
                <div style="display:flex;justify-content:space-between;align-items:center;padding-top:16px;">
                    <span style="font-size:16px;font-weight:700;color:#1F2937;">Tổng cộng</span>
                    <span style="font-size:20px;font-weight:700;color:#FF5C00;">@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:#FF5C00;color:white;font-size:16px;font-weight:700;cursor:pointer;margin-top:16px;opacity:@(_ordering ? "0.7" : "1");">
                    @(_ordering ? "Đang gửi..." : "Đặt món")
                </button>
                @if (_orderMessage != null)
                {
                    <div style="margin-top:10px;text-align:center;font-size:14px;padding:10px;border-radius:8px;background:@(_orderSuccess ? "#F0FDF4" : "#FEF2F2");color:@(_orderSuccess ? "#059669" : "#DC2626");">
                        @_orderMessage
                    </div>
                }
            </div>
        </div>
    }

    @* ═══ ORDER SUCCESS TOAST ═══ *@
    @if (_showOrderSuccess)
    {
        <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:300;box-shadow:0 4px 16px rgba(0,0,0,0.15);display:flex;align-items:center;gap:8px;">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            Đặt món thành công!
        </div>
    }
}

<style>
    @@keyframes spin { to { transform: rotate(360deg); } }
    /* Hide scrollbar for category tabs */
    div::-webkit-scrollbar { display: none; }
</style>

@code {
    [Parameter] public Guid ShopId { get; set; }
    [Parameter] public Guid? TableId { get; set; }

    private bool _loading = true;
    private string? _error;
    private PosDataService.PublicShopInfo? _shop;
    private List<PosDataService.PublicMenuCategory> _categories = new();

    // Search & filter
    private string _searchQuery = "";
    private Guid? _selectedCategoryId;

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

    // EN: Filtered items based on search query and selected category.
    // VI: Lọc món dựa trên từ khóa tìm kiếm và danh mục đã chọn.
    private IEnumerable<PosDataService.PublicMenuItem> FilteredItems
    {
        get
        {
            var allItems = _categories.SelectMany(c => c.Items);

            if (!string.IsNullOrWhiteSpace(_searchQuery))
            {
                var query = _searchQuery.Trim().ToLowerInvariant();
                return allItems.Where(i =>
                    i.Name.ToLowerInvariant().Contains(query) ||
                    (i.Description?.ToLowerInvariant().Contains(query) ?? false));
            }

            if (_selectedCategoryId != null)
            {
                var cat = _categories.FirstOrDefault(c => c.Id == _selectedCategoryId);
                return cat?.Items ?? Enumerable.Empty<PosDataService.PublicMenuItem>();
            }

            return allItems;
        }
    }

    // EN: Categories to display (respecting selected category filter).
    // VI: Danh mục để hiển thị (tôn trọng bộ lọc danh mục đã chọn).
    private IEnumerable<PosDataService.PublicMenuCategory> DisplayCategories =>
        _selectedCategoryId != null
            ? _categories.Where(c => c.Id == _selectedCategoryId)
            : _categories;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            // EN: Fetch shop info and menu in parallel
            // VI: Lấy thông tin shop và menu song song
            var shopTask = DataService.GetPublicShopInfoAsync(ShopId);
            var menuTask = DataService.GetPublicMenuAsync(ShopId);

            await Task.WhenAll(shopTask, menuTask);

            _shop = await shopTask;
            _categories = await menuTask;

            if (_shop == null && !_categories.Any())
            {
                _error = "Cửa hàng không tồn tại hoặc chưa có thực đơn.";
            }
        }
        catch
        {
            _error = "Không thể tải thực đơn. Vui lòng thử lại.";
        }
        _loading = false;
    }

    private RenderFragment RenderMenuItem(PosDataService.PublicMenuItem item) => __builder =>
    {
        var inCart = _cart.FirstOrDefault(c => c.ProductId == item.Id);
        var isUnavailable = !item.IsAvailable;

        <div style="background:white;border-radius:12px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.06);border:1px solid #F3F4F6;display:flex;gap:12px;padding:12px;@(isUnavailable ? "opacity:0.5;" : "")">
            @* Image or placeholder *@
            @if (!string.IsNullOrEmpty(item.ImageUrl))
            {
                <div style="width:80px;height:80px;border-radius:10px;overflow:hidden;flex-shrink:0;position:relative;">
                    <img src="@item.ImageUrl" alt="@item.Name" style="width:100%;height:100%;object-fit:cover;" />
                    @if (isUnavailable)
                    {
                        <div style="position:absolute;top:4px;right:4px;background:#EF4444;color:white;font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;">Hết</div>
                    }
                </div>
            }
            else
            {
                <div style="width:80px;height:80px;border-radius:10px;background:#F9FAFB;display:flex;align-items:center;justify-content:center;flex-shrink:0;position:relative;">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#D1D5DB" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
                    @if (isUnavailable)
                    {
                        <div style="position:absolute;top:4px;right:4px;background:#EF4444;color:white;font-size:10px;font-weight:700;padding:2px 6px;border-radius:4px;">Hết</div>
                    }
                </div>
            }

            @* Content *@
            <div style="flex:1;min-width:0;display:flex;flex-direction:column;justify-content:space-between;">
                <div>
                    <div style="font-size:14px;font-weight:600;color:#1F2937;line-height:1.3;margin-bottom:2px;">@item.Name</div>
                    @if (!string.IsNullOrEmpty(item.Description))
                    {
                        <div style="font-size:12px;color:#9CA3AF;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">@item.Description</div>
                    }
                </div>
                <div style="display:flex;align-items:center;justify-content:space-between;margin-top:6px;">
                    <span style="font-size:15px;font-weight:700;color:#FF5C00;">@FormatVND(item.Price)</span>
                    @if (!isUnavailable)
                    {
                        @if (inCart != null)
                        {
                            <div style="display:flex;align-items:center;gap:8px;">
                                <button @onclick='() => UpdateCartQty(item.Id, -1)' style="width:28px;height:28px;border-radius:8px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:14px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;">-</button>
                                <span style="font-size:14px;font-weight:700;color:#1F2937;min-width:16px;text-align:center;">@inCart.Qty</span>
                                <button @onclick='() => UpdateCartQty(item.Id, 1)' style="width:28px;height:28px;border-radius:8px;border:none;background:#FF5C00;color:white;font-size:14px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;">+</button>
                            </div>
                        }
                        else
                        {
                            <button @onclick='() => AddToCart(item)' style="padding:6px 14px;border-radius:8px;border:none;background:#FFF7ED;color:#FF5C00;font-weight:600;font-size:13px;cursor:pointer;">
                                + Thêm
                            </button>
                        }
                    }
                    else
                    {
                        <span style="font-size:12px;font-weight:600;color:#EF4444;background:#FEF2F2;padding:4px 10px;border-radius:6px;">Hết hàng</span>
                    }
                </div>
            </div>
        </div>
    };

    private void AddToCart(PosDataService.PublicMenuItem item)
    {
        var existing = _cart.FirstOrDefault(c => c.ProductId == item.Id);
        if (existing != null)
            existing.Qty++;
        else
            _cart.Add(new CartItem(item.Id, item.Name, item.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)
            {
                _orderSuccess = true;
                _orderMessage = "Đặt món thành công! Món sẽ được phục vụ sớm nhất.";
                _cart.Clear();
                _showCart = false;
                _showOrderSuccess = true;
                StateHasChanged();
                await Task.Delay(3000);
                _showOrderSuccess = false;
                StateHasChanged();
            }
            else
            {
                _orderSuccess = false;
                _orderMessage = "Không thể đặt món. Vui lòng thử lại.";
            }
        }
        catch
        {
            _orderSuccess = false;
            _orderMessage = "Lỗi khi đặt món. Vui lòng thử lại.";
        }
        _ordering = false;
    }

    private static string FormatVND(decimal amount)
    {
        // EN: Format as Vietnamese dong: "45.000d" with dot thousands separator.
        // VI: Định dạng đồng Việt Nam: "45.000d" với dấu chấm ngăn cách hàng nghìn.
        return $"{amount:N0}".Replace(",", ".") + "₫";
    }

    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; }
    }
}
