<?php require_once __DIR__ . '/../header.php'; ?>

<?php
$ui = [
    'add'  => __('actions.add_section', 'Add Section'),
    'save' => __('actions.save', 'Save'),
];

// AI settings — via active provider
$anyAiEnabled          = false;
$activeAiProvider      = '';
$activeAiProviderLabel = 'AI';
$activeAiModel         = '';
$aiDialectLine         = 'اكتب باللغة العربية الفصحى';

try {
    $_activeSvc = \Core\App\Services\AiService::fromActiveProvider();
    $anyAiEnabled          = true;
    $activeAiProvider      = $_activeSvc->getProvider();
    $activeAiProviderLabel = \Core\App\Services\AiService::getProviderLabel($activeAiProvider);
    $activeAiModel         = $_activeSvc->getModel() ?: '';
    $aiDialectLine         = $_activeSvc->buildDialectInstruction('ar');
} catch (\Throwable $e) {}

$geminiImageGeneration = $geminiImageGeneration ?? ['available' => false, 'model' => ''];
$productAiImageEnabled = !empty($geminiImageGeneration['available']);
$productAiImageTypes = [
    'hero' => __('products.ai_image_type_hero', 'Hero Image'),
    'lifestyle' => __('products.ai_image_type_lifestyle', 'Lifestyle Image'),
    'square_ad' => __('products.ai_image_type_square', 'Square Ad Image'),
    'clean_product' => __('products.ai_image_type_clean', 'Clean Product Image'),
];

$_badgePresetMap = product_badge_presets();
?>

