@using WebClientTpos.Client.Services
@using WebClientTpos.Client.Pages.Admin.Shop
@using System.Text.Json
@inject PosDataService DataService
@inject MerchantApiService MerchantApi
@inject IDialogService DialogService
@inject ISnackbar Snackbar
@inject NavigationManager NavigationManager
@inject IJSRuntime JS

@* ─── Shop info (read-only) ─── *@
<div class="admin-panel">
    <div class="admin-panel__header"><h3 class="admin-panel__title">Thông tin cửa hàng</h3></div>
    <div class="admin-panel__body">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
            <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Tên cửa hàng</label><div style="padding:10px 14px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);font-size:14px;">@(_shopName ?? "—")</div></div>
            <div><label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Ngành hàng</label><div style="padding:10px 14px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);font-size:14px;">@_verticalLabel</div></div>
        </div>
    </div>
</div>
@* ─── Opening hours + business days ─── *@
<div class="admin-panel" style="margin-top:16px;">
    <div class="admin-panel__header"><h3 class="admin-panel__title">Giờ & ngày hoạt động</h3></div>
    <div class="admin-panel__body">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;">
            <div>
                <label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giờ mở cửa</label>
                <input type="time" value="@_settingsOpenTime" @oninput="@(e => _settingsOpenTime = e.Value?.ToString() ?? "")" style="width:100%;padding:10px 14px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);font-size:14px;color:var(--admin-text-primary);" />
            </div>
            <div>
                <label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Giờ đóng cửa</label>
                <input type="time" value="@_settingsCloseTime" @oninput="@(e => _settingsCloseTime = e.Value?.ToString() ?? "")" style="width:100%;padding:10px 14px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);font-size:14px;color:var(--admin-text-primary);" />
            </div>
        </div>
        <div style="margin-bottom:16px;">
            <label style="font-size:12px;font-weight:600;display:block;margin-bottom:8px;">Ngày kinh doanh</label>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                @foreach (var (day, code) in new[] { ("T2","Monday"),("T3","Tuesday"),("T4","Wednesday"),("T5","Thursday"),("T6","Friday"),("T7","Saturday"),("CN","Sunday") })
                {
                    var isOn = _settingsOpenDays.Contains(code);
                    <button type="button" @onclick="@(() => ToggleDay(code))"
                        style="width:40px;height:40px;border-radius:10px;border:1px solid @(isOn ? "var(--admin-orange-primary)" : "var(--admin-border-subtle)");background:@(isOn ? "rgba(255,92,0,0.15)" : "var(--admin-bg-elevated)");color:@(isOn ? "var(--admin-orange-primary)" : "var(--admin-text-tertiary)");font-size:12px;font-weight:@(isOn ? "700" : "500");cursor:pointer;">
                        @day
                    </button>
                }
            </div>
        </div>
    </div>
</div>
@* ─── Features config toggles ─── *@
<div class="admin-panel" style="margin-top:16px;">
    <div class="admin-panel__header"><h3 class="admin-panel__title">Tính năng cửa hàng</h3></div>
    <div class="admin-panel__body">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
            @{ void RenderToggle(string label, bool isOn, Action<bool> setter) {
                <div style="display:flex;align-items:center;gap:10px;padding:10px 14px;border-radius:8px;border:1px solid var(--admin-border-subtle);cursor:pointer;" @onclick="@(() => { setter(!isOn); StateHasChanged(); })">
                    <div style="width:36px;height:20px;border-radius:10px;background:@(isOn ? "var(--admin-orange-primary)" : "var(--admin-border-subtle)");position:relative;transition:0.2s;">
                        <div style="width:16px;height:16px;border-radius:50%;background:white;position:absolute;top:2px;@(isOn ? "right:2px;" : "left:2px;");transition:0.2s;"></div>
                    </div>
                    <span style="font-size:13px;font-weight:500;">@label</span>
                </div>;
            } }
            @{ RenderToggle("Quản lý tồn kho", _featHasInventory, v => _featHasInventory = v); }
            @{ RenderToggle("Đặt lịch hẹn", _featHasBooking, v => _featHasBooking = v); }
            @{ RenderToggle("Quản lý bàn", _featHasTables, v => _featHasTables = v); }
            @{ RenderToggle("Hiển thị bếp", _featHasKitchen, v => _featHasKitchen = v); }
            @{ RenderToggle("Vận chuyển", _featHasShipping, v => _featHasShipping = v); }
            @{ RenderToggle("Giao hàng", _featHasDelivery, v => _featHasDelivery = v); }
        </div>
    </div>
