@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@inject PosDataService DataService

<div>
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:12px;">
        <h3 style="margin:0;font-size:16px;font-weight:700;">@(FilteredProducts.Count) sản phẩm</h3>
        <div style="display:flex;align-items:center;gap:8px;">
            @if (_categories.Any())
            {
                <select @bind="_productCategoryFilter" @bind:after="@(() => _productPage = 1)" style="padding:6px 10px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);font-size:12px;">
                    <option value="">Tất cả danh mục</option>
                    @foreach (var c in _categories) { <option value="@c.Id">@c.Name</option> }
                </select>
            }
            <div style="display:flex;border:1px solid var(--admin-border-subtle);border-radius:8px;overflow:hidden;">
                <button @onclick='() => _productView = "grid"' style="padding:6px 10px;border:none;cursor:pointer;background:@(_productView == "grid" ? "var(--admin-orange-primary)" : "var(--admin-bg-elevated)");color:@(_productView == "grid" ? "#FFF" : "var(--admin-text-secondary)");"><i data-lucide="grid-3x3" style="width:14px;height:14px;"></i></button>
                <button @onclick='() => _productView = "list"' style="padding:6px 10px;border:none;border-left:1px solid var(--admin-border-subtle);cursor:pointer;background:@(_productView == "list" ? "var(--admin-orange-primary)" : "var(--admin-bg-elevated)");color:@(_productView == "list" ? "#FFF" : "var(--admin-text-secondary)");"><i data-lucide="list" style="width:14px;height:14px;"></i></button>
            </div>
            <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick="@(() => { _editingProductId = null; _newProductName = ""; _newProductPrice = 0; _newProductDesc = ""; _newProductType = "PreparedFood"; _newProductCategoryId = ""; _formMessage = null; _productImageFile = null; _productImagePreview = null; _showProductForm = !_showProductForm; })">
                <i data-lucide="plus-circle" style="width:16px;height:16px;"></i>
                Thêm sản phẩm
            </button>
        </div>
    </div>
    @if (_showProductForm)
    {
        <div class="admin-panel" style="margin-bottom:16px;border:1px solid rgba(255,92,0,0.3);">
            <div class="admin-panel__header"><h3 class="admin-panel__title">@(_editingProductId.HasValue ? "Chỉnh sửa sản phẩm" : "Thêm sản phẩm mới")</h3></div>
            <div class="admin-panel__body">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên sản phẩm *</label><input type="text" @bind="_newProductName" class="admin-input" placeholder="VD: Cà phê sữa đá" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giá (₫) *</label><input type="number" @bind="_newProductPrice" class="admin-input" placeholder="35000" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Loại</label>
                        <select @bind="_newProductType" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                            <option value="PreparedFood">Đồ uống / Thức ăn</option>
                            <option value="Service">Dịch vụ</option>
                            <option value="Physical">Sản phẩm vật lý</option>
                        </select>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Mô tả</label><input type="text" @bind="_newProductDesc" class="admin-input" placeholder="Mô tả ngắn" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Danh mục</label>
                        <select @bind="_newProductCategoryId" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);">
                            <option value="">-- Không phân loại --</option>
                            @foreach (var c in _categories)
                            {
                                <option value="@c.Id">@c.Name</option>
                            }
                        </select>
                    </div>
                    <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Hình ảnh</label>
                        <div style="border:2px dashed var(--admin-border-subtle);border-radius:8px;padding:12px;text-align:center;">
                            @if (_productImagePreview != null)
                            {
                                <img src="@_productImagePreview" alt="Preview" style="max-width:80px;max-height:80px;border-radius:6px;margin-bottom:6px;" />
                            }
                            <InputFile OnChange="OnProductImageSelected" accept="image/*" style="font-size:12px;width:100%;" />
                        </div>
                    </div>
                </div>
                <div style="display:flex;gap:8px;margin-top:16px;">
                    <button class="admin-btn-primary" @onclick="@(_editingProductId.HasValue ? SaveProduct : AddProduct)" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>@(_editingProductId.HasValue ? "Cập nhật" : "Lưu")</button>
                    <button class="admin-btn" @onclick="@(() => _showProductForm = false)" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;"><i data-lucide="x" style="width:14px;height:14px;"></i>Hủy</button>
                </div>
                @if (!string.IsNullOrEmpty(_formMessage))
                {
                    <div style="margin-top:8px;font-size:13px;color:@(_formSuccess ? "#22C55E" : "#EF4444");">@_formMessage</div>
                }
            </div>
        </div>
    }
    @if (!_products.Any())
    {
        <div style="text-align:center;padding:60px 20px;">
            <div style="width:80px;height:80px;border-radius:24px;background:rgba(245,158,11,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">
                <i data-lucide="coffee" style="width:36px;height:36px;color:#F59E0B;"></i>
            </div>
            <h2 style="font-size:20px;font-weight:700;margin:0 0 8px;color:var(--pos-text-primary, #FFF);">Chưa có sản phẩm</h2>
            <p style="font-size:14px;color:var(--admin-text-tertiary);margin:0 0 20px;">Thêm sản phẩm để bắt đầu bán hàng</p>
        </div>
    }
    else if (_productView == "grid")
    {
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:16px;">
            @foreach (var p in PagedProducts)
            {
                var typeColor = (p.Type ?? "") switch { "Service" => "#EC4899", "Physical" => "#3B82F6", _ => "#F59E0B" };
                var typeLabel = (p.Type ?? "") switch { "Service" => "Dịch vụ", "Physical" => "Vật lý", _ => "Đồ uống" };
                <div class="admin-panel" style="position:relative;">
                    <div class="admin-panel__body" style="padding:16px;text-align:center;">
                        <div style="position:absolute;top:8px;right:8px;display:flex;gap:4px;">
                            <button @onclick="@(() => EditProduct(p))" style="background:rgba(59,130,246,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Sửa"><i data-lucide="pencil" style="color:#3B82F6;width:14px;height:14px;"></i></button>
                            <button @onclick="@(() => DeleteProduct(p.Id))" style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Xóa"><i data-lucide="trash-2" style="color:#EF4444;width:14px;height:14px;"></i></button>
                        </div>
                        @if (!string.IsNullOrWhiteSpace(p.ImageUrl))
                        {
                            <img src="@p.ImageUrl" alt="@p.Name" style="width:48px;height:48px;border-radius:12px;object-fit:cover;margin:0 auto 12px;" />
                        }
                        else
                        {
                            <div style="width:48px;height:48px;border-radius:12px;background:rgba(255,92,0,0.1);display:flex;align-items:center;justify-content:center;margin:0 auto 12px;"><i data-lucide="package" style="color:#FF5C00;width:24px;height:24px;"></i></div>
                        }
                        <div style="font-weight:600;font-size:14px;margin-bottom:4px;">@p.Name</div>
                        <div style="font-size:13px;color:var(--admin-text-tertiary);margin-bottom:4px;">@(p.CategoryName ?? "—")</div>
                        <span style="font-size:10px;font-weight:600;padding:2px 8px;border-radius:6px;background:@($"{typeColor}22");color:@typeColor;">@typeLabel</span>
                        <div style="font-weight:700;color:var(--admin-orange-primary);margin-top:8px;">@p.Price.ToString("N0")₫</div>
                    </div>
                </div>
            }
        </div>
    }
    else
    {
        @* LIST VIEW *@
        <div class="admin-panel">
            <div class="admin-panel__body" style="padding:0;">
                <table class="admin-table" style="width:100%;"><thead><tr>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Tên</th>
                    <th style="padding:12px 16px;text-align:left;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Danh mục</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Loại</th>
                    <th style="padding:12px 16px;text-align:right;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);">Giá</th>
                    <th style="padding:12px 16px;text-align:center;font-size:12px;text-transform:uppercase;color:var(--admin-text-tertiary);"></th>
                </tr></thead><tbody>
                    @foreach (var p in PagedProducts)
                    {
                        var typeColor = (p.Type ?? "") switch { "Service" => "#EC4899", "Physical" => "#3B82F6", _ => "#F59E0B" };
                        var typeLabel = (p.Type ?? "") switch { "Service" => "Dịch vụ", "Physical" => "Vật lý", _ => "Đồ uống" };
                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                            <td style="padding:12px 16px;font-weight:600;">@p.Name</td>
                            <td style="padding:12px 16px;color:var(--admin-text-secondary);font-size:13px;">@(p.CategoryName ?? "—")</td>
                            <td style="padding:12px 16px;text-align:center;"><span style="font-size:11px;padding:2px 8px;border-radius:4px;background:@($"{typeColor}22");color:@typeColor;font-weight:600;">@typeLabel</span></td>
                            <td style="padding:12px 16px;text-align:right;font-weight:600;color:var(--admin-orange-primary);">@p.Price.ToString("N0")₫</td>
                            <td style="padding:12px 16px;text-align:center;">
                                <div style="display:flex;gap:4px;justify-content:center;">
                                    <button @onclick="@(() => EditProduct(p))" style="background:rgba(59,130,246,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Sửa"><i data-lucide="pencil" style="color:#3B82F6;width:14px;height:14px;"></i></button>
                                    <button @onclick="@(() => DeleteProduct(p.Id))" style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Xóa"><i data-lucide="trash-2" style="color:#EF4444;width:14px;height:14px;"></i></button>
                                </div>
                            </td>
                        </tr>
                    }
                </tbody></table>
            </div>
        </div>
    }
    @* ═══ PAGINATION ═══ *@
    @if (ProductTotalPages > 1)
    {
        <div style="display:flex;align-items:center;justify-content:center;gap:8px;margin-top:16px;">
            <button disabled="@(_productPage <= 1)" @onclick="@(() => _productPage--)"
                style="padding:6px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-secondary);cursor:pointer;font-size:12px;">
                <i data-lucide="chevron-left" style="width:14px;height:14px;"></i>
            </button>
            @for (var i = 1; i <= ProductTotalPages; i++)
            {
                var pg = i;
                <button @onclick="@(() => _productPage = pg)"
                    style="min-width:32px;height:32px;border-radius:8px;border:1px solid @(pg == _productPage ? "var(--admin-orange-primary)" : "var(--admin-border-subtle)");background:@(pg == _productPage ? "var(--admin-orange-primary)" : "var(--admin-bg-elevated)");color:@(pg == _productPage ? "#FFF" : "var(--admin-text-secondary)");cursor:pointer;font-size:12px;font-weight:600;">
                    @pg
                </button>
            }
            <button disabled="@(_productPage >= ProductTotalPages)" @onclick="@(() => _productPage++)"
                style="padding:6px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-secondary);cursor:pointer;font-size:12px;">
                <i data-lucide="chevron-right" style="width:14px;height:14px;"></i>
            </button>
            <span style="font-size:12px;color:var(--admin-text-tertiary);margin-left:8px;">Trang @_productPage / @ProductTotalPages</span>
        </div>
    }
    @* Categories Management *@
    <div class="admin-panel" style="margin-top:20px;">
        <div class="admin-panel__header">
            <h3 class="admin-panel__title">Danh mục (@_categories.Count)</h3>
            <button class="admin-btn-primary" style="display:inline-flex;align-items:center;gap:8px;" @onclick="@(() => { _editingCategoryId = null; _newCategoryName = ""; _newCategoryDesc = ""; _newCategoryOrder = 0; _categoryFormMessage = null; _categoryImageFile = null; _categoryImagePreview = null; _newCategoryImageUrl = ""; _showCategoryForm = !_showCategoryForm; })">
                <i data-lucide="plus" style="width:16px;height:16px;"></i>Thêm danh mục
            </button>
        </div>
        @if (_showCategoryForm)
        {
            <div style="padding:16px;border-bottom:1px solid var(--admin-border-subtle);">
                <h4 style="margin:0 0 12px;color:var(--admin-text-primary);">@(_editingCategoryId.HasValue ? "Chỉnh sửa danh mục" : "Thêm danh mục mới")</h4>
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;align-items:end;">
                    <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Tên</label><input @bind="_newCategoryName" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Mô tả</label><input @bind="_newCategoryDesc" style="width:100%;padding:8px 12px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:var(--admin-bg-elevated);color:var(--admin-text-primary);" /></div>
                    <div><label style="font-size:12px;color:var(--admin-text-secondary);display:block;margin-bottom:4px;">Hình ảnh</label>
                        <div style="border:2px dashed var(--admin-border-subtle);border-radius:8px;padding:8px;text-align:center;">
                            @if (_categoryImagePreview != null) { <img src="@_categoryImagePreview" alt="Preview" style="max-width:60px;max-height:60px;border-radius:6px;margin-bottom:4px;" /> }
                            <InputFile OnChange="OnCategoryImageSelected" accept="image/*" style="font-size:11px;width:100%;" />
                        </div>
                    </div>
                </div>
                <div style="display:flex;gap:8px;margin-top:12px;">
                    <button class="admin-btn-primary" @onclick="@SaveCategory" style="display:inline-flex;align-items:center;gap:6px;"><i data-lucide="check" style="width:14px;height:14px;"></i>@(_editingCategoryId.HasValue ? "Cập nhật" : "Lưu")</button>
                    <button @onclick="@(() => _showCategoryForm = false)" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-border-subtle);background:transparent;color:var(--admin-text-secondary);cursor:pointer;"><i data-lucide="x" style="width:14px;height:14px;"></i>Hủy</button>
                </div>
                @if (_categoryFormMessage != null) { <div style="margin-top:8px;padding:8px 12px;border-radius:6px;font-size:13px;@(_categoryFormSuccess ? "color:#22C55E;background:rgba(34,197,94,0.1);" : "color:#EF4444;background:rgba(239,68,68,0.1);")">@_categoryFormMessage</div> }
            </div>
        }
        <div style="padding:16px;">
            <table style="width:100%;border-collapse:collapse;">
                <thead><tr style="font-size:12px;color:var(--admin-text-tertiary);text-align:left;">
                    <th style="padding:8px 12px;">TÊN</th><th style="padding:8px 12px;">MÔ TẢ</th><th style="padding:8px 12px;">THỨ TỰ</th><th style="padding:8px 12px;text-align:right;">HÀNH ĐỘNG</th>
                </tr></thead>
                <tbody>
                    @foreach (var c in _categories)
                    {
                        <tr style="border-top:1px solid var(--admin-border-subtle);">
                            <td style="padding:10px 12px;color:var(--admin-text-primary);font-weight:500;">@c.Name</td>
                            <td style="padding:10px 12px;color:var(--admin-text-secondary);font-size:13px;">@c.Description</td>
                            <td style="padding:10px 12px;color:var(--admin-text-secondary);">@c.DisplayOrder</td>
                            <td style="padding:10px 12px;text-align:right;">
                                <div style="display:flex;gap:6px;justify-content:flex-end;">
                                    <button @onclick="@(() => EditCategory(c))" style="background:rgba(59,130,246,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Sửa"><i data-lucide="pencil" style="color:#3B82F6;width:14px;height:14px;"></i></button>
                                    <button @onclick="@(() => DeleteCategoryItem(c.Id))" style="background:rgba(239,68,68,0.1);border:none;border-radius:6px;width:28px;height:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;" title="Xóa"><i data-lucide="trash-2" style="color:#EF4444;width:14px;height:14px;"></i></button>
                                </div>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
            @if (!_categories.Any()) { <div style="text-align:center;padding:24px;color:var(--admin-text-tertiary);font-size:14px;">Chưa có danh mục. Nhấn "Thêm danh mục" để tạo mới.</div> }
        </div>
    </div>
</div>

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

    private Guid? _shopGuid => ShopId != Guid.Empty ? ShopId : null;

    // Product state
    private List<PosDataService.AdminProductInfo> _products = new();
    private bool _showProductForm;
    private Guid? _editingProductId;
    private string _newProductName = "";
    private decimal _newProductPrice;
    private string _newProductType = "PreparedFood";
    private string _newProductDesc = "";
    private string _newProductCategoryId = "";
    private string? _formMessage;
    private bool _formSuccess;
    private int _productPage = 1;
    private int _productPageSize = 20;
    private string _productView = "grid";
    private string _productCategoryFilter = "";
    private int ProductTotalPages => Math.Max(1, (int)Math.Ceiling((double)FilteredProducts.Count / _productPageSize));
    private List<PosDataService.AdminProductInfo> FilteredProducts =>
        string.IsNullOrEmpty(_productCategoryFilter) ? _products :
        _products.Where(p => (p.CategoryId?.ToString() ?? "") == _productCategoryFilter).ToList();
    private List<PosDataService.AdminProductInfo> PagedProducts =>
        FilteredProducts.Skip((_productPage - 1) * _productPageSize).Take(_productPageSize).ToList();

    // Category state
    private List<PosDataService.AdminCategoryInfo> _categories = new();
    private bool _showCategoryForm;
    private Guid? _editingCategoryId;
    private string _newCategoryName = "";
    private string _newCategoryDesc = "";
    private int _newCategoryOrder;
    private string? _categoryFormMessage;
    private bool _categoryFormSuccess;

    // Image upload state
    private Microsoft.AspNetCore.Components.Forms.IBrowserFile? _productImageFile;
    private string? _productImagePreview;
    private Microsoft.AspNetCore.Components.Forms.IBrowserFile? _categoryImageFile;
    private string? _categoryImagePreview;
    private string _newCategoryImageUrl = "";

    protected override async Task OnInitializedAsync()
    {
        _products = await DataService.GetAllProductsAsync(_shopGuid);
        _categories = await DataService.GetAllCategoriesAsync(_shopGuid);
    }

    private async Task AddProduct()
    {
        _formMessage = null;
        if (string.IsNullOrWhiteSpace(_newProductName) || _newProductPrice <= 0 || ShopId == Guid.Empty)
        {
            _formMessage = "Vui lòng nhập tên và giá sản phẩm."; _formSuccess = false; return;
        }
        try
        {
            Guid? catId = Guid.TryParse(_newProductCategoryId, out var cid) ? cid : null;
            var imgUrl = await UploadFileIfNeeded(_productImageFile);
            await DataService.CreateProductAsync(new PosDataService.CreateProductRequest(
                ShopId, _newProductName, _newProductDesc, _newProductPrice, _newProductType, imgUrl, null, catId));
            _formMessage = $"Đã thêm '{_newProductName}' thành công!"; _formSuccess = true;
            _newProductName = ""; _newProductPrice = 0; _newProductDesc = ""; _newProductCategoryId = ""; _productImageFile = null; _productImagePreview = null;
            _products = await DataService.GetAllProductsAsync(_shopGuid);
        }
        catch (Exception ex) { _formMessage = $"Lỗi: {ex.Message}"; _formSuccess = false; }
    }

    private async Task DeleteProduct(Guid productId)
    {
        try
        {
            await DataService.DeleteProductAsync(productId);
            _products = await DataService.GetAllProductsAsync(_shopGuid);
        }
        catch (Exception ex) { _formMessage = $"Không thể xóa: {ex.Message}"; _formSuccess = false; }
    }

    private void EditProduct(PosDataService.AdminProductInfo p)
    {
        _editingProductId = p.Id;
        _newProductName = p.Name;
        _newProductPrice = p.Price;
        _newProductType = p.Type ?? "PreparedFood";
        _newProductDesc = p.Description ?? "";
        _newProductCategoryId = p.CategoryId?.ToString() ?? "";
        _productImageFile = null;
        _productImagePreview = p.ImageUrl;
        _formMessage = null;
        _showProductForm = true;
    }

    private async Task SaveProduct()
    {
        _formMessage = null;
        if (string.IsNullOrWhiteSpace(_newProductName) || _newProductPrice <= 0 || ShopId == Guid.Empty || !_editingProductId.HasValue)
        {
            _formMessage = "Vui lòng nhập tên và giá sản phẩm."; _formSuccess = false; return;
        }
        try
        {
            Guid? catId = Guid.TryParse(_newProductCategoryId, out var cid2) ? cid2 : null;
            var imgUrl2 = await UploadFileIfNeeded(_productImageFile);
            await DataService.UpdateProductAsync(_editingProductId.Value, new PosDataService.CreateProductRequest(
                ShopId, _newProductName, _newProductDesc, _newProductPrice, _newProductType, imgUrl2, null, catId));
            _formMessage = $"Đã cập nhật '{_newProductName}' thành công!"; _formSuccess = true;
            _editingProductId = null;
            _products = await DataService.GetAllProductsAsync(_shopGuid);
        }
        catch (Exception ex) { _formMessage = $"Lỗi: {ex.Message}"; _formSuccess = false; }
    }

    private async Task SaveCategory()
    {
        if (string.IsNullOrWhiteSpace(_newCategoryName)) { _categoryFormMessage = "Tên danh mục không được trống."; _categoryFormSuccess = false; return; }
        var catImgUrl = await UploadFileIfNeeded(_categoryImageFile) ?? _newCategoryImageUrl;
        var req = new PosDataService.AdminCreateCategoryRequest(_shopGuid ?? Guid.Empty, _newCategoryName, _newCategoryDesc, _newCategoryOrder, string.IsNullOrWhiteSpace(catImgUrl) ? null : catImgUrl);
        bool ok;
        if (_editingCategoryId.HasValue)
            ok = await DataService.UpdateCategoryAsync(_editingCategoryId.Value, req);
        else
            ok = await DataService.CreateCategoryAsync(req);
        _categoryFormMessage = ok ? (_editingCategoryId.HasValue ? "Đã cập nhật danh mục!" : "Đã thêm danh mục!") : "Lỗi khi lưu danh mục.";
        _categoryFormSuccess = ok;
        if (ok) { _showCategoryForm = false; _categoryImageFile = null; _categoryImagePreview = null; _newCategoryImageUrl = ""; _categories = await DataService.GetAllCategoriesAsync(_shopGuid); }
    }

    private void EditCategory(PosDataService.AdminCategoryInfo c)
    {
        _editingCategoryId = c.Id; _newCategoryName = c.Name ?? ""; _newCategoryDesc = c.Description ?? ""; _newCategoryOrder = c.DisplayOrder; _newCategoryImageUrl = c.ImageUrl ?? ""; _categoryImageFile = null; _categoryImagePreview = c.ImageUrl; _showCategoryForm = true; _categoryFormMessage = null;
    }

    private async Task DeleteCategoryItem(Guid id) { await DataService.DeleteCategoryAsync(id); _categories = await DataService.GetAllCategoriesAsync(_shopGuid); }

    private async Task OnProductImageSelected(Microsoft.AspNetCore.Components.Forms.InputFileChangeEventArgs e)
    {
        _productImageFile = e.File;
        var format = "image/png";
        var resized = await e.File.RequestImageFileAsync(format, 200, 200);
        var buffer = new byte[resized.Size];
        await resized.OpenReadStream().ReadAsync(buffer);
        _productImagePreview = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
        StateHasChanged();
    }

    private async Task OnCategoryImageSelected(Microsoft.AspNetCore.Components.Forms.InputFileChangeEventArgs e)
    {
        _categoryImageFile = e.File;
        var format = "image/png";
        var resized = await e.File.RequestImageFileAsync(format, 200, 200);
        var buffer = new byte[resized.Size];
        await resized.OpenReadStream().ReadAsync(buffer);
        _categoryImagePreview = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
        StateHasChanged();
    }

    private async Task<string?> UploadFileIfNeeded(Microsoft.AspNetCore.Components.Forms.IBrowserFile? file)
    {
        if (file == null) return null;
        using var stream = file.OpenReadStream(maxAllowedSize: 10_485_760);
        return await DataService.UploadImageAsync(stream, file.Name, file.ContentType);
    }
}