<div class="container-fluid">

    <form method="POST"
          action="/admin/products/store"
          enctype="multipart/form-data"
          id="productForm">
        <?= \Core\System\Csrf::field(); ?>
        <input type="hidden" name="seo_share_payload" id="seoSharePayload" value="">

        <div class="row mb-4">
            <div class="col-12 d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-1"><?= __('products.add_product', 'Add Product') ?></h1>
                    <p class="text-muted mb-0"><?= __('products.create_subtitle') ?></p>
                </div>
                <div>
                    <button type="submit" class="btn btn-success">
                        <?= __('actions.save', 'Save') ?>
                    </button>
                    <a href="/admin/products" class="btn btn-outline-secondary ms-2">
                        <?= __('actions.back', 'Back') ?>
                    </a>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <ul class="nav nav-tabs mb-4">
            <li class="nav-item">
                <button type="button" class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-general">
                    <?= __('products.tab.general') ?>
                </button>
            </li>
            <li class="nav-item">
                <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-pricing">
                    <?= __('products.tab.pricing') ?>
                </button>
            </li>
            <li class="nav-item">
                <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-variants">
                    <?= __('products.variants') ?>
                </button>
            </li>
            <li class="nav-item">
                <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-stock">
                    <i class="bi bi-boxes me-1"></i><?= __('products.tab.stock', 'Stock') ?>
                </button>
            </li>
            <li class="nav-item">
                <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-media">
                    <?= __('products.tab.media', 'Media') ?>
                </button>
            </li>
            <li class="nav-item">
                <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-page">
                    <?= __('products.tab.page') ?>
                </button>
            </li>
            <li class="nav-item">
                <button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-offers">
                    <i class="bi bi-tags-fill me-1 text-warning"></i><?= __('products.tab.offers', 'Offers') ?>
                </button>
            </li>
        </ul>

        <div class="tab-content">

            <!-- ===== GENERAL ===== -->
            <div class="tab-pane fade show active" id="tab-general">
                <div class="card mb-4">
                    <div class="card-body">

                        <label class="form-label"><?= __('products.title') ?></label>
                        <div class="row g-2 mb-3">
                            <div class="col-md-9">
                                <input type="text" name="title" class="form-control" required>
                            </div>
                            <?php if ($anyAiEnabled): ?>
                            <div class="col-md-3 d-grid">
                                <button type="button" id="ai-generate-btn"
                                        class="btn btn-outline-primary d-flex align-items-center justify-content-center gap-2"
                                        data-label-idle="<?= __('ai.generate_description', 'Generate with AI') ?>"
                                        data-label-loading="<?= __('ai.generating', 'Generating...') ?>"
                                        data-error-title="<?= __('ai.error', 'Error') ?>"
                                        data-error-missing-title="<?= __('ai.error.missing_title', 'Please enter a product title first') ?>"
                                        data-error-csrf="<?= __('ai.error.csrf', 'Security token missing') ?>">
                                    <i class="bi bi-stars"></i>
                                    <?= __('ai.generate_description', 'Generate with AI') ?>
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('products.badge_text', 'Badge Text') ?></label>
                            <input type="text" id="badgeTextInputDisplay" class="form-control" maxlength="50"
                                   value=""
                                   placeholder="<?= __('products.badge_text_placeholder', 'Choose a badge from below') ?>"
                                   readonly>
                            <input type="hidden" name="badge_text" id="badgeTextInput" value="">
                            <div class="badge-preset-preview mt-2">
                                <?php foreach ($_badgePresetMap as $_presetKey => $_preset): ?>
                                    <button type="button"
                                            class="badge-preset-chip <?= htmlspecialchars($_preset['class']) ?>"
                                            data-badge-key="<?= htmlspecialchars($_presetKey, ENT_QUOTES) ?>"
                                            data-badge-label="<?= htmlspecialchars($_preset['text'], ENT_QUOTES) ?>"
                                            onclick="applyBadgePreset(<?= json_encode($_presetKey) ?>, <?= json_encode($_preset['text']) ?>, this)">
                                        <span class="badge-preset-emoji"><?= htmlspecialchars($_preset['emoji'] ?? '🏷️') ?></span>
                                        <span><?= htmlspecialchars($_preset['text']) ?></span>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                            <div class="text-muted small mt-2">
                                <?= __('products.badge_preset_help_click', 'Click one of the badges below to insert it into the field.') ?>
                            </div>
                        </div>
                        <style>
                            .badge-preset-preview{display:flex;flex-wrap:wrap;gap:10px;}
                            #badgeTextInputDisplay[readonly]{background:#f8fafc;font-weight:700;cursor:default;}
                        </style>
                        <script>
                            (function(){
                                function applyBadgePresetScoped(container, key, label, el){
                                    if (!container) return;
                                    var hidden = container.querySelector('#badgeTextInput');
                                    var display = container.querySelector('#badgeTextInputDisplay');
                                    if (hidden) hidden.value = key || '';
                                    if (display) display.value = label || '';
                                    container.querySelectorAll('.badge-preset-chip').forEach(function(chip){ chip.classList.remove('is-active'); chip.setAttribute('aria-pressed','false'); });
                                    if (el) { el.classList.add('is-active'); el.setAttribute('aria-pressed','true'); }
                                }
                                window.applyBadgePreset = function(key, label, el){
                                    var container = el ? el.closest('.mb-3') : document;
                                    applyBadgePresetScoped(container, key, label, el || null);
                                };
                                document.addEventListener('DOMContentLoaded', function(){
                                    var legacyMap = {
                                        'new':'products.badge_preset_new',
                                        'hot':'products.badge_preset_hot',
                                        'sale':'products.badge_preset_sale',
                                        'limited':'products.badge_preset_limited',
                                        'exclusive':'products.badge_preset_exclusive',
                                        'free_shipping':'products.badge_preset_shipping',
                                        'discount':'products.badge_preset_discount',
                                        'وصل حديثًا':'products.badge_preset_new',
                                        'الأكثر مبيعًا':'products.badge_preset_hot',
                                        'عرض خاص':'products.badge_preset_sale',
                                        'كمية محدودة':'products.badge_preset_limited',
                                        'حصري':'products.badge_preset_exclusive',
                                        'توصيل مجاني':'products.badge_preset_shipping',
                                        'تخفيض':'products.badge_preset_discount',
                                        'New Arrival':'products.badge_preset_new',
                                        'Best Seller':'products.badge_preset_hot',
                                        'Special Offer':'products.badge_preset_sale',
                                        'Limited Stock':'products.badge_preset_limited',
                                        'Exclusive':'products.badge_preset_exclusive',
                                        'Free Shipping':'products.badge_preset_shipping',
                                        'Discount':'products.badge_preset_discount'
                                    };
                                    document.querySelectorAll('.badge-preset-preview').forEach(function(preview){
                                        var container = preview.closest('.mb-3') || preview.parentElement;
                                        var hidden = container ? container.querySelector('#badgeTextInput') : null;
                                        var display = container ? container.querySelector('#badgeTextInputDisplay') : null;
                                        if (!container || !hidden) return;
                                        var current = (hidden.value || '').trim();
                                        if (legacyMap[current]) {
                                            hidden.value = legacyMap[current];
                                            current = hidden.value;
                                        }
                                        preview.querySelectorAll('.badge-preset-chip').forEach(function(chip){
                                            chip.setAttribute('aria-pressed','false');
                                            chip.addEventListener('click', function(ev){
                                                ev.preventDefault();
                                                ev.stopPropagation();
                                                applyBadgePresetScoped(container, chip.getAttribute('data-badge-key') || '', chip.getAttribute('data-badge-label') || '', chip);
                                            });
                                            var key = (chip.getAttribute('data-badge-key') || '').trim();
                                            if (key === current) {
                                                chip.classList.add('is-active');
                                                chip.setAttribute('aria-pressed','true');
                                                if (display) display.value = chip.getAttribute('data-badge-label') || '';
                                            }
                                        });
                                    });
                                });
                            })();
                        </script>

                        <label class="form-label"><?= __('products.short_description') ?></label>
                        <textarea name="short_description" class="form-control mb-3" rows="2"></textarea>

                        <!-- ════════════════════════════════════════════════
                             DESCRIPTION EDITOR
                        ════════════════════════════════════════════════ -->
                        <div class="mb-3" id="desc-editor-wrapper">

                            <div class="d-flex align-items-center justify-content-between mb-2">
                                <label class="form-label mb-0">
                                    <?= __('products.description', 'Description') ?>
                                </label>
                                <div class="btn-group btn-group-sm">
                                    <input type="radio" class="btn-check" name="desc_mode_radio" id="desc-mode-text" value="text" autocomplete="off" checked>
                                    <label class="btn btn-outline-secondary" for="desc-mode-text">
                                        <i class="bi bi-type me-1"></i><?= __('products.desc_mode_text', 'Plain Text') ?>
                                    </label>
                                    <input type="radio" class="btn-check" name="desc_mode_radio" id="desc-mode-html" value="html" autocomplete="off">
                                    <label class="btn btn-outline-primary" for="desc-mode-html">
                                        <i class="bi bi-code-slash me-1"></i>HTML
                                    </label>
                                </div>
                            </div>

                            <!-- Plain text -->
                            <div id="desc-text-panel">
                                <textarea name="description" id="desc-textarea"
                                          class="form-control" rows="6"></textarea>
                            </div>

                            <!-- HTML Editor -->
                            <div id="desc-html-panel" style="display:none">

                                <?php if ($anyAiEnabled): ?>
                                <!-- AI HTML Assistant -->
                                <div class="card border-0 shadow-sm mb-3" id="claude-chat-box" style="border-radius:12px;overflow:hidden;">
                                    <div class="d-flex align-items-center justify-content-between px-3 py-2" style="background:linear-gradient(135deg,#f59e0b,#d97706);color:#fff;">
                                        <span class="fw-semibold small d-flex align-items-center gap-2">
                                            <i class="bi bi-stars"></i>
                                            <?= __('ai.assistant', 'مساعد الذكاء الاصطناعي') ?>
                                            <span class="badge" style="background:rgba(255,255,255,0.25);font-size:10px;font-weight:500;"><?= htmlspecialchars($activeAiProviderLabel . ($activeAiModel !== '' ? ' • ' . $activeAiModel : '')) ?></span>
                                        </span>
                                        <button type="button" class="btn btn-sm p-0 border-0" id="claude-chat-toggle" style="color:rgba(255,255,255,0.8);background:none;">
                                            <i class="bi bi-chevron-up"></i>
                                        </button>
                                    </div>

                                    <div id="claude-chat-body" style="min-height:80px;max-height:340px;overflow-y:auto;padding:14px 14px 8px;display:flex;flex-direction:column;gap:10px;background:#fafafa;">
                                        <div class="text-center py-3" id="claude-chat-empty">
                                            <i class="bi bi-stars text-warning d-block mb-1" style="font-size:22px;"></i>
                                            <span class="text-muted small"><?= __('ai.assistant_hint', 'اطلب من الذكاء الاصطناعي كتابة وصف HTML لمنتجك') ?></span>
                                        </div>
                                    </div>

                                    <div class="border-top px-3 pt-2 pb-3" style="background:#fff;">
                                        <!-- Quick templates -->
                                        <div class="d-flex flex-wrap gap-1 mb-2">
                                            <span class="text-muted small me-1 align-self-center" style="font-size:11px;"><?= __('ai.templates','نماذج:') ?></span>
                                            <button type="button" class="claude-tpl btn btn-sm py-0 px-2" style="font-size:11px;border:1px solid #d97706;color:#d97706;border-radius:20px;background:none;"
                                                data-msg="<?= __('ai.tpl_desc', 'Write a detailed HTML product description based on the title') ?>">
                                                <i class="bi bi-file-text me-1"></i><?= __('ai.tpl_desc_short', 'Full Description') ?>
                                            </button>
                                            <button type="button" class="claude-tpl btn btn-sm py-0 px-2" style="font-size:11px;border:1px solid #d97706;color:#d97706;border-radius:20px;background:none;"
                                                data-msg="<?= __('ai.tpl_features', 'List the main features and benefits as HTML bullet points') ?>">
                                                <i class="bi bi-list-check me-1"></i><?= __('ai.tpl_features_short', 'Features') ?>
                                            </button>
                                            <button type="button" class="claude-tpl btn btn-sm py-0 px-2" style="font-size:11px;border:1px solid #d97706;color:#d97706;border-radius:20px;background:none;"
                                                data-msg="<?= __('ai.tpl_faq', 'Create an HTML FAQ section for this product') ?>">
                                                <i class="bi bi-question-circle me-1"></i>FAQ
                                            </button>
                                        </div>

                                        <!-- Image attach row -->
                                        <div class="d-flex align-items-center gap-2 mb-2">
                                            <label class="btn btn-sm py-1 px-2 mb-0" style="cursor:pointer;font-size:12px;border:1px dashed #dee2e6;border-radius:8px;color:#6c757d;background:#f8f9fa;">
                                                <i class="bi bi-paperclip me-1"></i><?= __('ai.attach_image', 'Attach Image') ?>
                                                <input type="file" id="claude-img-input" accept="image/*" style="display:none" multiple>
                                            </label>
                                            <div id="claude-img-preview" class="d-flex gap-1 flex-wrap"></div>
                                        </div>

                                        <!-- Input row -->
                                        <div class="d-flex gap-2 align-items-end">
                                            <textarea id="claude-msg-input" class="form-control form-control-sm flex-grow-1"
                                                      rows="2" style="resize:none;border-radius:10px;font-size:13px;"
                                                      placeholder="<?= __('ai.assistant_placeholder', 'اطلب من الذكاء الاصطناعي...') ?>"></textarea>
                                            <button type="button" class="btn btn-warning btn-sm px-3 d-flex align-items-center gap-1" id="claude-send-btn"
                                                    style="border-radius:10px;min-width:44px;flex-shrink:0;">
                                                <i class="bi bi-send-fill"></i>
                                            </button>
                                        </div>

                                        <!-- Footer row -->
                                        <div class="d-flex justify-content-between align-items-center mt-2">
                                            <button type="button" class="btn btn-sm p-0 text-muted border-0 bg-transparent" style="font-size:11px;" id="claude-clear-btn">
                                                <i class="bi bi-trash me-1"></i><?= __('ai.clear_chat', 'Clear') ?>
                                            </button>
                                            <button type="button" class="btn btn-sm px-3 py-1 border-0" id="claude-apply-btn" style="display:none;background:#d1fae5;color:#065f46;border-radius:20px;font-size:12px;">
                                                <i class="bi bi-check-lg me-1"></i><?= __('ai.apply_to_description', 'Apply to Description') ?>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>


                                <textarea name="description" id="desc-html-textarea"
                                          class="form-control font-monospace" rows="10"
                                          placeholder="<h2>Product Title</h2>&#10;<p>Description...</p>"
                                          style="direction:ltr;text-align:left;"></textarea>
                                <div class="form-text">
                                    <i class="bi bi-info-circle me-1"></i>
                                    <?= __('products.html_hint', 'Write HTML directly. The content will be rendered as-is on the product page.') ?>
                                </div>
                            </div>

                        </div>
                        <!-- /description editor -->
                        <script>
                        window.AI_ASSISTANT_ENABLED      = <?= $anyAiEnabled ? 'true' : 'false' ?>;
                        window.AI_ASSISTANT_PROVIDER     = <?= json_encode($activeAiProvider) ?>;
                        window.AI_ASSISTANT_MODEL        = <?= json_encode($activeAiModel) ?>;
                        window.AI_ASSISTANT_DIALECT_LINE = <?= json_encode($aiDialectLine) ?>;
                        window.PRODUCT_TITLE_EL          = 'input[name="title"]';
                        </script>

                        <div class="form-check mt-3">
                            <input class="form-check-input" type="checkbox" name="is_featured" id="is_featured" value="1">
                            <label class="form-check-label fw-semibold" for="is_featured">
                                <?= __('products.is_featured', 'Featured Product') ?>
                            </label>
                            <div class="text-muted small">
                                <?= __('products.is_featured_help', 'Mark this product as featured for special sections.') ?>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header bg-white">
                        <strong><i class="bi bi-tags me-1"></i><?= __('products.categories.title', 'Categories') ?></strong>
                    </div>
                    <div class="card-body" style="max-height:260px; overflow:auto">
                        <?php if (empty($categories)): ?>
                            <p class="text-muted mb-0"><?= __('products.categories.empty', 'No categories available.') ?></p>
                        <?php else: ?>
                            <?php foreach ($categories as $cat): ?>
                                <?php if ($cat['status'] !== 'active') continue; ?>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox"
                                           name="categories[]" value="<?= (int)$cat['id'] ?>"
                                           id="cat_<?= (int)$cat['id'] ?>">
                                    <label class="form-check-label" for="cat_<?= (int)$cat['id'] ?>">
                                        <?= htmlspecialchars($cat['name']) ?>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- ===== PRICING ===== -->
            <div class="tab-pane fade" id="tab-pricing">
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label"><?= __('products.price') ?></label>
                                <input type="number" step="0.01" name="price" class="form-control" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('products.sale_price', 'Sale price') ?></label>
                                <input type="number" step="0.01" name="sale_price" class="form-control">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label"><?= __('products.discount_type', 'Discount type') ?></label>
                                <select name="discount_type" class="form-select">
                                    <option value=""><?= __('common.none', 'None') ?></option>
                                    <option value="fixed"><?= __('products.discount_fixed', 'Fixed') ?></option>
                                    <option value="percent"><?= __('products.discount_percent', 'Percent') ?></option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label"><?= __('products.discount_value', 'Discount value') ?></label>
                                <input type="number" step="0.01" name="discount_value" class="form-control" placeholder="0.00">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('products.discount_start', 'Discount start') ?></label>
                                <input type="datetime-local" name="discount_start" class="form-control">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('products.discount_end', 'Discount end') ?></label>
                                <input type="datetime-local" name="discount_end" class="form-control">
                            </div>
                            <div class="col-12">
                                <div class="alert alert-light border mb-0">
                                    <div class="d-flex gap-2 align-items-start">
                                        <i class="bi bi-info-circle text-primary"></i>
                                        <div class="small text-muted">
                                            <?= __('products.discount_help', 'Discount settings will be used later for countdown and price display on product page.') ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ===== VARIANTS ===== -->
            <div class="tab-pane fade" id="tab-variants">
                <div class="row g-4">
                    <div class="col-lg-6">
                        <div class="card h-100">
                            <div class="card-header bg-white d-flex align-items-center justify-content-between">
                                <strong><i class="bi bi-rulers me-1"></i><?= __('products.sizes') ?></strong>
                                <span class="badge bg-light text-dark border" id="sizesCount">0</span>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label mb-2"><?= __('products.size_type') ?></label>
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="size_type" id="size_type_clothes" autocomplete="off" value="clothes" checked>
                                        <label class="btn btn-outline-primary btn-sm" for="size_type_clothes"><?= __('products.sizes_clothes') ?></label>
                                        <input type="radio" class="btn-check" name="size_type" id="size_type_shoes" autocomplete="off" value="shoes">
                                        <label class="btn btn-outline-primary btn-sm" for="size_type_shoes"><?= __('products.sizes_shoes') ?></label>
                                    </div>
                                    <div class="text-muted small mt-2"><?= __('products.sizes_help') ?></div>
                                </div>
                                <div class="d-flex gap-2 align-items-end">
                                    <div class="flex-grow-1">
                                        <label class="form-label"><?= __('products.select_size') ?></label>
                                        <select id="sizeSelect" class="form-select form-select-sm"></select>
                                    </div>
                                    <div>
                                        <button type="button" class="btn btn-primary btn-sm" id="addSizeBtn"
                                                style="height:38px;min-width:44px" title="<?= __('products.add_size') ?>">
                                            <i class="bi bi-plus-lg"></i>
                                        </button>
                                    </div>
                                </div>
                                <div id="sizesList" class="mt-3 d-flex flex-wrap gap-2"></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="card h-100">
                            <div class="card-header bg-white d-flex align-items-center justify-content-between">
                                <strong><i class="bi bi-palette me-1"></i><?= __('products.colors') ?></strong>
                                <span class="badge bg-light text-dark border" id="colorsCount">0</span>
                            </div>
                            <div class="card-body">
                                <div class="row g-2 align-items-end">
                                    <div class="col-md-4">
                                        <label class="form-label"><?= __('products.color_pick') ?></label>
                                        <input type="color" id="colorPicker" class="form-control form-control-color" value="#000000">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label"><?= __('products.color_name') ?></label>
                                        <input type="text" id="colorName" class="form-control form-control-sm"
                                               placeholder="<?= __('products.color_name_placeholder') ?>">
                                    </div>
                                    <div class="col-md-2 d-grid">
                                        <button type="button" class="btn btn-primary btn-sm" id="addColorBtn" title="<?= __('products.add_color') ?>">
                                            <i class="bi bi-plus-lg"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="text-muted small mt-2"><?= __('products.colors_help') ?></div>
                                <div id="colorsList" class="mt-3 d-flex flex-wrap gap-2"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="variants" id="variantsInput" value="">
            </div>

            <!-- ===== STOCK ===== -->
            <div class="tab-pane fade" id="tab-stock">

            <style>
            .stk-hero{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;margin-bottom:24px}
            .stk-card{background:#fff;border:1.5px solid #e5e7eb;border-radius:14px;padding:20px 22px;position:relative;overflow:hidden;transition:box-shadow .2s}
            .stk-card:hover{box-shadow:0 6px 24px rgba(0,0,0,.08)}
            .stk-card-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:#9ca3af;margin-bottom:6px}
            .stk-card-val{font-size:32px;font-weight:900;line-height:1;color:#111827}
            .stk-card-sub{font-size:12px;color:#9ca3af;margin-top:4px}
            .stk-card-badge{position:absolute;top:14px;right:14px}
            .stk-card.is-ok{border-color:#d1fae5;background:linear-gradient(135deg,#f0fdf4,#fff)}
            .stk-card.is-low{border-color:#fef3c7;background:linear-gradient(135deg,#fffbeb,#fff)}
            .stk-card.is-zero{border-color:#fee2e2;background:linear-gradient(135deg,#fff1f2,#fff)}
            .stk-card.is-ok .stk-card-val{color:#059669}
            .stk-card.is-low .stk-card-val{color:#d97706}
            .stk-card.is-zero .stk-card-val{color:#dc2626}
            .stk-settings{background:#fff;border:1.5px solid #e5e7eb;border-radius:14px;padding:20px 22px;margin-bottom:24px}
            .stk-settings-title{font-size:13px;font-weight:700;color:#374151;margin-bottom:16px;display:flex;align-items:center;gap:8px}
            .stk-fill-bar{display:flex;align-items:center;gap:10px;margin-bottom:20px}
            .stk-fill-btn{font-size:12px;padding:4px 12px;white-space:nowrap}
            .stk-variants-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}
            .stk-variant-card{background:#f9fafb;border:1.5px solid #e5e7eb;border-radius:12px;padding:14px 16px;display:flex;flex-direction:column;gap:10px;transition:border-color .2s,box-shadow .2s,background .2s;position:relative}
            .stk-variant-card:focus-within{border-color:#6366f1;box-shadow:0 0 0 3px rgba(99,102,241,.12);background:#fff}
            .stk-variant-card.is-ok{border-left:4px solid #10b981}
            .stk-variant-card.is-low{border-left:4px solid #f59e0b}
            .stk-variant-card.is-zero{border-left:4px solid #ef4444}
            .stk-variant-label{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
            .stk-size-badge{display:inline-flex;align-items:center;justify-content:center;min-width:36px;height:28px;padding:0 8px;background:#fff;border:1.5px solid #d1d5db;border-radius:6px;font-size:13px;font-weight:700;color:#374151}
            .stk-color-dot{width:20px;height:20px;border-radius:50%;border:2px solid rgba(0,0,0,.12);flex-shrink:0}
            .stk-color-name{font-size:12px;color:#6b7280;font-weight:600}
            .stk-qty-row{display:flex;align-items:center;gap:6px}
            .stk-qty-minus,.stk-qty-plus{width:28px;height:28px;border-radius:6px;border:1.5px solid #d1d5db;background:#fff;font-size:16px;font-weight:700;color:#374151;display:flex;align-items:center;justify-content:center;cursor:pointer;user-select:none;flex-shrink:0;transition:all .15s}
            .stk-qty-minus:hover{border-color:#ef4444;color:#ef4444;background:#fff1f2}
            .stk-qty-plus:hover{border-color:#10b981;color:#10b981;background:#f0fdf4}
            .stk-qty-input{flex:1;min-width:0;text-align:center;font-size:18px;font-weight:800;color:#111827;border:1.5px solid #d1d5db;border-radius:8px;padding:4px 6px;background:#fff;transition:border-color .15s}
            .stk-qty-input:focus{outline:none;border-color:#6366f1}
            .stk-status-pill{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:700;padding:3px 10px;border-radius:99px;letter-spacing:.3px}
            .stk-status-ok{background:#d1fae5;color:#065f46}
            .stk-status-low{background:#fef3c7;color:#92400e}
            .stk-status-zero{background:#fee2e2;color:#991b1b}
            .stk-progress-wrap{height:4px;background:#e5e7eb;border-radius:99px;margin-top:2px;overflow:hidden}
            .stk-progress-bar{height:100%;border-radius:99px;transition:width .4s ease,background .3s}
            </style>

            <!-- KPI Cards (يتم تحديثها ديناميكياً) -->
            <div class="stk-hero" id="stk-kpi-row">
                <div class="stk-card is-zero" id="stk-kpi-total">
                    <div class="stk-card-label"><?= __('products.stock_total','Total Stock') ?></div>
                    <div class="stk-card-val" id="kpi-total-val">0</div>
                    <div class="stk-card-sub" id="kpi-total-sub"><?= __('products.stock_units','units') ?></div>
                    <div class="stk-card-badge"><span class="stk-status-pill stk-status-zero" id="kpi-total-pill">🔴 <?= __('products.out_of_stock','Out of Stock') ?></span></div>
                </div>
                <div class="stk-card" id="stk-kpi-variants" style="display:none">
                    <div class="stk-card-label"><?= __('products.stock_variants_count','Variants') ?></div>
                    <div class="stk-card-val" id="kpi-variants-val">0</div>
                    <div class="stk-card-sub"><?= __('products.stock_combinations','combinations') ?></div>
                </div>
                <div class="stk-card" id="stk-kpi-zero" style="display:none">
                    <div class="stk-card-label"><?= __('products.stock_out_variants','Out of Stock') ?></div>
                    <div class="stk-card-val" id="kpi-zero-val">0</div>
                    <div class="stk-card-sub"><?= __('products.stock_variants_label','variants') ?></div>
                </div>
                <div class="stk-card">
                    <div class="stk-card-label"><?= __('products.stock_alert','Alert Threshold') ?></div>
                    <div class="stk-card-val" id="kpi-alert-val">5</div>
                    <div class="stk-card-sub"><?= __('products.stock_alert_hint_short','notify below this') ?></div>
                </div>
            </div>

            <!-- Settings -->
            <div class="stk-settings mb-4">
                <div class="stk-settings-title">
                    <i class="bi bi-sliders2"></i>
                    <?= __('products.stock_settings','Stock Settings') ?>
                </div>
                <div class="row g-3">
                    <!-- حقل الكمية الإجمالية — يظهر فقط بدون متغيرات -->
                    <div class="col-md-4" id="stk-global-qty-wrap">
                        <label class="form-label fw-semibold"><?= __('products.stock_quantity','Quantity') ?></label>
                        <div class="input-group">
                            <input type="number" name="stock_quantity" class="form-control" min="0" value="0" id="global-stock-input">
                            <span class="input-group-text text-muted"><?= __('products.stock_units','units') ?></span>
                        </div>
                        <div class="text-muted small mt-1"><?= __('products.stock_quantity_hint','Used when no variants are set') ?></div>
                    </div>
                    <!-- Fill-all — يظهر فقط مع متغيرات -->
                    <div class="col-md-5" id="stk-fill-wrap" style="display:none">
                        <label class="form-label fw-semibold"><?= __('products.stock_fill_all','Set all variants to') ?></label>
                        <div class="stk-fill-bar">
                            <input type="number" id="fill-all-qty" class="form-control form-control-sm" min="0" value="10" style="width:90px">
                            <button type="button" class="btn btn-outline-primary btn-sm stk-fill-btn" id="fill-all-btn">
                                <i class="bi bi-lightning-fill me-1"></i><?= __('products.stock_fill_all_btn','Apply to all') ?>
                            </button>
                            <button type="button" class="btn btn-outline-danger btn-sm stk-fill-btn" id="zero-all-btn">
                                <i class="bi bi-x-circle me-1"></i><?= __('products.stock_zero_all','Zero all') ?>
                            </button>
                        </div>
                        <div class="text-muted small"><?= __('products.stock_fill_hint','Quickly set same quantity for all combinations') ?></div>
                        <!-- hidden global qty when variants exist -->
                        <input type="hidden" name="stock_quantity" id="global-stock-hidden" value="0">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-semibold"><?= __('products.stock_alert','Alert Threshold') ?></label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="bi bi-bell"></i></span>
                            <input type="number" name="stock_alert" class="form-control" min="0" value="5" id="alert-threshold">
                        </div>
                        <div class="text-muted small mt-1"><?= __('products.stock_alert_hint','Notify when stock reaches this level') ?></div>
                    </div>
                </div>
            </div>

            <!-- Variant cards grid (يتم بناؤه من JS) -->
            <div id="stk-variants-section" style="display:none">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <div>
                        <strong class="d-block"><?= __('products.stock_variants','Variant Stock') ?></strong>
                        <span class="text-muted small"><?= __('products.stock_variants_hint','Set quantity for each combination') ?></span>
                    </div>
                    <span class="badge bg-light text-dark border">
                        <?= __('products.stock_total','Total') ?>: <span id="total-variant-stock">0</span>
                    </span>
                </div>
                <div class="stk-variants-grid" id="stk-variants-grid"></div>
            </div>

            <!-- رسالة لا متغيرات -->
            <div id="stk-no-variants-msg">
                <div class="alert border rounded-3 d-flex gap-3 align-items-start" style="background:#f0f9ff;border-color:#bae6fd!important">
                    <i class="bi bi-info-circle-fill text-info fs-5 flex-shrink-0 mt-1"></i>
                    <div>
                        <div class="fw-semibold mb-1"><?= __('products.stock_no_variants_title','No variants defined') ?></div>
                        <div class="text-muted small"><?= __('products.stock_no_variants_create','Add sizes or colors from the Variants tab to set stock per combination.') ?></div>
                    </div>
                </div>
            </div>

                <input type="hidden" name="variant_stock" id="variantStockInput" value="[]">

            </div><!-- /tab-stock -->

            <script>
            // ════════════════════════════════════════════════════════
            //  STOCK TAB — Dynamic builder (create.php)
            //  Reads variantsState (sizes/colors) and builds cards
            // ════════════════════════════════════════════════════════
            (function () {
                var LABEL_OK   = <?= json_encode(__('products.in_stock','OK')) ?>;
                var LABEL_LOW  = <?= json_encode(__('products.low_stock','Low')) ?>;
                var LABEL_ZERO = <?= json_encode(__('products.out_of_stock','Out')) ?>;
                var LABEL_ZERO_CONFIRM = <?= json_encode(__('products.stock_zero_confirm','Set all variants to zero?')) ?>;

                // ── حالة المخزون: {key → qty}  key = "size||color" ──
                var stockState = {};

                // ── ربط مع variantsState (يُحدَّث بعد init) ──
                function getVariantsState() {
                    return (window.variantsState && typeof window.variantsState === 'object')
                        ? window.variantsState
                        : { sizes: [], colors: [] };
                }

                // ── بناء قائمة التركيبات ──
                function buildCombinations() {
                    var vs     = getVariantsState();
                    var sizes  = (vs.sizes  || []).filter(function(s){ return s.value && s.value !== ''; });
                    var colors = (vs.colors || []).filter(function(c){ return c.name  && c.name  !== ''; });
                    var rows   = [];

                    if (sizes.length && colors.length) {
                        sizes.forEach(function(sz) {
                            colors.forEach(function(cl) {
                                rows.push({ size: sz.value, color: cl.name, code: cl.code || '' });
                            });
                        });
                    } else if (sizes.length) {
                        sizes.forEach(function(sz) { rows.push({ size: sz.value, color: '', code: '' }); });
                    } else if (colors.length) {
                        colors.forEach(function(cl) { rows.push({ size: '', color: cl.name, code: cl.code || '' }); });
                    }
                    return rows;
                }

                // ── مفتاح التخزين ──
                function rowKey(row) { return row.size + '||' + row.color; }

                // ── حساب KPIs ──
                function calcKpis(rows, alert) {
                    var total = 0, zeros = 0;
                    rows.forEach(function(r) {
                        var q = stockState[rowKey(r)] || 0;
                        total += q;
                        if (q === 0) zeros++;
                    });
                    return { total: total, zeros: zeros, count: rows.length };
                }

                // ── تحديث KPI cards ──
                function updateKpis(rows, alert) {
                    var k   = calcKpis(rows, alert);
                    var hasV = rows.length > 0;

                    // total
                    var tot = hasV ? k.total : (parseInt(document.getElementById('global-stock-input').value, 10) || 0);
                    document.getElementById('kpi-total-val').textContent = tot;
                    document.getElementById('kpi-alert-val').textContent = alert;

                    var kpiCard = document.getElementById('stk-kpi-total');
                    kpiCard.classList.remove('is-ok','is-low','is-zero');
                    var pill = document.getElementById('kpi-total-pill');
                    pill.classList.remove('stk-status-ok','stk-status-low','stk-status-zero');

                    var sub  = hasV ? <?= json_encode(__('products.stock_across_variants','across all variants')) ?> : <?= json_encode(__('products.stock_units','units')) ?>;
                    document.getElementById('kpi-total-sub').textContent = sub;

                    if (tot === 0) {
                        kpiCard.classList.add('is-zero'); pill.classList.add('stk-status-zero');
                        pill.textContent = '🔴 ' + <?= json_encode(__('products.out_of_stock','Out of Stock')) ?>;
                    } else if (tot <= alert) {
                        kpiCard.classList.add('is-low');  pill.classList.add('stk-status-low');
                        pill.textContent = '🟡 ' + <?= json_encode(__('products.low_stock','Low Stock')) ?>;
                    } else {
                        kpiCard.classList.add('is-ok');   pill.classList.add('stk-status-ok');
                        pill.textContent = '🟢 ' + <?= json_encode(__('products.in_stock','In Stock')) ?>;
                    }

                    // variants KPI cards
                    document.getElementById('stk-kpi-variants').style.display = hasV ? '' : 'none';
                    document.getElementById('stk-kpi-zero').style.display     = hasV ? '' : 'none';
                    if (hasV) {
                        document.getElementById('kpi-variants-val').textContent = k.count;
                        document.getElementById('kpi-zero-val').textContent     = k.zeros;
                        var zCard = document.getElementById('stk-kpi-zero');
                        zCard.classList.remove('is-ok','is-zero');
                        zCard.classList.add(k.zeros > 0 ? 'is-zero' : 'is-ok');
                    }

                    // total in header
                    var tvEl = document.getElementById('total-variant-stock');
                    if (tvEl) tvEl.textContent = k.total;
                }

                // ── بناء / إعادة بناء كل الـ cards ──
                function rebuildGrid() {
                    var rows   = buildCombinations();
                    var alert  = parseInt(document.getElementById('alert-threshold').value, 10) || 5;
                    var grid   = document.getElementById('stk-variants-grid');
                    var hasV   = rows.length > 0;

                    // إظهار / إخفاء العناصر
                    document.getElementById('stk-variants-section').style.display = hasV ? '' : 'none';
                    document.getElementById('stk-no-variants-msg').style.display  = hasV ? 'none' : '';
                    document.getElementById('stk-global-qty-wrap').style.display  = hasV ? 'none' : '';
                    document.getElementById('stk-fill-wrap').style.display        = hasV ? '' : 'none';

                    // حذف إدخالات name=stock_quantity المكررة عند التبديل
                    if (hasV) {
                        var gInp = document.querySelector('input[name="stock_quantity"]:not(#global-stock-hidden)');
                        if (gInp && gInp.id !== 'global-stock-hidden') gInp.removeAttribute('name');
                        var ghInp = document.getElementById('global-stock-hidden');
                        if (ghInp) ghInp.name = 'stock_quantity';
                    } else {
                        var gInp2 = document.getElementById('global-stock-input');
                        if (gInp2) gInp2.name = 'stock_quantity';
                        var ghInp2 = document.getElementById('global-stock-hidden');
                        if (ghInp2) ghInp2.removeAttribute('name');
                    }

                    // بناء cards
                    grid.innerHTML = '';
                    var maxQty = Math.max(1, Math.max.apply(null, rows.map(function(r){ return stockState[rowKey(r)] || 0; }).concat([1])));

                    rows.forEach(function(row, ri) {
                        var k    = rowKey(row);
                        var qty  = stockState[k] || 0;
                        var cls  = qty === 0 ? 'is-zero' : (qty <= alert ? 'is-low' : 'is-ok');
                        var pColor = qty === 0 ? '#ef4444' : (qty <= alert ? '#f59e0b' : '#10b981');
                        var pct  = Math.min(100, Math.round(qty / maxQty * 100));
                        var pillCls = qty === 0 ? 'stk-status-zero' : (qty <= alert ? 'stk-status-low' : 'stk-status-ok');
                        var pillTxt = qty === 0 ? LABEL_ZERO : (qty <= alert ? LABEL_LOW : LABEL_OK);

                        var labelHtml = '';
                        if (row.size)  labelHtml += '<span class="stk-size-badge">' + esc(row.size) + '</span>';
                        if (row.code)  labelHtml += '<span class="stk-color-dot" style="background:' + esc(row.code) + '"></span>';
                        if (row.color) labelHtml += '<span class="stk-color-name">' + esc(row.color) + '</span>';

                        var card = document.createElement('div');
                        card.className = 'stk-variant-card ' + cls;
                        card.dataset.row = ri;
                        card.innerHTML =
                            '<div class="stk-variant-label">' + labelHtml + '</div>' +
                            '<div class="stk-qty-row">' +
                                '<button type="button" class="stk-qty-minus" data-row="' + ri + '">−</button>' +
                                '<input type="number" min="0" class="stk-qty-input variant-stock-input"' +
                                    ' data-size="' + esc(row.size) + '"' +
                                    ' data-color="' + esc(row.color) + '"' +
                                    ' data-row="' + ri + '"' +
                                    ' value="' + qty + '">' +
                                '<button type="button" class="stk-qty-plus" data-row="' + ri + '">+</button>' +
                            '</div>' +
                            '<div>' +
                                '<div class="d-flex align-items-center justify-content-between mb-1">' +
                                    '<span class="stk-status-pill ' + pillCls + '" id="stk-pill-' + ri + '">' + pillTxt + '</span>' +
                                    '<span class="text-muted" style="font-size:11px" id="stk-pct-' + ri + '">' + pct + '%</span>' +
                                '</div>' +
                                '<div class="stk-progress-wrap"><div class="stk-progress-bar" id="stk-bar-' + ri + '" style="width:' + pct + '%;background:' + pColor + '"></div></div>' +
                            '</div>';
                        grid.appendChild(card);
                    });

                    // تعيين events على الـ steppers والـ inputs
                    grid.querySelectorAll('.stk-qty-minus').forEach(function(btn) {
                        btn.addEventListener('click', function() {
                            var inp = grid.querySelector('.stk-qty-input[data-row="'+btn.dataset.row+'"]');
                            if (!inp) return;
                            inp.value = Math.max(0, (parseInt(inp.value,10)||0) - 1);
                            onInputChange(inp);
                        });
                    });
                    grid.querySelectorAll('.stk-qty-plus').forEach(function(btn) {
                        btn.addEventListener('click', function() {
                            var inp = grid.querySelector('.stk-qty-input[data-row="'+btn.dataset.row+'"]');
                            if (!inp) return;
                            inp.value = (parseInt(inp.value,10)||0) + 1;
                            onInputChange(inp);
                        });
                    });
                    grid.querySelectorAll('.stk-qty-input').forEach(function(inp) {
                        inp.addEventListener('input', function() { onInputChange(inp); });
                    });

                    updateKpis(rows, alert);
                    syncVariantStock();
                }

                // ── تحديث card واحدة ──
                function onInputChange(inp) {
                    var qty   = Math.max(0, parseInt(inp.value, 10) || 0);
                    inp.value = qty;
                    var ri    = inp.dataset.row;
                    var alert = parseInt(document.getElementById('alert-threshold').value, 10) || 5;
                    var rows  = buildCombinations();
                    var key   = inp.dataset.size + '||' + inp.dataset.color;
                    stockState[key] = qty;

                    var allVals = Array.from(document.querySelectorAll('.stk-qty-input')).map(function(i){ return parseInt(i.value,10)||0; });
                    var mx  = Math.max(1, Math.max.apply(null, allVals));
                    var pct = Math.min(100, Math.round(qty / mx * 100));

                    var card = inp.closest('.stk-variant-card');
                    var pill = document.getElementById('stk-pill-' + ri);
                    var bar  = document.getElementById('stk-bar-'  + ri);
                    var pctEl= document.getElementById('stk-pct-'  + ri);

                    card.classList.remove('is-ok','is-low','is-zero');
                    if (pill) pill.classList.remove('stk-status-ok','stk-status-low','stk-status-zero');

                    var color, cls, pillCls, label;
                    if (qty === 0)        { color='#ef4444'; cls='is-zero'; pillCls='stk-status-zero'; label=LABEL_ZERO; }
                    else if (qty <= alert){ color='#f59e0b'; cls='is-low';  pillCls='stk-status-low';  label=LABEL_LOW;  }
                    else                  { color='#10b981'; cls='is-ok';   pillCls='stk-status-ok';   label=LABEL_OK;   }

                    card.classList.add(cls);
                    if (pill) { pill.classList.add(pillCls); pill.textContent = label; }
                    if (bar)  { bar.style.width = pct + '%'; bar.style.background = color; }
                    if (pctEl){ pctEl.textContent = pct + '%'; }

                    updateKpis(rows, alert);
                    syncVariantStock();
                }

                // ── fill all ──
                document.getElementById('fill-all-btn').addEventListener('click', function() {
                    var val = parseInt(document.getElementById('fill-all-qty').value, 10) || 0;
                    document.querySelectorAll('.stk-qty-input').forEach(function(inp) {
                        inp.value = val;
                        stockState[inp.dataset.size + '||' + inp.dataset.color] = val;
                        onInputChange(inp);
                    });
                });

                // ── zero all ──
                document.getElementById('zero-all-btn').addEventListener('click', function() {
                    if (!confirm(LABEL_ZERO_CONFIRM)) return;
                    document.querySelectorAll('.stk-qty-input').forEach(function(inp) {
                        inp.value = 0;
                        stockState[inp.dataset.size + '||' + inp.dataset.color] = 0;
                        onInputChange(inp);
                    });
                });

                // ── alert threshold change ──
                document.getElementById('alert-threshold').addEventListener('input', function() {
                    var alert = parseInt(this.value, 10) || 5;
                    document.getElementById('kpi-alert-val').textContent = alert;
                    document.querySelectorAll('.stk-qty-input').forEach(function(inp) { onInputChange(inp); });
                });

                // ── global stock input (no variants) ──
                document.getElementById('global-stock-input').addEventListener('input', function() {
                    updateKpis([], parseInt(document.getElementById('alert-threshold').value,10)||5);
                });

                // ── sync to hidden input ──
                function syncVariantStock() {
                    var inputs = document.querySelectorAll('.variant-stock-input');
                    var data = [];
                    inputs.forEach(function(inp) {
                        data.push({ size: inp.dataset.size||null, color: inp.dataset.color||null, qty: parseInt(inp.value,10)||0 });
                    });
                    var h = document.getElementById('variantStockInput');
                    if (h) h.value = JSON.stringify(data);
                }
                window.stkSyncVariantStock = syncVariantStock;

                // ── escape helper ──
                function esc(v) {
                    return String(v||'').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
                }

                // ── المراقب: يُعيد بناء الـ grid كلما تغيّر variantsState ──
                // يعمل عبر custom event يُطلقه كود المتغيرات
                document.addEventListener('variantsStateChanged', function() {
                    rebuildGrid();
                });

                // ── submit ──
                var form = document.getElementById('productForm');
                if (form) form.addEventListener('submit', syncVariantStock);

                // ── init ──
                rebuildGrid();

            })();
            </script>

            <!-- ===== MEDIA ===== -->
            <div class="tab-pane fade" id="tab-media">
                <div class="card mb-4">
                    <div class="card-body">
                        <label class="form-label"><?= __('products.featured_image') ?></label>
                        <div class="mb-3">
                            <img id="featuredImagePreview"
                                 src="<?= !empty($item['featured_image']) ? $item['featured_image'] : '' ?>"
                                 class="img-thumbnail <?= empty($item['featured_image']) ? 'd-none' : '' ?>"
                                 style="max-width:200px">
                        </div>
                        <input type="file" name="featured_image" id="featuredImageInput" class="form-control mb-4" accept="image/*">
                        <?php if ($productAiImageEnabled): ?>
                        <div class="mb-4">
                            <button type="button"
                                    class="btn btn-outline-primary"
                                    id="generateProductImagesBtn"
                                    data-bs-toggle="modal"
                                    data-bs-target="#generateProductImagesModal">
                                <i class="bi bi-image-alt me-1"></i><?= __('products.ai_generate_images', 'Generate Additional Images') ?>
                            </button>
                            <div class="form-text"><?= __('products.ai_generate_images_hint', 'Use the featured image, product name, and description to generate marketing images through Gemini.') ?></div>
                        </div>
                        <?php endif; ?>
                        <hr class="my-4">
                        <label class="form-label"><?= __('products.images') ?></label>
                        <div class="row g-3 mb-3" id="galleryPreview">
                            <?php if (!empty($item['images']) && is_array($item['images'])): ?>
                                <?php foreach ($item['images'] as $img): ?>
                                    <div class="col-md-3 gallery-item" data-type="existing" data-image="<?= htmlspecialchars($img) ?>">
                                        <div class="position-relative border rounded p-2 text-center">
                                            <img src="<?= $img ?>" class="img-fluid mb-2">
                                            <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 remove-gallery-image">
                                                <i class="bi bi-x-lg"></i>
                                            </button>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <input type="file" id="galleryInput" name="images[]" class="form-control" multiple accept="image/*">
                        <div id="generatedImagesHidden"></div>
                        <div id="discardGeneratedImagesHidden"></div>
                    </div>
                </div>
            </div>

            <!-- ===== PAGE SETTINGS (toggles — untouched) ===== -->
            <div class="tab-pane fade" id="tab-page">
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card mb-4">
                            <div class="card-header bg-white d-flex align-items-center justify-content-between">
                                <strong><i class="bi bi-sliders2-vertical me-1"></i><?= __('sections.settings') ?></strong>
                                <span class="text-muted small"><?= __('sections.settings_hint') ?></span>
                            </div>
                            <div class="card-body">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" role="switch" id="toggle_sticky_buy">
                                    <label class="form-check-label fw-semibold" for="toggle_sticky_buy"><?= __('sections.sticky_buy') ?></label>
                                    <div class="text-muted small"><?= __('sections.sticky_buy_help') ?></div>
                                </div>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" role="switch" id="toggle_whatsapp">
                                    <label class="form-check-label fw-semibold" for="toggle_whatsapp"><?= __('sections.whatsapp') ?></label>
                                    <div class="text-muted small"><?= __('sections.whatsapp_help') ?></div>
                                </div>
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" role="switch" id="toggle_reviews">
                                    <label class="form-check-label fw-semibold" for="toggle_reviews"><?= __('sections.reviews') ?></label>
                                    <div class="text-muted small"><?= __('sections.reviews_help') ?></div>
                                </div>
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input" type="checkbox" role="switch" id="toggle_countdown">
                                    <label class="form-check-label fw-semibold" for="toggle_countdown"><?= __('sections.countdown') ?></label>
                                    <div class="text-muted small"><?= __('sections.countdown_help') ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <div class="card mb-4">
                            <div class="card-header bg-white d-flex justify-content-between align-items-center gap-2 flex-wrap">
                                <strong><i class="bi bi-search-heart me-1"></i><?= __('products.seo_share_settings', 'SEO & Share Preview') ?></strong>
                                <?php if ($anyAiEnabled): ?>
                                    <button type="button"
                                            class="btn btn-outline-primary btn-sm d-inline-flex align-items-center gap-2"
                                            id="ai-seo-generate-btn"
                                            data-label-idle="<?= __('products.generate_seo_ai', 'Generate SEO with AI') ?>"
                                            data-label-loading="<?= __('ai.generating', 'Generating...') ?>"
                                            data-error-missing-title="<?= __('ai.error.missing_title', 'Title is required') ?>"
                                            data-error-csrf="<?= __('ai.error.csrf', 'Security error') ?>"
                                            data-error-title="<?= __('ai.error', 'Error') ?>">
                                        <i class="bi bi-stars"></i>
                                        <span><?= __('products.generate_seo_ai', 'Generate SEO with AI') ?></span>
                                    </button>
                                <?php endif; ?>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label"><?= __('seo.meta_title', 'Meta Title') ?></label>
                                    <input type="text" name="meta_title" id="seo_meta_title" data-seo-field="meta_title" class="form-control" maxlength="255" value="">
                                    <div class="form-text"><?= __('products.meta_title_help', 'Used for the browser title and search engines. Leave empty to use the product name.') ?></div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label"><?= __('seo.meta_description', 'Meta Description') ?></label>
                                    <textarea name="meta_description" id="seo_meta_description" data-seo-field="meta_description" class="form-control" rows="3" maxlength="320"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label"><?= __('products.og_title', 'Open Graph Title') ?></label>
                                    <input type="text" name="og_title" id="seo_og_title" data-seo-field="og_title" class="form-control" maxlength="255" value="">
                                    <div class="form-text"><?= __('products.og_title_help', 'Optional custom title for Facebook, WhatsApp and other social platforms.') ?></div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label"><?= __('products.og_description', 'Open Graph Description') ?></label>
                                    <textarea name="og_description" id="seo_og_description" data-seo-field="og_description" class="form-control" rows="3" maxlength="320"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label"><?= __('products.og_image', 'Share Image URL') ?></label>
                                    <input type="text" name="og_image" id="seo_og_image" data-seo-field="og_image" class="form-control" placeholder="/uploads/products/share-image.jpg" value="">
                                    <div class="form-text"><?= __('products.og_image_help', 'Optional dedicated image for link previews. Leave empty to use the featured image.') ?></div>
                                </div>
                                <hr>
                                <div class="mb-3">
                                    <label class="form-label"><?= __('products.schema_brand', 'Brand') ?></label>
                                    <input type="text" name="schema_brand" id="seo_schema_brand" data-seo-field="schema_brand" class="form-control" maxlength="190" value="">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label"><?= __('products.schema_gtin', 'GTIN / Barcode') ?></label>
                                    <input type="text" name="schema_gtin" id="seo_schema_gtin" data-seo-field="schema_gtin" class="form-control" maxlength="100" value="">
                                </div>
                                <div class="mb-0">
                                    <label class="form-label"><?= __('products.schema_mpn', 'MPN') ?></label>
                                    <input type="text" name="schema_mpn" id="seo_schema_mpn" data-seo-field="schema_mpn" class="form-control" maxlength="100" value="">
                                </div>
                            </div>
                        </div>
                        <div class="card mb-4 border-0 shadow-sm">
                            <div class="card-body">
                                <div class="d-flex gap-2 align-items-start">
                                    <i class="bi bi-info-circle text-primary fs-5"></i>
                                    <div>
                                        <div class="fw-semibold mb-1"><?= __('sections.note_title') ?></div>
                                        <div class="text-muted small mb-0"><?= __('sections.note_body') ?></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card mb-4">
                            <div class="card-header bg-white">
                                <strong><?= __('products.payload_preview') ?></strong>
                            </div>
                            <div class="card-body">
                                <div class="text-muted small mb-2"><?= __('products.payload_preview_hint') ?></div>
                                <pre class="bg-light border rounded p-2 mb-0" style="max-height:220px;overflow:auto"><code id="payloadPreview"></code></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ===== OFFERS (CREATE) ===== -->
            <div class="tab-pane fade" id="tab-offers">
                <div class="card mb-4">
                    <div class="card-header fw-bold">
                        <i class="bi bi-tags-fill text-warning me-2"></i>
                        <?= __('products.offers_title','Quantity Offers & Pricing Tiers') ?>
                    </div>
                    <div class="card-body">
                        <div class="form-check form-switch mb-4">
                            <input class="form-check-input" type="checkbox" role="switch"
                                   id="offersEnabledC" onchange="offersCToggle()">
                            <label class="form-check-label fw-semibold" for="offersEnabledC">
                                <?= __('products.offers_enable','Enable offers for this product') ?>
                            </label>
                        </div>
                        <div id="offersCBody" style="display:none">
                            <div class="mb-4">
                                <label class="form-label fw-semibold"><?= __('products.offers_type','Offer Type') ?></label>
                                <div class="d-flex gap-3 flex-wrap">
                                    <label class="border rounded-3 p-3 d-flex gap-2 align-items-center" style="cursor:pointer;min-width:220px">
                                        <input type="radio" name="offers_type_ui_c" value="quantity_pricing" checked onchange="offersCTypeChange('quantity_pricing')">
                                        <div>
                                            <div class="fw-bold"><?= __('products.offer_qty_pricing','Quantity Pricing') ?></div>
                                            <div class="text-muted small"><?= __('products.offer_qty_pricing_hint','e.g. 1 unit = 10, 2 units = 18') ?></div>
                                        </div>
                                    </label>
                                    <label class="border rounded-3 p-3 d-flex gap-2 align-items-center" style="cursor:pointer;min-width:220px">
                                        <input type="radio" name="offers_type_ui_c" value="bundle_free" onchange="offersCTypeChange('bundle_free')">
                                        <div>
                                            <div class="fw-bold"><?= __('products.offer_bundle_free','Buy X Get Y Free') ?></div>
                                            <div class="text-muted small"><?= __('products.offer_bundle_free_hint','e.g. buy 2 get 1 free') ?></div>
                                        </div>
                                    </label>
                                </div>
                            </div>
                            <div id="offersCPanelQty">
                                <label class="form-label fw-semibold">
                                    <?= __('products.offer_tiers','Pricing Tiers') ?>
                                    <span class="text-muted small fw-normal ms-1"><?= __('products.offer_tiers_hint','Set total price per quantity') ?></span>
                                </label>
                                <div id="offersCTiersWrap" class="mb-3">
                                    <div class="offers-tier-row d-flex gap-2 align-items-center mb-2">
                                        <div class="input-group" style="max-width:320px">
                                            <span class="input-group-text" style="min-width:110px"><i class="bi bi-hash me-1"></i><?= __('products.offer_qty','Quantity') ?></span>
                                            <input type="number" class="form-control offers-tier-qty" min="1" placeholder="e.g. 2">
                                            <span class="input-group-text" style="min-width:90px"><i class="bi bi-cash me-1"></i><?= __('products.offer_price','Total') ?></span>
                                            <input type="number" class="form-control offers-tier-price" min="0" step="0.01" placeholder="e.g. 18">
                                        </div>
                                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="offersCTierRemove(this)"><i class="bi bi-trash"></i></button>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-outline-success btn-sm" onclick="offersCTierAdd()">
                                    <i class="bi bi-plus-circle me-1"></i><?= __('products.offer_add_tier','Add Tier') ?>
                                </button>
                            </div>
                            <div id="offersCPanelBundle" style="display:none">
                                <label class="form-label fw-semibold"><?= __('products.offer_bundle_config','Bundle Configuration') ?></label>
                                <div class="d-flex gap-3 align-items-center flex-wrap">
                                    <div class="input-group offers-bundle-field">
                                        <span class="input-group-text offers-bundle-label"><?= __('products.offer_buy','Buy') ?></span>
                                        <input type="number" id="offerCBuyInput" class="form-control" min="1" value="2" placeholder="2">
                                    </div>
                                    <div class="input-group offers-bundle-field">
                                        <span class="input-group-text offers-bundle-label"><?= __('products.offer_get_free','Get Free') ?></span>
                                        <input type="number" id="offerCFreeInput" class="form-control" min="1" value="1" placeholder="1">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" name="offers" id="offersCJsonInput" value="{}">
                    </div>
                </div>
            </div><!-- /tab-offers -->

        </div><!-- /tab-content -->

<style>
.offers-tier-row { flex-wrap: nowrap; }
.offers-tier-row .input-group { width: 320px; max-width: 320px; flex: 0 0 320px; }
.offers-tier-row .form-control { min-width: 80px; }
.offers-bundle-field { max-width: 260px; min-width: 260px; }
.offers-bundle-label { min-width: 130px; justify-content: center; }
</style>
<script>
function offersCToggle() {
    var en = document.getElementById('offersEnabledC').checked;
    document.getElementById('offersCBody').style.display = en ? '' : 'none';
    offersCSerialize();
}
function offersCTypeChange(type) {
    document.getElementById('offersCPanelQty').style.display    = type === 'quantity_pricing' ? '' : 'none';
    document.getElementById('offersCPanelBundle').style.display = type === 'bundle_free' ? '' : 'none';
    offersCSerialize();
}
function offersCTierAdd() {
    var wrap = document.getElementById('offersCTiersWrap');
    var div = document.createElement('div');
    div.className = 'offers-tier-row d-flex gap-2 align-items-center mb-2';
    div.innerHTML = '<div class="input-group" style="max-width:320px">'
        + '<span class="input-group-text" style="min-width:110px"><i class="bi bi-hash me-1"></i><?= __('products.offer_qty','Quantity') ?></span>'
        + '<input type="number" class="form-control offers-tier-qty" min="1" placeholder="e.g. 3">'
        + '<span class="input-group-text" style="min-width:90px"><i class="bi bi-cash me-1"></i><?= __('products.offer_price','Total') ?></span>'
        + '<input type="number" class="form-control offers-tier-price" min="0" step="0.01" placeholder="e.g. 21">'
        + '</div>'
        + '<button type="button" class="btn btn-outline-danger btn-sm" onclick="offersCTierRemove(this)"><i class="bi bi-trash"></i></button>';
    wrap.appendChild(div);
    div.querySelector('.offers-tier-qty').addEventListener('input', offersCSerialize);
    div.querySelector('.offers-tier-price').addEventListener('input', offersCSerialize);
    offersCSerialize();
}
function offersCTierRemove(btn) { btn.closest('.offers-tier-row').remove(); offersCSerialize(); }
function offersCSerialize() {
    var enabled = document.getElementById('offersEnabledC').checked;
    var type = document.querySelector('input[name="offers_type_ui_c"]:checked')?.value || 'quantity_pricing';
    var obj = { enabled: enabled, type: type };
    if (type === 'quantity_pricing') {
        var tiers = [];
        document.querySelectorAll('#offersCTiersWrap .offers-tier-row').forEach(function(row) {
            var qty   = parseFloat(row.querySelector('.offers-tier-qty').value);
            var price = parseFloat(row.querySelector('.offers-tier-price').value);
            if (!isNaN(qty) && qty > 0 && !isNaN(price) && price >= 0) tiers.push({qty:qty, price:price});
        });
        obj.tiers = tiers;
    } else {
        obj.buy  = parseInt(document.getElementById('offerCBuyInput').value, 10) || 2;
        obj.free = parseInt(document.getElementById('offerCFreeInput').value, 10) || 1;
    }
    document.getElementById('offersCJsonInput').value = JSON.stringify(obj);
}
document.querySelectorAll('#offersCTiersWrap .offers-tier-row').forEach(function(row) {
    row.querySelector('.offers-tier-qty').addEventListener('input', offersCSerialize);
    row.querySelector('.offers-tier-price').addEventListener('input', offersCSerialize);
});
document.getElementById('offerCBuyInput')?.addEventListener('input', offersCSerialize);
document.getElementById('offerCFreeInput')?.addEventListener('input', offersCSerialize);
</script>


        <input type="hidden" name="layout" id="layoutInput"
               value="<?= htmlspecialchars(
                   isset($item['layout']) && is_array($item['layout'])
                       ? json_encode($item['layout'], JSON_UNESCAPED_UNICODE)
                       : '{}',
                   ENT_QUOTES
               ) ?>">

    </form>
</div>

<!-- Section editor modal -->
<div class="modal fade" id="lpbSectionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="lpbModalTitle">Edit Section</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="lpbModalBody"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= __('actions.cancel', 'Cancel') ?></button>
                <button type="button" class="btn btn-primary" id="lpbModalSave"><?= __('actions.apply', 'Apply') ?></button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {

    const form           = document.getElementById('productForm');
    const variantsInput  = document.getElementById('variantsInput');
    const layoutInput    = document.getElementById('layoutInput');
    const payloadPreview = document.getElementById('payloadPreview');
    if (!form) return;

    // ── Variants ─────────────────────────────────────────────────────
    const variantsState   = { sizes: [], colors: [] };
    const sizeTypeClothes = document.getElementById('size_type_clothes');
    const sizeTypeShoes   = document.getElementById('size_type_shoes');
    const sizeSelect      = document.getElementById('sizeSelect');
    const sizesListEl     = document.getElementById('sizesList');
    const sizesCountEl    = document.getElementById('sizesCount');
    const colorPicker     = document.getElementById('colorPicker');
    const colorName       = document.getElementById('colorName');
    const colorsListEl    = document.getElementById('colorsList');
    const colorsCountEl   = document.getElementById('colorsCount');

    function setSizeOptions(type) {
        sizeSelect.innerHTML = '';
        if (type === 'shoes') {
            for (let n = 32; n <= 46; n++) { const o = document.createElement('option'); o.value = o.textContent = n; sizeSelect.appendChild(o); }
        } else {
            ['XS','S','M','L','XL','2XL','3XL'].forEach(s => { const o = document.createElement('option'); o.value = o.textContent = s; sizeSelect.appendChild(o); });
        }
    }

    function syncVariants() {
        variantsInput.value = JSON.stringify(variantsState);
        sizesCountEl.textContent  = variantsState.sizes.length;
        colorsCountEl.textContent = variantsState.colors.length;
        renderPreview();
        // إعلام تبويب المخزون بتغيير المتغيرات
        // يجب تحديث window.variantsState أولاً حتى يقرأه تبويب المخزون بشكل صحيح
        window.variantsState = variantsState;
        document.dispatchEvent(new CustomEvent('variantsStateChanged'));
    }

    function renderSizes() {
        sizesListEl.innerHTML = '';
        if (!variantsState.sizes.length) { sizesListEl.innerHTML = '<div class="text-muted small"><?= __("products.sizes_empty") ?></div>'; return; }
        variantsState.sizes.forEach((s,i) => {
            const el = document.createElement('span');
            el.className = 'badge bg-light text-dark border d-inline-flex align-items-center gap-2 px-2 py-2';
            el.innerHTML = `<span class="fw-semibold">${s.value}</span><span class="text-muted" style="font-size:11px">${s.type}</span><button type="button" class="btn btn-sm btn-outline-danger border-0 px-1 py-0"><i class="bi bi-x-lg"></i></button>`;
            el.querySelector('button').onclick = () => { variantsState.sizes.splice(i,1); renderSizes(); syncVariants(); };
            sizesListEl.appendChild(el);
        });
    }

    function renderColors() {
        colorsListEl.innerHTML = '';
        if (!variantsState.colors.length) { colorsListEl.innerHTML = '<div class="text-muted small"><?= __("products.colors_empty") ?></div>'; return; }
        variantsState.colors.forEach((c,i) => {
            const el = document.createElement('div');
            el.className = 'd-inline-flex align-items-center gap-2 border rounded-pill px-2 py-2';
            el.innerHTML = `<span class="rounded-circle border" style="width:18px;height:18px;background:${c.code}"></span><span class="fw-semibold">${c.name}</span><span class="text-muted" style="font-size:11px">${c.code}</span><button type="button" class="btn btn-sm btn-outline-danger border-0 px-1 py-0"><i class="bi bi-x-lg"></i></button>`;
            el.querySelector('button').onclick = () => { variantsState.colors.splice(i,1); renderColors(); syncVariants(); };
            colorsListEl.appendChild(el);
        });
    }

    sizeTypeClothes.addEventListener('change', () => { if (sizeTypeClothes.checked) setSizeOptions('clothes'); });
    sizeTypeShoes.addEventListener('change',   () => { if (sizeTypeShoes.checked)   setSizeOptions('shoes');   });

    document.getElementById('addSizeBtn').addEventListener('click', () => {
        const type = sizeTypeShoes.checked ? 'shoes' : 'clothes';
        const value = sizeSelect.value;
        if (variantsState.sizes.some(s => s.type === type && s.value === value)) return;
        variantsState.sizes.push({ type, value });
        renderSizes(); syncVariants();
    });

    document.getElementById('addColorBtn').addEventListener('click', () => {
        const name = colorName.value.trim();
        const code = colorPicker.value;
        if (!name || variantsState.colors.some(c => c.name.toLowerCase() === name.toLowerCase())) return;
        variantsState.colors.push({ name, code });
        colorName.value = '';
        renderColors(); syncVariants();
    });

    if (window.ITEM_DATA && window.ITEM_DATA.variants) {
        const v = window.ITEM_DATA.variants;
        if (Array.isArray(v.sizes))  variantsState.sizes  = v.sizes;
        if (Array.isArray(v.colors)) variantsState.colors = v.colors;
    }
    if (variantsState.sizes.length && variantsState.sizes[0].type === 'shoes') { sizeTypeShoes.checked = true; setSizeOptions('shoes'); }
    else { sizeTypeClothes.checked = true; setSizeOptions('clothes'); }
    renderSizes(); renderColors(); syncVariants();

    // ── Layout toggles ────────────────────────────────────────────────
    const toggleSticky    = document.getElementById('toggle_sticky_buy');
    const toggleWhatsapp  = document.getElementById('toggle_whatsapp');
    const toggleReviews   = document.getElementById('toggle_reviews');
    const toggleCountdown = document.getElementById('toggle_countdown');

    function syncLayout() {
        // اقرأ القيمة الحالية (قد تحتوي sections من البانيّ)
        let obj = {};
        try { obj = JSON.parse(layoutInput.value || '{}'); } catch(e) { obj = {}; }
        // أضف/حدّث toggles فقط — لا تمسح باقي البيانات
        obj.toggles = {
            sticky_buy: toggleSticky.checked ? 1 : 0,
            whatsapp:   toggleWhatsapp.checked ? 1 : 0,
            reviews:    toggleReviews.checked ? 1 : 0,
            countdown:  toggleCountdown.checked ? 1 : 0
        };
        layoutInput.value = JSON.stringify(obj);
        renderPreview();
    }

    if (window.ITEM_DATA && window.ITEM_DATA.layout && window.ITEM_DATA.layout.toggles) {
        const t = window.ITEM_DATA.layout.toggles;
        toggleSticky.checked    = !!t.sticky_buy;
        toggleWhatsapp.checked  = !!t.whatsapp;
        toggleReviews.checked   = !!t.reviews;
        toggleCountdown.checked = !!t.countdown;
    }
    [toggleSticky, toggleWhatsapp, toggleReviews, toggleCountdown].forEach(el => el.addEventListener('change', syncLayout));
    syncLayout();

    function renderPreview() {
        if (!payloadPreview) return;
        let layoutObj = {};
        try { layoutObj = JSON.parse(layoutInput.value || '{}'); } catch(e) {}
        payloadPreview.textContent = JSON.stringify({ variants: variantsState, layout: layoutObj }, null, 2);
    }

    form.addEventListener('submit', function () {
        syncVariants();
        // 1. أولاً اكتب الـ sections من البانيّ
        if (window.lpbSyncToLayout) window.lpbSyncToLayout();
        // 2. ثم أضف الـ toggles فوق القيمة الموجودة (لا تمسح sections)
        syncLayout();
    });

});
</script>

<script>
(function(){
    if (typeof window.ITEM_DATA === 'undefined') {
        window.ITEM_DATA = <?= json_encode($item ?? null, JSON_UNESCAPED_UNICODE) ?>;
    }
    const d = window.ITEM_DATA;
    if (!d) return;

    document.querySelectorAll('[name]').forEach(el => {
        const name = el.getAttribute('name');
        if (!name || !(name in d)) return;
        if (el.type === 'checkbox') { el.checked = !!d[name]; }
        else if (el.type === 'radio') { if (el.value == d[name]) el.checked = true; }
        else if (el.type !== 'file') { el.value = d[name] ?? ''; }
    });

    if (Array.isArray(d.categories)) {
        d.categories.forEach(id => {
            const cb = document.querySelector('input[name="categories[]"][value="'+id+'"]');
            if (cb) cb.checked = true;
        });
    }

    if (d.variants) {
        const vi = document.getElementById('variantsInput');
        if (vi) vi.value = JSON.stringify(d.variants);
    }
})();
</script>

<script>
(function () {
    const form    = document.getElementById('productForm');
    const input   = document.getElementById('galleryInput');
    const preview = document.getElementById('galleryPreview');
    if (!form || !input || !preview) return;

    const newFilesMap = new Map();
    const generatedHiddenWrap = document.getElementById('generatedImagesHidden');
    const discardHiddenWrap = document.getElementById('discardGeneratedImagesHidden');
    const featuredInput = document.getElementById('featuredImageInput');
    const featuredPreview = document.getElementById('featuredImagePreview');
    const titleInput = document.querySelector('input[name="title"]');
    const shortDescriptionInput = document.querySelector('textarea[name="short_description"]');
    const descriptionInput = document.getElementById('desc-html-textarea') || document.getElementById('desc-textarea') || document.querySelector('textarea[name="description"]');
    const csrfInput = document.querySelector('input[name="_csrf"]');
    const modalEl = document.getElementById('generateProductImagesModal');
    const generateBtn = document.getElementById('generateProductImagesBtn');
    const generateConfirmBtn = document.getElementById('aiGenerateImagesConfirmBtn');
    const loadingText = document.getElementById('aiGenerateImagesLoadingText');
    const sourcePreview = document.getElementById('aiImageSourcePreview');
    const sourceEmpty = document.getElementById('aiImageSourceEmpty');
    const productNameField = document.getElementById('aiImageProductName');
    const productDescriptionField = document.getElementById('aiImageProductDescription');
    const alertBox = document.getElementById('aiImageGenerationAlert');
    const imageTypeInputs = modalEl ? Array.from(modalEl.querySelectorAll('.ai-image-type')) : [];

    function makeUID() {
        return (window.crypto && window.crypto.randomUUID) ? window.crypto.randomUUID() : 'uid_' + Date.now() + '_' + Math.random().toString(16).slice(2);
    }
    function syncFiles() {
        const dt = new DataTransfer();
        newFilesMap.forEach(file => dt.items.add(file));
        input.files = dt.files;
    }
    function showGenerationAlert(type, message) {
        if (!alertBox) return;
        alertBox.className = 'alert alert-' + type;
        alertBox.textContent = message;
        alertBox.classList.remove('d-none');
    }
    function clearGenerationAlert() {
        if (!alertBox) return;
        alertBox.className = 'alert d-none';
        alertBox.textContent = '';
    }
    function setGenerationBusy(isBusy, text) {
        if (generateConfirmBtn) {
            generateConfirmBtn.disabled = isBusy;
            generateConfirmBtn.querySelector('span').textContent = isBusy
                ? <?= json_encode(__('products.ai_generating_images', 'Generating images...')) ?>
                : <?= json_encode(__('products.ai_generate_images_action', 'Generate marketing images')) ?>;
        }
        if (generateBtn) generateBtn.disabled = isBusy;
        if (loadingText) loadingText.textContent = isBusy ? (text || <?= json_encode(__('products.ai_generation_in_progress', 'Gemini is generating new product images...')) ?>) : '';
    }
    function getCurrentSourcePreview() {
        if (featuredInput && featuredInput.files && featuredInput.files[0]) {
            return URL.createObjectURL(featuredInput.files[0]);
        }
        if (featuredPreview && featuredPreview.src && !featuredPreview.classList.contains('d-none')) {
            return featuredPreview.src;
        }
        return '';
    }
    function refreshGenerationModal() {
        if (!modalEl) return;
        const source = getCurrentSourcePreview();
        if (sourcePreview) {
            if (source) {
                sourcePreview.src = source;
                sourcePreview.classList.remove('d-none');
                if (sourceEmpty) sourceEmpty.classList.add('d-none');
            } else {
                sourcePreview.src = '';
                sourcePreview.classList.add('d-none');
                if (sourceEmpty) sourceEmpty.classList.remove('d-none');
            }
        }
        if (productNameField) productNameField.value = titleInput ? titleInput.value.trim() : '';
        if (productDescriptionField) {
            const shortPart = shortDescriptionInput ? shortDescriptionInput.value.trim() : '';
            const longPart = descriptionInput ? descriptionInput.value.trim() : '';
            productDescriptionField.value = [shortPart, longPart].filter(Boolean).join("\n\n");
        }
        clearGenerationAlert();
    }
    function createHiddenInput(name, value, uid) {
        const inputEl = document.createElement('input');
        inputEl.type = 'hidden';
        inputEl.name = name;
        inputEl.value = value;
        inputEl.dataset.generatedUid = uid;
        return inputEl;
    }
    function appendGeneratedImage(image) {
        if (!generatedHiddenWrap) return;
        const uid = makeUID();
        const col = document.createElement('div');
        col.className = 'col-md-3 gallery-item';
        col.dataset.type = 'generated';
        col.dataset.uid = uid;
        col.dataset.image = image.path;
        col.innerHTML = `<div class="position-relative border rounded p-2 text-center">
            <img src="${image.path}" class="img-fluid mb-2">
            <div class="small fw-semibold text-truncate mb-1">${image.label || ''}</div>
            <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 remove-gallery-image"><i class="bi bi-x-lg"></i></button>
        </div>`;
        preview.appendChild(col);
        generatedHiddenWrap.appendChild(createHiddenInput('generated_images[]', image.path, uid));
    }

    input.addEventListener('change', function () {
        Array.from(input.files || []).forEach(file => {
            if (!file || !file.type.startsWith('image/')) return;
            const uid = makeUID();
            newFilesMap.set(uid, file);
            const reader = new FileReader();
            reader.onload = e => {
                const col = document.createElement('div');
                col.className = 'col-md-3 gallery-item';
                col.dataset.type = 'new';
                col.dataset.uid  = uid;
                col.innerHTML = `<div class="position-relative border rounded p-2 text-center"><img src="${e.target.result}" class="img-fluid mb-2"><button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 remove-gallery-image"><i class="bi bi-x-lg"></i></button></div>`;
                preview.appendChild(col);
            };
            reader.readAsDataURL(file);
        });
        syncFiles();
    });

    preview.addEventListener('click', function (e) {
        const btn = e.target.closest('.remove-gallery-image');
        if (!btn) return;
        const item = btn.closest('.gallery-item');
        if (!item) return;
        if (item.dataset.type === 'existing' && item.dataset.image) {
            const h = document.createElement('input');
            h.type = 'hidden'; h.name = 'removed_images[]'; h.value = item.dataset.image;
            form.appendChild(h);
        }
        if (item.dataset.type === 'new' && item.dataset.uid) {
            newFilesMap.delete(item.dataset.uid); syncFiles();
        }
        if (item.dataset.type === 'generated' && item.dataset.uid) {
            if (generatedHiddenWrap) {
                generatedHiddenWrap.querySelectorAll('input[name="generated_images[]"]').forEach(function (hidden) {
                    if (hidden.dataset.generatedUid === item.dataset.uid) hidden.remove();
                });
            }
            if (discardHiddenWrap && item.dataset.image) {
                discardHiddenWrap.appendChild(createHiddenInput('discard_generated_images[]', item.dataset.image, item.dataset.uid));
            }
        }
        item.remove();
    });

    if (modalEl) {
        modalEl.addEventListener('show.bs.modal', refreshGenerationModal);
    }

    if (featuredInput) {
        featuredInput.addEventListener('change', function () {
            if (modalEl && modalEl.classList.contains('show')) {
                setTimeout(refreshGenerationModal, 50);
            }
        });
    }

    if (generateConfirmBtn) {
        generateConfirmBtn.addEventListener('click', async function () {
            clearGenerationAlert();

            const title = titleInput ? titleInput.value.trim() : '';
            if (!title) {
                showGenerationAlert('danger', <?= json_encode(__('products.ai_images_name_required', 'Product name is required before generating images.')) ?>);
                return;
            }

            if (!featuredInput || !(featuredInput.files && featuredInput.files[0])) {
                showGenerationAlert('danger', <?= json_encode(__('products.ai_images_source_required_create', 'Choose a featured image in the form before generating additional images.')) ?>);
                return;
            }

            const selectedTypes = imageTypeInputs.filter(function (inputEl) { return inputEl.checked; }).map(function (inputEl) { return inputEl.value; });
            if (!selectedTypes.length) {
                showGenerationAlert('danger', <?= json_encode(__('products.ai_images_type_required', 'Select at least one image type.')) ?>);
                return;
            }

            const formData = new FormData();
            formData.append('_csrf', csrfInput ? csrfInput.value : '');
            formData.append('product_name', title);
            formData.append('product_description', productDescriptionField ? productDescriptionField.value : '');
            formData.append('source_image', featuredInput.files[0]);
            selectedTypes.forEach(function (type) { formData.append('requested_image_types[]', type); });

            setGenerationBusy(true);

            try {
                const response = await fetch('/admin/ai/generate-product-images', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-Token': csrfInput ? csrfInput.value : ''
                    }
                });

                const payload = await response.json();
                if (!response.ok || !payload.success) {
                    throw new Error(payload.message || <?= json_encode(__('ai.error', 'Error')) ?>);
                }

                (payload.images || []).forEach(appendGeneratedImage);
                showGenerationAlert('success', payload.message || <?= json_encode(__('products.ai_images_generated_success', 'Additional images were generated successfully.')) ?>);
            } catch (error) {
                showGenerationAlert('danger', error.message || <?= json_encode(__('products.ai_images_generation_failed', 'Unable to generate product images right now.')) ?>);
            } finally {
                setGenerationBusy(false);
            }
        });
    }
})();
</script>

<script>
(function () {
    const form = document.getElementById('productForm');
    const payloadInput = document.getElementById('seoSharePayload');
    if (!form || !payloadInput) return;

    const fieldNames = [
        'meta_title',
        'meta_description',
        'og_title',
        'og_description',
        'og_image',
        'schema_brand',
        'schema_gtin',
        'schema_mpn'
    ];

    function syncSeoPayload() {
        const payload = {};
        fieldNames.forEach(function (name) {
            const field = document.querySelector('[data-seo-field="' + name + '"]');
            if (!field) return;
            payload[name] = typeof field.value === 'string' ? field.value.trim() : '';
        });
        payloadInput.value = JSON.stringify(payload);
    }

    fieldNames.forEach(function (name) {
        const field = document.querySelector('[data-seo-field="' + name + '"]');
        if (!field) return;
        field.addEventListener('input', syncSeoPayload);
        field.addEventListener('change', syncSeoPayload);
    });

    form.addEventListener('submit', syncSeoPayload);
    syncSeoPayload();
})();
</script>

<script>
(function () {
    const btn = document.getElementById('ai-generate-btn');
    if (!btn) return;

    const titleInput = document.querySelector('input[name="title"]');
    const shortDesc  = document.querySelector('textarea[name="short_description"]');
    const desc       = document.getElementById('desc-textarea') || document.getElementById('desc-html-textarea');
    const csrfInput  = document.querySelector('input[name="_csrf"]');

    const LABEL_IDLE    = btn.dataset.labelIdle    || 'Generate with AI';
    const LABEL_LOADING = btn.dataset.labelLoading || 'Generating...';
    const ERROR_MISSING = btn.dataset.errorMissingTitle || 'Please enter a title';
    const ERROR_CSRF    = btn.dataset.errorCsrf || 'Security error';
    const ERROR_GENERIC = btn.dataset.errorTitle || 'Error';

    btn.addEventListener('click', async function () {
        const title = titleInput.value.trim();
        if (!title) { alert(ERROR_MISSING); return; }
        if (!csrfInput || !csrfInput.value) { alert(ERROR_CSRF); return; }

        btn.disabled = true;
        btn.innerHTML = '<i class="bi bi-stars"></i> ' + LABEL_LOADING;
        if (shortDesc) shortDesc.value = '';
        if (desc)      desc.value      = '';

        try {
            const fd = new FormData();
            fd.append('title', title);
            fd.append('_csrf', csrfInput.value);

            const res = await fetch('/admin/ai/generate-product-description', {
                method: 'POST',
                body: fd,
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-Token': csrfInput.value
                }
            });

            const contentType = (res.headers.get('content-type') || '').toLowerCase();
            const rawResponse = await res.text();
            let json = null;

            if (contentType.includes('application/json')) {
                try {
                    json = JSON.parse(rawResponse);
                } catch (parseError) {
                    throw new Error(ERROR_GENERIC);
                }
            }

            if (!res.ok) {
                const message = json && json.message ? json.message : (rawResponse ? rawResponse.trim() : ERROR_GENERIC);
                throw new Error(message || ERROR_GENERIC);
            }

            if (!json || !json.success) {
                throw new Error((json && json.message) ? json.message : ERROR_GENERIC);
            }

            if (shortDesc) shortDesc.value = json.short || '';
            if (desc)      desc.value      = json.full  || '';
        } catch(e) {
            alert(e.message || ERROR_GENERIC);
        } finally {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-stars"></i> ' + LABEL_IDLE;
        }
    });
})();
</script>

<script>
(function () {
    const btn = document.getElementById('ai-seo-generate-btn');
    if (!btn) return;

    const csrfInput  = document.querySelector('input[name="_csrf"]');
    const titleInput = document.querySelector('input[name="title"]');
    const shortInput = document.querySelector('textarea[name="short_description"]');
    const descInput  = document.querySelector('#desc-html-textarea') || document.querySelector('#desc-textarea') || document.querySelector('textarea[name="description"]');
    const priceInput = document.querySelector('input[name="price"]');
    const currencyInput = document.querySelector('input[name="currency"]');
    const featuredImageInput = document.querySelector('input[name="featured_image"]');

    const fieldMap = {
        meta_title: document.querySelector('[data-seo-field="meta_title"]'),
        meta_description: document.querySelector('[data-seo-field="meta_description"]'),
        og_title: document.querySelector('[data-seo-field="og_title"]'),
        og_description: document.querySelector('[data-seo-field="og_description"]'),
        og_image: document.querySelector('[data-seo-field="og_image"]'),
        schema_brand: document.querySelector('[data-seo-field="schema_brand"]'),
        schema_gtin: document.querySelector('[data-seo-field="schema_gtin"]'),
        schema_mpn: document.querySelector('[data-seo-field="schema_mpn"]')
    };

    const LABEL_IDLE    = btn.dataset.labelIdle || 'Generate SEO with AI';
    const LABEL_LOADING = btn.dataset.labelLoading || 'Generating...';
    const ERROR_MISSING = btn.dataset.errorMissingTitle || 'Title is required';
    const ERROR_CSRF    = btn.dataset.errorCsrf || 'Security error';
    const ERROR_GENERIC = btn.dataset.errorTitle || 'Error';

    function getSelectedCategoryLabel() {
        const checked = document.querySelector('input[name="categories[]"]:checked');
        if (!checked) return '';
        const label = checked.closest('label');
        return label ? label.textContent.trim() : '';
    }

    function setButtonLoading(isLoading) {
        btn.disabled = isLoading;
        btn.innerHTML = isLoading
            ? '<i class="bi bi-stars"></i><span>' + LABEL_LOADING + '</span>'
            : '<i class="bi bi-stars"></i><span>' + LABEL_IDLE + '</span>';
    }

    btn.addEventListener('click', async function () {
        const title = (titleInput && titleInput.value || '').trim();
        if (!title) { alert(ERROR_MISSING); return; }
        if (!csrfInput || !csrfInput.value) { alert(ERROR_CSRF); return; }

        setButtonLoading(true);

        try {
            const fd = new FormData();
            fd.append('_csrf', csrfInput.value);
            fd.append('title', title);
            fd.append('short_description', shortInput ? shortInput.value : '');
            fd.append('description', descInput ? descInput.value : '');
            fd.append('price', priceInput ? priceInput.value : '');
            fd.append('currency', currencyInput ? currencyInput.value : '');
            fd.append('category', getSelectedCategoryLabel());
            fd.append('featured_image', featuredImageInput ? featuredImageInput.value : '');

            const res = await fetch('/admin/ai/generate-product-seo', {
                method: 'POST',
                body: fd,
                headers: { 'Accept': 'application/json' }
            });

            const text = await res.text();
            let json = null;
            try { json = JSON.parse(text); } catch (e) { throw new Error(ERROR_GENERIC); }
            if (!json.success || !json.data) throw new Error(json.message || ERROR_GENERIC);

            Object.keys(fieldMap).forEach(function (key) {
                if (fieldMap[key] && Object.prototype.hasOwnProperty.call(json.data, key)) {
                    fieldMap[key].value = json.data[key] || '';
                }
            });

            const payloadInput = document.getElementById('seoSharePayload');
            if (payloadInput) {
                const payload = {};
                Object.keys(fieldMap).forEach(function (key) {
                    payload[key] = fieldMap[key] && typeof fieldMap[key].value === 'string'
                        ? fieldMap[key].value.trim()
                        : '';
                });
                payloadInput.value = JSON.stringify(payload);
            }
        } catch (e) {
            alert(e.message || ERROR_GENERIC);
        } finally {
            setButtonLoading(false);
        }
    });
})();
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const featuredInput   = document.getElementById('featuredImageInput');
    const featuredPreview = document.getElementById('featuredImagePreview');
    if (!featuredInput || !featuredPreview) return;

    featuredInput.addEventListener('change', function () {
        const file = featuredInput.files && featuredInput.files[0];
        if (!file || !file.type.startsWith('image/')) {
            featuredPreview.src = ''; featuredPreview.classList.add('d-none'); return;
        }
        const reader = new FileReader();
        reader.onload = e => { featuredPreview.src = e.target.result; featuredPreview.classList.remove('d-none'); };
        reader.readAsDataURL(file);
    });
});
</script>



<script>
(function () {
'use strict';

var radioText = document.getElementById('desc-mode-text');
var radioHtml = document.getElementById('desc-mode-html');
var textPanel = document.getElementById('desc-text-panel');
var htmlPanel = document.getElementById('desc-html-panel');
var textTA    = document.getElementById('desc-textarea');
var htmlTA    = document.getElementById('desc-html-textarea');

if (!radioText || !radioHtml || !textPanel || !htmlPanel) return;

function switchMode(mode) {
    if (mode === 'html') {
        if (textTA && htmlTA && textTA.value.trim()) htmlTA.value = textTA.value;
        if (textTA) textTA.name = '';
        if (htmlTA) htmlTA.name = 'description';
        textPanel.style.display = 'none';
        htmlPanel.style.display = '';
    } else {
        if (htmlTA && textTA && htmlTA.value.trim()) textTA.value = htmlTA.value;
        if (htmlTA) htmlTA.name = '';
        if (textTA) textTA.name = 'description';
        htmlPanel.style.display = 'none';
        textPanel.style.display = '';
    }
}

radioText.addEventListener('change', function () { if (this.checked) switchMode('text'); });
radioHtml.addEventListener('change', function () { if (this.checked) switchMode('html'); });

if (!window.AI_ASSISTANT_ENABLED) return;

var chatBody   = document.getElementById('claude-chat-body');
var chatEmpty  = document.getElementById('claude-chat-empty');
var msgInput   = document.getElementById('claude-msg-input');
var sendBtn    = document.getElementById('claude-send-btn');
var clearBtn   = document.getElementById('claude-clear-btn');
var applyBtn   = document.getElementById('claude-apply-btn');
var toggleBtn  = document.getElementById('claude-chat-toggle');
var imgInput   = document.getElementById('claude-img-input');
var imgPreview = document.getElementById('claude-img-preview');
var csrfInput  = document.querySelector('input[name="_csrf"]');

var history      = [];
var lastResponse = '';
var attachedImgs = [];

if (imgInput) {
    imgInput.addEventListener('change', function () {
        Array.from(this.files || []).forEach(function (file) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var b64 = e.target.result.split(',')[1];
                attachedImgs.push({ base64: b64, mediaType: file.type, name: file.name });
                var thumb = document.createElement('div');
                thumb.className = 'position-relative d-inline-block';
                thumb.innerHTML = '<img src="' + e.target.result + '" style="height:36px;width:36px;object-fit:cover;border-radius:4px;border:1px solid #dee2e6">'
                    + '<button type="button" class="btn-close position-absolute top-0 end-0" style="font-size:8px;background-color:white;" data-idx="' + (attachedImgs.length-1) + '"></button>';
                thumb.querySelector('.btn-close').addEventListener('click', function () {
                    attachedImgs.splice(parseInt(this.dataset.idx), 1);
                    thumb.remove();
                });
                imgPreview.appendChild(thumb);
            };
            reader.readAsDataURL(file);
        });
        imgInput.value = '';
    });
}

document.querySelectorAll('.claude-tpl').forEach(function (btn) {
    btn.addEventListener('click', function () {
        if (msgInput) msgInput.value = btn.dataset.msg;
        sendMessage();
    });
});

if (toggleBtn) {
    toggleBtn.addEventListener('click', function () {
        var isOpen = chatBody.style.display !== 'none';
        chatBody.style.display = isOpen ? 'none' : 'flex';
        toggleBtn.querySelector('i').className = isOpen ? 'bi bi-chevron-down' : 'bi bi-chevron-up';
    });
}

if (clearBtn) {
    clearBtn.addEventListener('click', function () {
        history = []; lastResponse = ''; attachedImgs = [];
        if (imgPreview) imgPreview.innerHTML = '';
        chatBody.innerHTML = '<div class="text-muted small text-center py-2">اسأل كلود لكتابة وصف HTML للمنتج</div>';
        if (applyBtn) applyBtn.style.display = 'none';
    });
}

if (applyBtn) {
    applyBtn.addEventListener('click', function () {
        if (lastResponse && htmlTA) {
            htmlTA.value = normalizeAiHtml(lastResponse);
            if (!radioHtml.checked) { radioHtml.checked = true; switchMode('html'); }
        }
    });
}

if (msgInput) {
    msgInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); sendMessage(); }
    });
}
if (sendBtn) sendBtn.addEventListener('click', sendMessage);

function appendBubble(role, text, isLoading) {
    if (chatEmpty) chatEmpty.style.display = 'none';
    var d = document.createElement('div');
    d.style.cssText = role === 'user'
        ? 'align-self:flex-end;background:#0d6efd;color:#fff;border-radius:12px 12px 2px 12px;padding:8px 12px;max-width:85%;font-size:13px;white-space:pre-wrap'
        : 'align-self:flex-start;background:#f1f3f5;color:#212529;border-radius:12px 12px 12px 2px;padding:8px 12px;max-width:90%;font-size:13px;white-space:pre-wrap';
    d.textContent = isLoading ? '...' : text;
    if (isLoading) d.id = 'claude-loading-bubble';
    chatBody.appendChild(d);
    chatBody.scrollTop = chatBody.scrollHeight;
    return d;
}

function normalizeAiHtml(raw) {
    raw = (raw || '').trim();
    var fence = raw.match(/```(?:html)?\s*([\s\S]+?)\s*```/i);
    if (fence) raw = fence[1].trim();
    var startMatch = raw.match(/(?:<!DOCTYPE\s+html[^>]*>|<html\b)/i);
    if (startMatch && typeof startMatch.index === 'number') raw = raw.slice(startMatch.index).trim();
    var endMatch = raw.match(/<\/html\s*>/i);
    if (endMatch && typeof endMatch.index === 'number') raw = raw.slice(0, endMatch.index + endMatch[0].length).trim();
    if (!/<html\b/i.test(raw)) {
        raw = '<!DOCTYPE html>\n<html lang="ar" dir="rtl">\n<head>\n<meta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n</head>\n<body>\n' + raw + '\n</body>\n</html>';
    } else if (!/<!DOCTYPE\s+html/i.test(raw)) {
        raw = '<!DOCTYPE html>\n' + raw;
    }
    if (!/<\/html\s*>$/i.test(raw)) raw += '\n</html>';
    return raw.trim();
}

async function sendMessage() {
    var titleEl = document.querySelector(window.PRODUCT_TITLE_EL || 'input[name="title"]');
    var title   = titleEl ? titleEl.value.trim() : '';
    var msg     = msgInput ? msgInput.value.trim() : '';
    if (!msg) return;

    var userContent = [];
    attachedImgs.forEach(function (img) {
        userContent.push({ type: 'image', source: { type: 'base64', media_type: img.mediaType, data: img.base64 } });
    });
    var fullMsg = title ? 'اسم المنتج: ' + title + '\n\n' + msg : msg;
    userContent.push({ type: 'text', text: fullMsg });
    history.push({ role: 'user', content: userContent });
    appendBubble('user', msg);
    attachedImgs = [];
    if (imgPreview) imgPreview.innerHTML = '';
    if (msgInput) msgInput.value = '';

    var loadBubble = appendBubble('assistant', '', true);
    if (sendBtn) sendBtn.disabled = true;

    try {
        var csrfToken = csrfInput ? csrfInput.value.trim() : '';
        if (!csrfToken) throw new Error('انتهت صلاحية رمز الحماية. أعد تحميل الصفحة ثم حاول مرة أخرى.');
        var dialectLine = window.AI_ASSISTANT_DIALECT_LINE || 'اكتب باللغة العربية الفصحى';
        var response = await fetch('/admin/ai/proxy-assistant', {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                _csrf: csrfToken,
                model: window.AI_ASSISTANT_MODEL || '',
                max_tokens: 2048,
                system: dialectLine + '\n\nأنت مساعد متخصص في كتابة أوصاف منتجات بصيغة HTML احترافية. أرجع دائما مستندا كاملا وصالحا يبدأ بـ <!DOCTYPE html> ثم <html> وينتهي بـ </html>. أخرج HTML الخام فقط بدون شروحات وبدون markdown وبدون code fences.',
                messages: history
            })
        });
        var data = await response.json();
        if (!response.ok || data.success === false || data.error) {
            throw new Error((data.error && data.error.message) || data.message || ('AI API error (' + response.status + ')'));
        }
        var reply = (data.content || []).filter(function(b){ return b.type==='text'; }).map(function(b){ return b.text; }).join('\n');
        if (!reply.trim()) throw new Error('مزود الذكاء الاصطناعي لم يرجع أي نص قابل للاستخدام.');
        history.push({ role: 'assistant', content: reply });
        lastResponse = normalizeAiHtml(reply);
        loadBubble.textContent = lastResponse;
        if (applyBtn) applyBtn.style.display = '';
    } catch (err) {
        loadBubble.textContent = 'خطأ: ' + err.message;
        loadBubble.style.background = '#fee2e2';
        loadBubble.style.color = '#991b1b';
        history.pop();
    } finally {
        if (sendBtn) sendBtn.disabled = false;
    }
}

})();
</script>

<?php if ($productAiImageEnabled): ?>
<div class="modal fade" id="generateProductImagesModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?= __('products.ai_generate_images', 'Generate Additional Images') ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?= __('actions.close', 'Close') ?>"></button>
            </div>
            <div class="modal-body">
                <div class="row g-4">
                    <div class="col-lg-5">
                        <div class="border rounded p-3 h-100">
                            <div class="fw-semibold mb-2"><?= __('products.ai_source_preview', 'Source preview') ?></div>
                            <img id="aiImageSourcePreview" src="" class="img-fluid rounded border d-none mb-3" alt="">
                            <div id="aiImageSourceEmpty" class="text-muted small"><?= __('products.ai_source_empty', 'Choose a featured image first to use it as the visual reference.') ?></div>
                            <div class="mt-3 small text-muted">
                                <?= __('products.ai_generate_images_gemini_note', 'This tool uses Gemini image generation only and does not depend on the main active text provider.') ?>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-7">
                        <div class="mb-3">
                            <label class="form-label fw-semibold"><?= __('products.title') ?></label>
                            <input type="text" class="form-control" id="aiImageProductName" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold"><?= __('products.description', 'Description') ?></label>
                            <textarea class="form-control" id="aiImageProductDescription" rows="5" readonly></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold"><?= __('products.ai_image_types', 'Requested image types') ?></label>
                            <div class="row g-2">
                                <?php foreach ($productAiImageTypes as $typeKey => $typeLabel): ?>
                                    <div class="col-md-6">
                                        <label class="border rounded px-3 py-2 d-flex align-items-center gap-2 w-100" style="cursor:pointer;">
                                            <input type="checkbox" class="form-check-input m-0 ai-image-type" value="<?= htmlspecialchars($typeKey) ?>" <?= $typeKey === 'hero' || $typeKey === 'lifestyle' ? 'checked' : '' ?>>
                                            <span><?= htmlspecialchars($typeLabel) ?></span>
                                        </label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="alert d-none" id="aiImageGenerationAlert"></div>
                        <div class="d-flex flex-wrap gap-2 align-items-center">
                            <button type="button" class="btn btn-primary" id="aiGenerateImagesConfirmBtn">
                                <i class="bi bi-stars me-1"></i><span><?= __('products.ai_generate_images_action', 'Generate marketing images') ?></span>
                            </button>
                            <span class="text-muted small" id="aiGenerateImagesLoadingText"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/../footer.php'; ?>