</div>
@* ─── Save button ─── *@
<div style="margin-top:16px;display:flex;align-items:center;gap:12px;">
    <button class="admin-btn-primary" @onclick="SaveShopSettings" style="display:inline-flex;align-items:center;gap:8px;">
        <i data-lucide="save" style="width:16px;height:16px;"></i>Lưu thiết lập
    </button>
    @if (_settingsMessage != null)
    {
        <span style="font-size:13px;color:@(_settingsSuccess ? "#22C55E" : "#EF4444");">@_settingsMessage</span>
    }
</div>

@* ─── EN: Receipt Template Configuration ─── *@
@* ─── VI: Cấu hình mẫu hoá đơn in ─── *@
<div class="admin-panel" style="margin-top:16px;">
    <div class="admin-panel__header">
        <h3 class="admin-panel__title" style="display:flex;align-items:center;gap:8px;">
            <i data-lucide="receipt" style="width:18px;height:18px;color:var(--admin-orange-primary);"></i>
            Hoá đơn in
        </h3>
    </div>
    <div class="admin-panel__body" style="display:flex;align-items:center;justify-content:space-between;">
        <div>
            <div style="font-size:14px;font-weight:600;">Quản lý mẫu hoá đơn</div>
            <div style="font-size:12px;color:var(--admin-text-tertiary);margin-top:2px;">
                Mẫu đang dùng: <strong style="color:var(--admin-orange-primary);">@(_activeReceiptTemplateName ?? "Mẫu mặc định")</strong>
            </div>
        </div>
        <button @onclick="NavigateToReceiptTemplates"
                style="display:inline-flex;align-items:center;gap:8px;padding:8px 16px;border-radius:8px;border:1px solid var(--admin-orange-primary);background:rgba(255,92,0,0.08);color:var(--admin-orange-primary);cursor:pointer;font-size:13px;font-weight:600;">
            <i data-lucide="settings-2" style="width:14px;height:14px;"></i>Quản lý template hoá đơn
        </button>
    </div>
</div>

@* ─── EN: AI Assistant Configuration ─── *@
@* ─── VI: Cấu hình AI Assistant ─── *@
<div class="admin-panel" style="margin-top:16px;">
    <div class="admin-panel__header">
        <h3 class="admin-panel__title" style="display:flex;align-items:center;gap:8px;">
            <i data-lucide="bot" style="width:18px;height:18px;color:var(--admin-orange-primary);"></i>
            AI Assistant
        </h3>
    </div>
    <div class="admin-panel__body" style="display:flex;flex-direction:column;gap:16px;">
        <div style="display:flex;justify-content:space-between;align-items:center;">
            <div>
                <div style="font-size:14px;font-weight:600;">Kích hoạt AI Assistant</div>
                <div style="font-size:12px;color:var(--admin-text-tertiary);">Cho phép sử dụng trợ lý AI trong quản lý cửa hàng</div>
            </div>
            <MudSwitch T="bool" @bind-Value="_aiEnabled" Color="Color.Primary" />
        </div>

        @if (_aiEnabled)
        {
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                <div>
                    <label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Provider</label>
                    <select @bind="_aiProvider" style="width:100%;padding:10px 14px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);color:var(--admin-text-primary);font-size:14px;">
                        <option value="openai">OpenAI</option>
                        <option value="openrouter">OpenRouter</option>
                        <option value="claude">Claude (Anthropic)</option>
                    </select>
                </div>
                <div>
                    <label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">Model</label>
                    <input type="text" @bind="_aiModel" placeholder="@(_aiProvider switch { "openai" => "gpt-4o", "openrouter" => "anthropic/claude-sonnet-4", "claude" => "claude-sonnet-4-20250514", _ => "gpt-4o" })"
                           style="width:100%;padding:10px 14px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);color:var(--admin-text-primary);font-size:14px;" />
                </div>
            </div>

            <div>
                <label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">API Key</label>
                <div style="position:relative;">
                    <input type="@(_showApiKey ? "text" : "password")" @bind="_aiApiKey" placeholder="sk-..."
                           style="width:100%;padding:10px 14px;padding-right:44px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);color:var(--admin-text-primary);font-size:14px;font-family:monospace;" />
                    <button @onclick="() => _showApiKey = !_showApiKey" style="position:absolute;right:8px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--admin-text-tertiary);padding:4px;">
                        <i data-lucide="@(_showApiKey ? "eye-off" : "eye")" style="width:16px;height:16px;"></i>
                    </button>
                </div>
                <div style="font-size:11px;color:var(--admin-text-tertiary);margin-top:4px;">
                    @(_aiProvider switch {
                        "openai" => "Lấy API key tại platform.openai.com/api-keys",
                        "openrouter" => "Lấy API key tại openrouter.ai/keys",
                        "claude" => "Lấy API key tại console.anthropic.com/settings/keys",
                        _ => ""
                    })
                </div>
            </div>

            <div>
                <label style="font-size:12px;font-weight:600;display:block;margin-bottom:4px;">System Prompt (tuỳ chọn)</label>
                <textarea @bind="_aiSystemPrompt" rows="3" placeholder="Để trống sẽ dùng prompt mặc định cho quản lý cửa hàng..."
                          style="width:100%;padding:10px 14px;border-radius:8px;background:var(--admin-bg-elevated);border:1px solid var(--admin-border-subtle);color:var(--admin-text-primary);font-size:13px;resize:vertical;min-height:60px;"></textarea>
            </div>

            <div style="display:flex;align-items:center;gap:12px;">
                <button class="admin-btn-primary" @onclick="SaveAiConfig" disabled="@_aiSaving" style="display:inline-flex;align-items:center;gap:8px;">
                    @if (_aiSaving) { <span>Đang lưu...</span> } else { <i data-lucide="save" style="width:16px;height:16px;"></i> <span>Lưu cấu hình AI</span> }
                </button>
                @if (_aiMessage != null)
                {
                    <span style="font-size:13px;color:@(_aiSuccess ? "#22C55E" : "#EF4444");">@_aiMessage</span>
                }
            </div>
        }
    </div>
</div>

@* ─── EN: Publish / Activate shop (when Draft) ─── *@
@* ─── VI: Kích hoạt cửa hàng (khi đang ở trạng thái Draft) ─── *@
@if (ShopVerticalHelper.IsSetup(ShopStatus))
{
    <MudPaper Class="mt-4 pa-0" Style="border: 1px solid rgba(34,197,94,0.4); border-radius: 8px; background: rgba(34,197,94,0.04); overflow: hidden;">
        <div style="padding: 20px; display: flex; align-items: center; justify-content: space-between;">
            <div>
                <MudText Typo="Typo.h6" Style="color: #22C55E; font-size: 16px; font-weight: 700;">
                    <i data-lucide="rocket" style="width:18px;height:18px;display:inline;vertical-align:middle;margin-right:6px;"></i>
                    Kích hoạt cửa hàng
                </MudText>
                <MudText Typo="Typo.body2" Style="color: var(--admin-text-tertiary, #999); font-size: 13px; margin-top: 4px;">
                    Cửa hàng đang ở chế độ thiết lập. Kích hoạt để bắt đầu sử dụng POS bán hàng và nhận đơn hàng.
                </MudText>
                <div style="margin-top:8px;font-size:12px;color:var(--admin-text-tertiary);">
                    <span style="display:inline-flex;align-items:center;gap:4px;margin-right:12px;">
                        <i data-lucide="check-circle" style="width:12px;height:12px;color:#22C55E;"></i> Thông tin cửa hàng
                    </span>
                    <span style="display:inline-flex;align-items:center;gap:4px;margin-right:12px;">
                        <i data-lucide="check-circle" style="width:12px;height:12px;color:#22C55E;"></i> Thiết lập giờ mở cửa
                    </span>
                    <span style="display:inline-flex;align-items:center;gap:4px;">
                        <i data-lucide="check-circle" style="width:12px;height:12px;color:#22C55E;"></i> Tính năng cửa hàng
                    </span>
                </div>
            </div>
            <MudButton Variant="Variant.Filled" Color="Color.Success" Size="Size.Medium"
                       OnClick="OnPublishShop" Disabled="_isPublishing"
                       Style="min-width: 160px; text-transform: none; font-weight: 700;">
                @if (_isPublishing)
                {
                    <MudProgressCircular Size="Size.Small" Indeterminate="true" Class="mr-2" Style="width:16px;height:16px;" />
                }
                Kích hoạt ngay
            </MudButton>
        </div>
    </MudPaper>
}

@* ─── EN: Danger Zone — shop lifecycle actions (deactivate, close) ─── *@
@* ─── VI: Vùng nguy hiểm — thao tác vòng đời cửa hàng (tạm ngưng, đóng) ─── *@
<MudPaper Class="mt-6 pa-0" Style="border: 1px solid #f44336; border-radius: 8px; background: rgba(244,67,54,0.04); overflow: hidden;">
    <div style="padding: 16px 20px; border-bottom: 1px solid rgba(244,67,54,0.2);">
        <MudText Typo="Typo.h6" Style="color: #f44336; font-size: 16px; font-weight: 700;">Vùng nguy hiểm</MudText>
    </div>

    @* EN: Deactivate shop — temporarily disable *@
    @* VI: Tạm ngưng cửa hàng — vô hiệu hóa tạm thời *@
    <div style="padding: 16px 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(244,67,54,0.12);">
        <div>
            <MudText Typo="Typo.subtitle1" Style="font-weight: 600; font-size: 14px;">Tạm ngưng cửa hàng</MudText>
            <MudText Typo="Typo.body2" Style="color: var(--admin-text-tertiary, #999); font-size: 13px; margin-top: 2px;">
                Cửa hàng sẽ không hiển thị trên POS. Có thể kích hoạt lại sau.
            </MudText>
        </div>
        <MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small"
                   OnClick="OnDeactivateShop" Disabled="_isDangerActionRunning"
                   Style="min-width: 120px; text-transform: none;">
            @if (_isDangerActionRunning && _dangerAction == "deactivate")
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" Class="mr-2" Style="width:16px;height:16px;" />
            }
            Tạm ngưng
        </MudButton>
    </div>

    @* EN: Close shop permanently — irreversible *@
    @* VI: Đóng cửa hàng vĩnh viễn — không thể hoàn tác *@
    <div style="padding: 16px 20px; display: flex; align-items: center; justify-content: space-between;">
        <div>
            <MudText Typo="Typo.subtitle1" Style="font-weight: 600; font-size: 14px;">Đóng cửa hàng vĩnh viễn</MudText>
            <MudText Typo="Typo.body2" Style="color: var(--admin-text-tertiary, #999); font-size: 13px; margin-top: 2px;">
                Không thể hoàn tác. Tất cả dữ liệu sẽ được lưu trữ nhưng cửa hàng sẽ bị khóa vĩnh viễn.
            </MudText>
        </div>
        <MudButton Variant="Variant.Filled" Color="Color.Error" Size="Size.Small"
                   OnClick="OnCloseShop" Disabled="_isDangerActionRunning"
                   Style="min-width: 120px; text-transform: none;">
            @if (_isDangerActionRunning && _dangerAction == "close")
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" Class="mr-2" Style="width:16px;height:16px;" />
            }
            Đóng vĩnh viễn
        </MudButton>
    </div>
</MudPaper>

@code {
    [Parameter] public Guid ShopId { get; set; }
    [Parameter] public string? ShopName { get; set; }
    [Parameter] public string? VerticalLabel { get; set; }
    [Parameter] public string? ShopStatus { get; set; }

    // Settings state
    private PosDataService.ShopSettingsInfo? _shopSettings;
    private string _settingsOpenTime = "";
    private string _settingsCloseTime = "";
    private List<string> _settingsOpenDays = new();
    private bool _featHasInventory, _featHasBooking, _featHasTables;
    private bool _featHasKitchen, _featHasShipping, _featHasDelivery;
    private string? _settingsMessage;
    private bool _settingsSuccess;

    private string? _shopName => ShopName;
    private string _verticalLabel => VerticalLabel ?? "";

    protected override async Task OnInitializedAsync()
    {
        if (ShopId != Guid.Empty)
        {
            await LoadShopSettings();
            await LoadAiConfig();
            await LoadActiveReceiptTemplateName();
        }
    }

    /// <summary>
    /// EN: Load the name of the active (default) receipt template from localStorage.
    /// VI: Tải tên mẫu hoá đơn mặc định từ localStorage.
    /// </summary>
    private async Task LoadActiveReceiptTemplateName()
    {
        try
        {
            var key = $"aPOS_receipt_templates_{ShopId}";
            var json = await JS.InvokeAsync<string?>("localStorage.getItem", key);
            if (!string.IsNullOrWhiteSpace(json))
            {
                var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
                var templates = JsonSerializer.Deserialize<List<ReceiptTemplateInfo>>(json, options);
                _activeReceiptTemplateName = templates?.FirstOrDefault(t => t.IsDefault)?.Name
                    ?? templates?.FirstOrDefault()?.Name;
            }
        }
        catch { /* non-fatal */ }
    }

    private record ReceiptTemplateInfo(string? Name, bool IsDefault);

    /// <summary>
    /// EN: Navigate to receipt templates management page.
    /// VI: Điều hướng đến trang quản lý mẫu hoá đơn.
    /// </summary>
    private void NavigateToReceiptTemplates()
    {
        // EN: Build URL using ShopId from parameter — navigate to receipt-templates section of ShopPage
        // VI: Xây dựng URL từ ShopId — điều hướng tới section receipt-templates của ShopPage
        var shopIdStr = ShopId.ToString();
        NavigationManager.NavigateTo($"/admin/shop/{shopIdStr}/receipt-templates");
    }

    private async Task LoadAiConfig()
    {
        try
        {
            var config = await DataService.GetAiChatConfigAsync(ShopId);
            if (config != null)
            {
                _aiEnabled = config.Enabled;
                _aiProvider = config.Provider ?? "openai";
                _aiApiKey = config.ApiKeyMasked ?? "";
                _aiModel = config.Model ?? "";
                _aiSystemPrompt = config.SystemPrompt ?? "";
            }
        }
        catch { /* AI config not found — defaults are fine */ }
    }

    private async Task SaveAiConfig()
    {
        _aiSaving = true;
        _aiMessage = null;
        StateHasChanged();
        try
        {
            var ok = await DataService.UpdateAiChatConfigAsync(ShopId, new
            {
                provider = _aiProvider,
                apiKey = _aiApiKey,
                model = string.IsNullOrWhiteSpace(_aiModel) ? null : _aiModel,
                systemPrompt = string.IsNullOrWhiteSpace(_aiSystemPrompt) ? null : _aiSystemPrompt,
                enabled = _aiEnabled
            });
            _aiSuccess = ok;
            _aiMessage = ok ? "Đã lưu cấu hình AI!" : "Lỗi khi lưu.";
        }
        catch (Exception ex) { _aiSuccess = false; _aiMessage = $"Lỗi: {ex.Message}"; }
        finally { _aiSaving = false; StateHasChanged(); }
    }

    private async Task LoadShopSettings()
    {
        if (ShopId == Guid.Empty) return;
        try
        {
            _shopSettings = await DataService.GetShopSettingsAsync(ShopId);
            if (_shopSettings != null)
            {
                _settingsOpenTime  = _shopSettings.OpenTime  ?? "";
                _settingsCloseTime = _shopSettings.CloseTime ?? "";
                _settingsOpenDays  = _shopSettings.OpenDays  ?? new();
                if (_shopSettings.Features != null)
                {
                    _featHasInventory = _shopSettings.Features.HasInventory;
                    _featHasBooking   = _shopSettings.Features.HasBooking;
                    _featHasTables    = _shopSettings.Features.HasTables;
                    _featHasKitchen   = _shopSettings.Features.HasKitchen;
                    _featHasShipping  = _shopSettings.Features.HasShipping;
                    _featHasDelivery  = _shopSettings.Features.HasDelivery;
                }
            }
        }
        catch { /* non-fatal */ }
    }

    private async Task SaveShopSettings()
    {
        if (ShopId == Guid.Empty) return;
        _settingsMessage = null;
        var features = new PosDataService.ShopFeaturesInfo
        {
            HasInventory = _featHasInventory, HasBooking = _featHasBooking, HasTables = _featHasTables,
            HasKitchen = _featHasKitchen, HasShipping = _featHasShipping, HasDelivery = _featHasDelivery
        };
        var req = new PosDataService.UpdateShopSettingsRequest(
            Features:  features,
            OpenTime:  string.IsNullOrWhiteSpace(_settingsOpenTime) ? null : _settingsOpenTime,
            CloseTime: string.IsNullOrWhiteSpace(_settingsCloseTime) ? null : _settingsCloseTime,
            OpenDays:  _settingsOpenDays.Any() ? _settingsOpenDays : null);
        var ok = await DataService.UpdateShopSettingsAsync(ShopId, req);
        _settingsSuccess = ok;
        _settingsMessage = ok ? "Đã lưu thiết lập thành công!" : "Lỗi khi lưu thiết lập.";
        StateHasChanged();
    }

    private void ToggleDay(string code)
    {
        if (_settingsOpenDays.Contains(code)) _settingsOpenDays.Remove(code);
        else _settingsOpenDays.Add(code);
        StateHasChanged();
    }

    // EN: Receipt template state
    // VI: Trạng thái mẫu hoá đơn
    private string? _activeReceiptTemplateName;

    // EN: AI config state
    // VI: Trạng thái cấu hình AI
    private bool _aiEnabled;
    private string _aiProvider = "openai";
    private string _aiApiKey = "";
    private string _aiModel = "";
    private string _aiSystemPrompt = "";
    private bool _showApiKey;
    private bool _aiSaving;
    private string? _aiMessage;
    private bool _aiSuccess;

    // EN: Publish state
    // VI: Trạng thái kích hoạt
    private bool _isPublishing;

    // EN: Danger Zone state
    // VI: Trạng thái Vùng nguy hiểm
    private bool _isDangerActionRunning;
    private string? _dangerAction;

    /// <summary>
    /// EN: Publish shop (Draft → Active). No confirmation needed.
    /// VI: Kích hoạt cửa hàng (Draft → Active). Không cần xác nhận.
    /// </summary>
    private async Task OnPublishShop()
    {
        if (ShopId == Guid.Empty) return;
        _isPublishing = true;
        StateHasChanged();
        try
        {
            var ok = await DataService.PublishShopAsync(ShopId);
            if (ok)
            {
                Snackbar.Add("Cửa hàng đã được kích hoạt thành công!", Severity.Success);
                ShopStatus = "Published";
                StateHasChanged();
            }
            else
            {
                Snackbar.Add("Không thể kích hoạt cửa hàng. Vui lòng thử lại.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Lỗi: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isPublishing = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Show deactivate confirmation dialog and call API.
    /// VI: Hiển thị dialog xác nhận tạm ngưng và gọi API.
    /// </summary>
    private async Task OnDeactivateShop()
    {
        if (ShopId == Guid.Empty) return;

        var confirmed = await DialogService.ShowMessageBox(
            "Tạm ngưng cửa hàng",
            $"Bạn có chắc muốn tạm ngưng cửa hàng {_shopName ?? "này"}?",
            yesText: "Tạm ngưng", cancelText: "Hủy");

        if (confirmed != true) return;

        _isDangerActionRunning = true;
        _dangerAction = "deactivate";
        StateHasChanged();

        try
        {
            var ok = await MerchantApi.DeactivateShopAsync(ShopId);
            if (ok)
            {
                Snackbar.Add("Đã tạm ngưng cửa hàng thành công.", Severity.Success);
                NavigationManager.NavigateTo("/admin");
            }
            else
            {
                Snackbar.Add("Không thể tạm ngưng cửa hàng. Vui lòng thử lại.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Lỗi: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isDangerActionRunning = false;
            _dangerAction = null;
            StateHasChanged();
        }
    }

    /// <summary>
    /// EN: Show close confirmation dialog (requires typing shop name) and call API.
    /// VI: Hiển thị dialog xác nhận đóng (yêu cầu nhập tên shop) và gọi API.
    /// </summary>
    private async Task OnCloseShop()
    {
        if (ShopId == Guid.Empty) return;

        var displayName = _shopName ?? "cửa hàng";

        // EN: Custom inline dialog requiring the user to type the shop name to confirm.
        // VI: Dialog tùy chỉnh yêu cầu người dùng nhập tên cửa hàng để xác nhận.
        var parameters = new DialogParameters<CloseShopConfirmDialog>
        {
            { x => x.ShopName, displayName }
        };
        var options = new DialogOptions
        {
            CloseButton = true,
            MaxWidth = MaxWidth.Small,
            FullWidth = true
        };
        var dialog = await DialogService.ShowAsync<CloseShopConfirmDialog>("Đóng cửa hàng vĩnh viễn", parameters, options);
        var result = await dialog.Result;

        if (result == null || result.Canceled) return;

        _isDangerActionRunning = true;
        _dangerAction = "close";
        StateHasChanged();

        try
        {
            var ok = await MerchantApi.CloseShopAsync(ShopId);
            if (ok)
            {
                Snackbar.Add("Đã đóng cửa hàng vĩnh viễn.", Severity.Success);
                NavigationManager.NavigateTo("/admin");
            }
            else
            {
                Snackbar.Add("Không thể đóng cửa hàng. Vui lòng thử lại.", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Lỗi: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isDangerActionRunning = false;
            _dangerAction = null;
            StateHasChanged();
        }
    }
}
