<?php
/**
 * Bizmart — AJAX Product Creation Form.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals

(static function() {
// AJAX Product Creation Form - Optimized version
if (!current_user_can('manage_woocommerce')) {
    wp_die('Insufficient permissions');
}

// Only get what's absolutely necessary for the form
// Get all product categories
$product_categories = get_terms([
    'taxonomy' => 'product_cat',
    'hide_empty' => false,
    'orderby' => 'name',
    'order' => 'ASC',
    'number' => 100 // Limit to prevent loading too many
]);

// Get shipping classes
$shipping_classes = get_terms([
    'taxonomy' => 'product_shipping_class',
    'hide_empty' => false
]);

// Optional: Get simple products for grouped products (if needed)
// Only fetch when absolutely required to reduce load
$simple_products = [];

?>

<style>
    .biz-products-container {
        display: flex;
        gap: 30px;
        margin-bottom: 30px;
    }

    .biz-products-main {
        flex: 4;
    }

    .biz-products-sidebar {
        flex: 1;
        min-width: 320px;
    }

    .biz-card {
        background: white;
        border-radius: 16px;
        padding: 30px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        margin-bottom: 20px;
    }

    .biz-tabs {
        display: flex;
        border-bottom: 2px solid #e5e7eb;
        margin-bottom: 30px;
        flex-wrap: wrap;
        gap: 5px;
    }

    .biz-tab {
        padding: 16px 24px;
        cursor: pointer;
        border-bottom: 2px solid transparent;
        margin-bottom: -2px;
        font-weight: 500;
        color: #6b7280;
        transition: all 0.3s;
        white-space: nowrap;
    }

    .biz-tab:hover {
        color: #4f46e5;
    }

    .biz-tab.active {
        color: #4f46e5;
        border-bottom-color: #4f46e5;
    }

    .biz-tab-content {
        display: none;
        animation: fadeIn 0.3s ease;
    }

    .biz-tab-content.active {
        display: block;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .biz-form-group {
        margin-bottom: 24px;
    }

    .biz-form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: #374151;
        font-size: 14px;
    }

    .biz-form-group label.required:after {
        content: ' *';
        color: #ef4444;
    }

    .biz-input, .biz-select, .biz-textarea, .biz-multiselect {
        width: 100%;
        padding: 14px;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        font-size: 14px;
        box-sizing: border-box;
        transition: all 0.3s;
        background: white;
    }

    /* Ensure number inputs remain editable (not just spinner arrows) */
    .biz-input[type="number"] {
        pointer-events: auto;
        user-select: text;
        -webkit-user-select: text;
        cursor: text;
    }

    .biz-multiselect {
        min-height: 100px;
        padding: 10px;
    }

    .biz-multiselect option {
        padding: 8px;
        margin: 2px 0;
        border-radius: 4px;
    }

    .biz-multiselect option:hover {
        background: #f3f4f6;
    }

    .biz-input:focus, .biz-select:focus, .biz-textarea:focus, .biz-multiselect:focus {
        outline: none;
        border-color: #4f46e5;
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }

    .biz-textarea {
        min-height: 100px;
        resize: vertical;
    }

    .biz-textarea-small {
        min-height: 80px;
    }

    .biz-switch {
        position: relative;
        display: inline-block;
        width: 44px;
        height: 24px;
        vertical-align: middle;
        margin-right: 8px;
    }

    .biz-switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .biz-slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        transition: .4s;
        border-radius: 24px;
    }

    .biz-slider:before {
        position: absolute;
        content: "";
        height: 18px;
        width: 18px;
        left: 3px;
        bottom: 3px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
    }

    .biz-switch input:checked + .biz-slider {
        background-color: #4f46e5;
    }

    .biz-switch input:checked + .biz-slider:before {
        transform: translateX(20px);
    }

    .biz-form-grid-2 {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
    }

    .biz-form-grid-3 {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
    }

    .biz-section {
        margin-bottom: 40px;
        padding: 24px;
        background: #fafafa;
        border-radius: 12px;
        border: 1px solid #f0f0f0;
    }

    .biz-section-title {
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .biz-category-creator {
        margin-top: 10px;
        display: flex;
        gap: 8px;
    }

    .biz-category-creator input {
        flex: 1;
        padding: 8px 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
    }

    .biz-category-creator button {
        padding: 8px 16px;
        background: #4f46e5;
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
    }

    .biz-tag {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background: #4f46e5;
        color: white;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 12px;
        margin: 4px 4px 0 0;
        position: relative;
        padding-right: 24px;
    }

    .biz-tag-remove {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        background: none;
        border: none;
        color: white;
        font-size: 16px;
        line-height: 1;
        padding: 0;
        z-index: 10;
    }

    .biz-tag-remove:hover {
        color: #ff6b6b;
    }

    .biz-tag-input {
        min-height: 44px;
        padding: 8px;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        background: white;
        position: relative;
        z-index: 1;
    }

    .biz-tag-input input {
        position: relative;
        z-index: 2;
    }

    .biz-attribute-term-picker {
        margin-top: 10px;
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }

    .biz-attribute-term-picker button {
        border: 1px solid #e5e7eb;
        background: #fff;
        border-radius: 999px;
        padding: 6px 12px;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.2s ease;
        color: #4b5563;
    }

    .biz-attribute-term-picker button:hover {
        background: #f3f4f6;
        color: #111827;
    }

    .biz-attribute-term-picker .biz-attr-term-add-all {
        border-style: dashed;
        font-weight: 600;
        color: #2563eb;
    }

    .biz-attribute-term-picker-empty {
        font-size: 12px;
        color: #9ca3af;
    }

    .biz-image-upload-area {
        border: 2px dashed #d1d5db;
        border-radius: 12px;
        padding: 40px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        background: #fafafa;
    }

    .biz-image-upload-area:hover {
        border-color: #4f46e5;
        background: #f8f9ff;
    }

    .biz-image-preview {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
        gap: 12px;
        margin-top: 16px;
    }

    .biz-image-preview img {
        width: 100%;
        height: 100px;
        object-fit: cover;
        border-radius: 8px;
        border: 1px solid #e5e7eb;
    }

    .biz-gallery-images {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        margin-top: 16px;
    }

    .biz-btn {
        padding: 12px 24px;
        border: none;
        border-radius: 8px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        position: relative;
    }

    .biz-btn:disabled,
    .biz-btn[disabled] {
        opacity: 0.6 !important;
        cursor: not-allowed !important;
        transform: none !important;
    }

    .biz-btn.loading {
        pointer-events: none;
    }

    .biz-btn.loading::after {
        content: '';
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: white;
        animation: spin 0.8s linear infinite;
        margin-left: 8px;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    .biz-btn-success {
        background: #10b981;
        color: white;
    }

    .biz-btn-success:hover:not(:disabled) {
        background: #059669;
        transform: translateY(-1px);
    }

    .biz-btn-secondary {
        background: #6b7280;
        color: white;
    }

    .biz-btn-secondary:hover:not(:disabled) {
        background: #4b5563;
    }

    .biz-toggle-section {
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #e5e7eb;
        margin-bottom: 20px;
    }

    .biz-toggle-section:hover {
        color: #4f46e5;
    }

    .biz-collapsible-content {
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.3s ease;
    }

    .biz-collapsible-content.show {
        max-height: 2000px;
    }

    .biz-shipping-section {
        display: none;
    }

    .biz-shipping-section.show {
        display: block;
    }

    .biz-attribute-row {
        background: #f9fafb;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 16px;
        border: 1px solid #f3f4f6;
    }

    .biz-variation-row {
        background: #f9fafb;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 16px;
        border: 1px solid #f3f4f6;
    }

    .biz-variation-row h4 {
        margin: 0 0 16px 0;
        color: #374151;
        font-size: 16px;
    }

    .biz-remove-variation {
        background: #ef4444;
        color: white;
        border: none;
        padding: 6px 12px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 12px;
    }

    .biz-remove-variation:hover {
        background: #dc2626;
    }

    .biz-notification {
        padding: 16px;
        border-radius: 8px;
        margin-bottom: 20px;
        display: none;
        font-weight: 500;
        font-size: 14px;
        animation: slideDown 0.3s ease;
        position: relative;
        z-index: 10;
    }

    @keyframes slideDown {
        from { transform: translateY(-20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
    }

    .biz-notification.success {
        background: #d1fae5;
        color: #065f46;
        border: 2px solid #6ee7b7;
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.15);
    }

    .biz-notification.error {
        background: #fee2e2;
        color: #991b1b;
        border: 2px solid #fca5a5;
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.15);
    }

    /* Modal specific adjustments */
    .biz-products-container {
        margin: 0;
    }

    .biz-card {
        margin: 0;
        box-shadow: none;
        border: 1px solid #e5e7eb;
    }
</style>

<div class="biz-products-container">
    <div class="biz-products-main">
        <div id="biz-notification" class="biz-notification"></div>

        <div class="biz-card">
            <div class="biz-tabs">
                <div class="biz-tab active" data-tab="simple" onclick="BizProducts.switchTab('simple')">📦 <?php echo esc_html(bizmart_text('Simple', 'Simple', 'بسيط')); ?></div>
                <div class="biz-tab" data-tab="variable" onclick="BizProducts.switchTab('variable')">🎯 <?php echo esc_html(bizmart_text('Variable', 'Variable', 'متغير')); ?></div>
                <div class="biz-tab" data-tab="grouped" onclick="BizProducts.switchTab('grouped')">📦 <?php echo esc_html(bizmart_text('Grouped', 'Groupé', 'مجمّع')); ?></div>
                <div class="biz-tab" data-tab="external" onclick="BizProducts.switchTab('external')">🔗 <?php echo esc_html(bizmart_text('External', 'Externe', 'خارجي')); ?></div>
                <div class="biz-tab" data-tab="digital" onclick="BizProducts.switchTab('digital')">💾 <?php echo esc_html(bizmart_text('Digital', 'Digital', 'رقمي')); ?></div>
            </div>
            <div id="biz-tab-simple" class="biz-tab-content active">
                <form id="biz-form-simple">
                    <div class="biz-workspace-layout">
                        <!-- Left Column: Main Content (70%) -->
                        <div class="biz-workspace-main">
                            <!-- Basic Information -->
                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('📋 Basic Information', '📋 Informations de Base', '📋 المعلومات الأساسية'); ?></h3>
                                <div class="biz-form-row-name-sku">
                                    <div class="biz-form-group">
                                        <label class="required"><?php bizmart_e('Product name', 'Nom du produit', 'اسم المنتج'); ?></label>
                                        <input type="text" id="biz-simple-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Descriptive product name', 'Nom descriptif du produit', 'اسم المنتج الوصفي')); ?>" required>
                                    </div>
                                    </div>
                                    <div class="biz-form-group">
                                        <label class="required"><?php bizmart_e('SKU', 'SKU', 'رمز المنتج'); ?></label>
                                        <input type="text" id="biz-simple-sku" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Unique reference', 'Référence unique', 'مرجع فريد')); ?>" required>
                                    </div>
                                </div>

                                <div class="biz-form-grid-3">
                                    <div class="biz-form-group">
                                        <label class="required"><?php bizmart_e('Regular price', 'Prix régulier', 'السعر العادي'); ?></label>
                                        <div class="biz-input-prefix-wrapper">
                                            <span class="biz-input-prefix">$</span>
                                            <input type="number" step="0.01" min="0" id="biz-simple-regular-price" class="biz-input biz-price-input" placeholder="0.00" required>
                                        </div>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Sale price', 'Prix promotionnel', 'سعر التخفيض'); ?></label>
                                        <div class="biz-input-prefix-wrapper">
                                            <span class="biz-input-prefix">$</span>
                                            <input type="number" step="0.01" min="0" id="biz-simple-sale-price" class="biz-input biz-price-input" placeholder="0.00">
                                        </div>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Cost price', "Prix d'achat (coût)", 'سعر التكلفة'); ?></label>
                                        <div class="biz-input-prefix-wrapper">
                                            <span class="biz-input-prefix">$</span>
                                            <input type="number" step="0.01" min="0" id="biz-simple-cost-price" class="biz-input biz-price-input" placeholder="0.00">
                                        </div>
                                    </div>
                                </div>

                                <!-- Profit Calculator Intel (instant feedback) -->
                                <div id="biz-simple-profit-intel" style="display: none; padding: 15px 20px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; margin-top: 10px;">
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                        <span style="font-weight: 600; font-size: 13px; color: #475569; text-transform: uppercase; letter-spacing: 0.5px;">Profit Intel</span>
                                        <span id="biz-simple-profit-status" style="font-size: 11px; font-weight: 700; padding: 2px 8px; border-radius: 9999px;"></span>
                                    </div>
                                    <div class="biz-form-grid-3" style="gap: 12px;">
                                        <div>
                                            <div style="font-size: 12px; color: #64748b;">Net Profit</div>
                                            <div id="biz-simple-profit-val" style="font-size: 16px; font-weight: 700; color: #1e293b;">0.00</div>
                                        </div>
                                        <div>
                                            <div style="font-size: 12px; color: #64748b;">Profit Margin</div>
                                            <div id="biz-simple-margin-val" style="font-size: 16px; font-weight: 700; color: #1e293b;">0.0%</div>
                                        </div>
                                        <div>
                                            <div style="font-size: 12px; color: #64748b;">Markup</div>
                                            <div id="biz-simple-markup-val" style="font-size: 16px; font-weight: 700; color: #1e293b;">0.0%</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Description -->
                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('📝 Description', '📝 Description', '📝 الوصف'); ?></h3>
                                <div class="biz-form-grid-2">
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Short description', 'Description courte', 'وصف قصير'); ?></label>
                                        <textarea id="biz-simple-short-description" class="biz-textarea biz-textarea-small" placeholder="<?php echo esc_attr(bizmart_text('Short description shown in lists...', 'Description concise affichée dans les listes...', 'وصف قصير يظهر في القوائم...')); ?>"></textarea>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Full description', 'Description complète', 'الوصف الكامل'); ?></label>
                                        <textarea id="biz-simple-description" class="biz-textarea" placeholder="<?php echo esc_attr(bizmart_text('Full product description...', 'Description détaillée du produit...', 'الوصف الكامل للمنتج...')); ?>"></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Inventory & Identification (Barcodes) -->
                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('📦 Inventory & Identification', '📦 Gestion du Stock & Identification', '📦 المخزون والتعريف'); ?></h3>
                                
                                <!-- Manage Stock Toggle Inline with label -->
                                <div class="biz-form-group">
                                    <label style="display: flex; align-items: center; cursor: pointer; margin-bottom: 0;">
                                        <span class="biz-switch">
                                            <input type="checkbox" id="biz-simple-manage-stock">
                                            <span class="biz-slider"></span>
                                        </span>
                                        <?php bizmart_e('Manage stock', 'Gérer le stock', 'إدارة المخزون'); ?>
                                    </label>
                                </div>

                                <!-- Stock quantity hidden by default -->
                                <div class="biz-form-group" id="biz-simple-stock-quantity-group" style="display: none;">
                                    <label><?php bizmart_e('Stock quantity', 'Quantité en stock', 'كمية المخزون'); ?></label>
                                    <input type="number" min="0" step="1" inputmode="numeric" pattern="[0-9]*" id="biz-simple-stock-quantity" class="biz-input" placeholder="0">
                                </div>

                                <!-- Stock Status and Purchase Limit side by side -->
                                <div class="biz-form-grid-2">
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Stock status', 'Statut du stock', 'حالة المخزون'); ?></label>
                                        <select id="biz-simple-stock-status" class="biz-select">
                                            <option value="instock"><?php bizmart_e('In stock', 'En stock', 'متوفر'); ?></option>
                                            <option value="outofstock"><?php bizmart_e('Out of stock', 'Rupture de stock', 'نفد من المخزون'); ?></option>
                                            <option value="onbackorder"><?php bizmart_e('On backorder', 'Sur commande', 'طلب مسبق'); ?></option>
                                        </select>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Purchase limit', 'Limite par commande', 'حد الشراء'); ?></label>
                                        <input type="number" min="0" id="biz-simple-purchase-limit" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Unlimited', 'Illimité', 'غير محدود')); ?>">
                                    </div>
                                </div>

                                <!-- Allow Backorders and Sold Individually side by side -->
                                <div class="biz-form-grid-2">
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Allow backorders?', 'Permettre les précommandes?', 'السماح بالطلبات المسبقة؟'); ?></label>
                                        <select id="biz-simple-backorders" class="biz-select">
                                            <option value="no"><?php bizmart_e('No', 'Non', 'لا'); ?></option>
                                            <option value="notify"><?php bizmart_e('Allow, notify customer', 'Autoriser, notifier', 'السماح، إخطار العميل'); ?></option>
                                            <option value="yes"><?php bizmart_e('Allow', 'Autoriser', 'السماح'); ?></option>
                                        </select>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Sold individually?', 'Vendu individuellement?', 'يُباع بشكل فردي؟'); ?></label>
                                        <select id="biz-simple-sold-individually" class="biz-select">
                                            <option value="no"><?php bizmart_e('No', 'Non', 'لا'); ?></option>
                                            <option value="yes"><?php bizmart_e('Yes', 'Oui', 'نعم'); ?></option>
                                        </select>
                                    </div>
                                </div>

                                <!-- Barcodes subdivision -->
                                <div style="border-top: 1px solid #f1f5f9; padding-top: 20px; margin-top: 20px;">
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                                        <label style="font-weight: 600; font-size: 14px; color: #1e293b;">🏷️ <?php bizmart_e('EAN-13 Product Barcodes', 'Barcodes du Produit', 'باركود المنتج'); ?></label>
                                        <div style="display: flex; gap: 8px;">
                                            <button type="button" class="biz-btn biz-btn-secondary add-barcode-btn" data-product-type="simple" style="padding: 6px 12px; font-size: 12px;">
                                                ➕ <?php bizmart_e('Add Barcode', 'Ajouter', 'إضافة باركود'); ?>
                                            </button>
                                            <button type="button" class="biz-btn biz-btn-secondary generate-barcode-btn" data-product-type="simple" style="padding: 6px 12px; font-size: 12px;">
                                                ⚡ <?php bizmart_e('Generate EAN-13', 'Générer EAN-13', 'توليد EAN-13'); ?>
                                            </button>
                                        </div>
                                    </div>
                                    
                                    <!-- Card Grid -->
                                    <div class="biz-barcodes-grid biz-barcodes-tbody" data-product-type="simple">
                                        <div class="biz-no-barcodes-placeholder" style="text-align: center; color: #9ca3af; padding: 20px 0; grid-column: 1 / -1;">
                                            <?php bizmart_e('No barcodes added yet.', 'Aucun code-barres ajouté.', 'لم يتم إضافة باركود بعد.'); ?>
                                        </div>
                                    </div>
                                </div>

                                <!-- Virtual product toggle inline at the bottom of this section -->
                                <div style="border-top: 1px solid #f1f5f9; padding-top: 20px; margin-top: 20px;">
                                    <div class="biz-form-group" style="margin-bottom: 0;">
                                        <label style="display: flex; align-items: center; cursor: pointer; margin-bottom: 0;">
                                            <span class="biz-switch">
                                                <input type="checkbox" id="biz-simple-virtual" onchange="BizProducts.toggleShippingSection(this.checked)">
                                                <span class="biz-slider"></span>
                                            </span>
                                            <?php bizmart_e('Virtual product (no shipping)', 'Produit virtuel (pas de livraison)', 'منتج افتراضي (بدون شحن)'); ?>
                                        </label>
                                    </div>
                                </div>

                                <!-- Shipping dimensions inline inside Inventory card -->
                                <div class="biz-shipping-section" id="biz-simple-shipping-section" style="margin-top: 15px;">
                                    <h4 style="margin: 15px 0 10px; color: #374151; font-size: 14px; font-weight: 600;">🚚 <?php bizmart_e('Shipping Dimensions', 'Dimensions de livraison', 'أبعاد الشحن'); ?></h4>
                                    <div class="biz-form-grid-4">
                                        <div class="biz-form-group">
                                            <label><?php bizmart_e('Weight (kg)', 'Poids (kg)', 'الوزن (كجم)'); ?></label>
                                            <input type="number" step="0.001" min="0" id="biz-simple-weight" class="biz-input" placeholder="0.00">
                                        </div>
                                        <div class="biz-form-group">
                                            <label><?php bizmart_e('Length (cm)', 'Longueur (cm)', 'الطول (سم)'); ?></label>
                                            <input type="number" step="0.1" min="0" id="biz-simple-length" class="biz-input" placeholder="0.0">
                                        </div>
                                        <div class="biz-form-group">
                                            <label><?php bizmart_e('Width (cm)', 'Largeur (cm)', 'العرض (سم)'); ?></label>
                                            <input type="number" step="0.1" min="0" id="biz-simple-width" class="biz-input" placeholder="0.0">
                                        </div>
                                        <div class="biz-form-group">
                                            <label><?php bizmart_e('Height (cm)', 'Hauteur (cm)', 'الارتفاع (سم)'); ?></label>
                                            <input type="number" step="0.1" min="0" id="biz-simple-height" class="biz-input" placeholder="0.0">
                                        </div>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Shipping class', 'Classe de livraison', 'فئة الشحن'); ?></label>
                                        <select id="biz-simple-shipping-class" class="biz-select">
                                            <option value=""><?php bizmart_e('Default', 'Par défaut', 'افتراضي'); ?></option>
                                            <?php foreach ($shipping_classes as $class): ?>
                                                <option value="<?php echo esc_attr($class->term_id); ?>"><?php echo esc_html($class->name); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('🔗 Linked Products', '🔗 Produits Liés', '🔗 منتجات مرتبطة'); ?></h3>
                                <div class="biz-form-grid-2">
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Cross-sells', 'Ventes croisées (Cross-sells)', 'بيع متقاطع'); ?></label>
                                        <input type="text" id="biz-simple-cross-sells" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('SKUs separated by commas', 'SKUs séparés par des virgules', 'رموز SKU مفصولة بفواصل')); ?>">
                                        <small style="color: #6b7280;"><?php bizmart_e('Frequently bought together', 'Produits fréquemment achetés ensemble', 'يُشترى معًا كثيرًا'); ?></small>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Upsells', 'Ventes incitatives (Upsells)', 'بيع إضافي'); ?></label>
                                        <input type="text" id="biz-simple-upsells" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('SKUs separated by commas', 'SKUs séparés par des virgules', 'رموز SKU مفصولة بفواصل')); ?>">
                                        <small style="color: #6b7280;"><?php bizmart_e('Higher quality alternatives', 'Produits similaires de meilleure qualité', 'بدائل ذات جودة أعلى'); ?></small>
                                    </div>
                                </div>
                            </div>

                            <!-- Advanced Settings -->
                            <div class="biz-section">
                                <div class="biz-toggle-section" onclick="BizProducts.toggleSection('biz-simple-advanced')">
                                    <h3 class="biz-section-title" style="margin: 0;"><?php bizmart_e('⚙️ Advanced Settings', '⚙️ Paramètres Avancés', '⚙️ إعدادات متقدمة'); ?></h3>
                                    <span>▼</span>
                                </div>
                                <div id="biz-simple-advanced" class="biz-collapsible-content">
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Purchase note', "Note d'achat", 'ملاحظة الشراء'); ?></label>
                                        <textarea id="biz-simple-purchase-note" class="biz-textarea biz-textarea-small" placeholder="<?php echo esc_attr(bizmart_text('Message after purchase...', 'Message après achat...', 'رسالة après achat...')); ?>"></textarea>
                                    </div>
                                    <div class="biz-form-grid-2">
                                        <div class="biz-form-group">
                                            <label><?php bizmart_e('Menu order', 'Ordre de menu', 'ترتيب القائمة'); ?></label>
                                            <input type="number" id="biz-simple-menu-order" class="biz-input" placeholder="0">
                                        </div>
                                        <div class="biz-form-group">
                                            <label><?php bizmart_e('Reviews', 'Commentaires', 'التقييمات'); ?></label>
                                            <select id="biz-simple-reviews" class="biz-select">
                                                <option value="open"><?php bizmart_e('Enable', 'Autoriser', 'تفعيل'); ?></option>
                                                <option value="closed"><?php bizmart_e('Disable', 'Fermer', 'تعطيل'); ?></option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column: Sidebar (30%) -->
                        <div class="biz-workspace-sidebar">
                            <!-- Status Card -->
                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('📊 Status & Visibility', '📊 Statut & Visibilité', '📊 الحالة والظهور'); ?></h3>
                                <div class="biz-form-group">
                                    <label><?php bizmart_e('Status', 'Statut', 'الحالة'); ?></label>
                                    <select id="biz-simple-status" class="biz-select">
                                        <option value="publish"><?php bizmart_e('Published', 'Publié', 'منشور'); ?></option>
                                        <option value="draft"><?php bizmart_e('Draft', 'Brouillon', 'مسودة'); ?></option>
                                    </select>
                                </div>
                            </div>

                            <!-- Images -->
                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('🖼️ Product Images', '🖼️ Images du Produit', '🖼️ صور المنتج'); ?></h3>
                                <div class="biz-form-group">
                                    <label><?php bizmart_e('Main image', 'Image principale', 'الصورة الرئيسية'); ?></label>
                                    <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('biz-simple-image-id', 'biz-simple-image-preview')">
                                        <div style="font-size: 48px; color: #9ca3af;">📷</div>
                                        <p style="margin: 10px 0 0 0; color: #6b7280;"><?php bizmart_e('Click to upload', 'Cliquez pour télécharger', 'انقر للرفع'); ?></p>
                                    </div>
                                    <input type="hidden" id="biz-simple-image-id">
                                    <img id="biz-simple-image-preview" class="biz-image-preview">
                                </div>
                                <div class="biz-form-group" style="margin-top: 15px;">
                                    <label><?php bizmart_e('Image gallery', "Galerie d'images", 'معرض الصور'); ?></label>
                                    <div class="biz-image-upload-area" onclick="BizProducts.openGalleryUploader('simple')">
                                        <div style="font-size: 48px; color: #9ca3af;">🖼️</div>
                                        <p style="margin: 10px 0 0 0; color: #6b7280;"><?php bizmart_e('Click to add', 'Cliquez pour ajouter', 'انقر للإضافة'); ?></p>
                                    </div>
                                    <div class="biz-gallery-images" id="biz-simple-gallery"></div>
                                    <input type="hidden" id="biz-simple-gallery-ids">
                                </div>
                            </div>

                            <!-- Categories -->
                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('🏷️ Categories', '🏷️ Catégories', '🏷️ الفئات'); ?></h3>
                                <div class="biz-form-group">
                                    <select id="biz-simple-categories" class="biz-multiselect" multiple style="height: 150px;">
                                        <?php foreach ($product_categories as $category): ?>
                                            <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="biz-category-creator" style="margin-top: 10px;">
                                        <input type="text" id="biz-simple-new-category" placeholder="<?php echo esc_attr(bizmart_text('New category', 'Nouvelle catégorie', 'فئة جديدة')); ?>">
                                        <button type="button" onclick="BizProducts.createCategory('simple')">+ <?php bizmart_e('Add', 'Ajouter', 'إضافة'); ?></button>
                                    </div>
                                </div>
                            </div>

                            <!-- Tags -->
                            <div class="biz-section">
                                <h3 class="biz-section-title"><?php bizmart_e('🏷️ Tags', '🏷️ Étiquettes', '🏷️ العلامات'); ?></h3>
                                <div class="biz-form-group">
                                    <div class="biz-tag-input" id="biz-simple-tags-container">
                                        <input type="text" id="biz-simple-tags-input" placeholder="<?php echo esc_attr(bizmart_text('Add tag & press Enter', 'Ajouter & Entrée', 'أضف علامة واضغط Enter')); ?>">
                                    </div>
                                    <input type="hidden" id="biz-simple-tags">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Sticky Action/Save Bar -->
                    <div class="biz-sticky-save-bar">
                        <div style="display: flex; gap: 12px;">
                            <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.resetForm('simple'); return false;">
                                <?php bizmart_e('↻ Reset', '↻ Réinitialiser', '↻ إعادة تعيين'); ?>
                            </button>
                            <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.saveProduct('simple','draft', this); return false;">
                                <?php bizmart_e('💾 Save draft', '💾 Enregistrer brouillon', '💾 حفظ كمسودة'); ?>
                            </button>
                        </div>
                        <div>
                            <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createSimpleProduct(this); return false;">
                                <span style="font-size: 16px; margin-right: 6px;">✅</span>
                                <?php bizmart_e('Create product', 'Créer le produit', 'إنشاء المنتج'); ?>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            <!-- Variable Product Tab -->
            <div id="biz-tab-variable" class="biz-tab-content">tton type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createFromActiveTab(); return false;">
                            <span style="font-size: 18px;">✅</span>
                            <?php bizmart_e('Create product', 'Créer le produit', 'إنشاء المنتج'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.resetForm('simple'); return false;">
                            <?php bizmart_e('↻ Reset', '↻ Réinitialiser', '↻ إعادة تعيين'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.saveProduct('draft'); return false;">
                            <?php bizmart_e('💾 Save draft', '💾 Enregistrer brouillon', '💾 حفظ كمسودة'); ?>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Variable Product Tab -->
            <div id="biz-tab-variable" class="biz-tab-content">
                <form id="biz-form-variable">
                    <!-- Basic Information -->
                    <div class="biz-section">
                        <h3 class="biz-section-title"><?php bizmart_e('📋 Basic Information', '📋 Informations de Base', '📋 المعلومات الأساسية'); ?></h3>
                        <div class="biz-form-row-name-sku">
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Product name', 'Nom du produit', 'اسم المنتج'); ?></label>
                                <input type="text" id="biz-variable-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Range name', 'Nom de la gamme', 'اسم النطاق')); ?>" required>
                            </div>
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Parent SKU', 'SKU parent', 'SKU الأصل'); ?></label>
                                <input type="text" id="biz-variable-sku" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Range SKU', 'SKU de la gamme', 'SKU النطاق')); ?>" required>
                            </div>
                        </div>

                        <div class="biz-form-grid-2">
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Short description', 'Description courte', 'وصف قصير'); ?></label>
                                <textarea id="biz-variable-short-description" class="biz-textarea biz-textarea-variable-desc" placeholder="<?php echo esc_attr(bizmart_text('Short description...', 'Description concise...', 'وصف قصير...')); ?>"></textarea>
                            </div>

                            <div class="biz-form-group">
                                <label><?php bizmart_e('Full description', 'Description complète', 'الوصف الكامل'); ?></label>
                                <textarea id="biz-variable-description" class="biz-textarea biz-textarea-variable-desc" placeholder="<?php echo esc_attr(bizmart_text('Full description...', 'Description détaillée...', 'الوصف الكامل...')); ?>"></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Categories & Tags -->
                    <div class="biz-section" style="padding: 12px 20px !important;">
                        <h3 class="biz-section-title"><?php bizmart_e('🏷️ Categories & Tags', '🏷️ Catégories & Étiquettes', '🏷️ الفئات والعلامات'); ?></h3>
                        <div class="biz-form-grid-2">
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Categories', 'Catégories', 'الفئات'); ?></label>
                                <select id="biz-variable-categories" class="biz-multiselect biz-multiselect-compact" multiple>
                                    <?php foreach ($product_categories as $category): ?>
                                        <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="biz-category-creator-inline">
                                    <input type="text" id="biz-variable-new-category" placeholder="<?php echo esc_attr(bizmart_text('New category', 'Nouvelle catégorie', 'فئة جديدة')); ?>">
                                    <button type="button" onclick="BizProducts.createCategory('variable')"><?php bizmart_e('+ Add', '+ Ajouter', '+ إضافة'); ?></button>
                                </div>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Tags', 'Étiquettes (Tags)', 'العلامات'); ?></label>
                                <div class="biz-tag-input" id="biz-variable-tags-container">
                                    <input type="text" id="biz-variable-tags-input" placeholder="<?php echo esc_attr(bizmart_text('Add a tag, press Enter', 'Ajouter une étiquette, appuyez sur Entrée', 'أضف علامة، اضغط Enter')); ?>">
                                </div>
                                <input type="hidden" id="biz-variable-tags">
                            </div>
                        </div>
                    </div>

                    <!-- Attributes -->
                    <div class="biz-section">
                        <h3 class="biz-section-title"><?php bizmart_e('🎨 Attributes', '🎨 Attributs', '🎨 السمات'); ?></h3>
                        <div id="biz-variable-attributes">
                            <div class="biz-attribute-row" data-id="1">
                                <div class="biz-form-grid-2">
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Select an existing attribute', 'Sélectionner un attribut existant', 'اختيار سمة موجودة'); ?></label>
                                        <select class="biz-select existing-attribute-select" onchange="BizProducts.onExistingAttributeSelect(this)">
                                            <option value=""><?php bizmart_e('-- Choose an existing attribute --', '-- Choisir un attribut existant --', '-- اختر سمة موجودة --'); ?></option>
                                            <?php
                                            // Get all product attributes
                                            $attribute_taxonomies = wc_get_attribute_taxonomies();
                                            foreach ($attribute_taxonomies as $tax) {
                                                echo '<option value="' . esc_attr($tax->attribute_name) . '" data-label="' . esc_attr($tax->attribute_label) . '">' . esc_html($tax->attribute_label) . '</option>';
                                            }
                                            ?>
                                            <option value="new"><?php bizmart_e('+ Create a new attribute', '+ Créer un nouvel attribut', '+ إنشاء سمة جديدة'); ?></option>
                                        </select>
                                    </div>
                                    <div class="biz-form-group">
                                        <label><?php bizmart_e('Or create a new attribute', 'Ou créer un nouvel attribut', 'أو إنشاء سمة جديدة'); ?></label>
                                        <input type="text" class="biz-input attribute-name" placeholder="<?php echo esc_attr(bizmart_text('Attribute name (e.g., Color, Size)', "Nom de l'attribut (ex: Couleur, Taille)")); ?>" style="display: none;">
                                    </div>
                                </div>
                                
                                <div class="biz-form-group" style="margin-top: 10px; width: 100%;">
                                    <label><?php bizmart_e('Attribute values', "Valeurs de l'attribut", 'قيم السمة'); ?></label>
                                    <div class="biz-tag-input" id="biz-attribute-values-1">
                                        <input type="text" class="biz-attribute-values-input" placeholder="<?php echo esc_attr(bizmart_text('Add a value, press Enter (Separate with commas)', 'Ajouter une valeur, Entrée (Séparer par des virgules)', 'أضف قيمة، اضغط Enter (افصل بفواصل)')); ?>">
                                    </div>
                                    <input type="hidden" class="attribute-values" id="biz-attribute-values-hidden-1">
                                    <div class="biz-attribute-term-picker" data-row="1"></div>
                                </div>

                                <div class="biz-attr-inline-row">
                                    <div class="biz-attr-inline-left">
                                        <label style="display: flex; align-items: center; cursor: pointer; gap: 8px; font-size: 12px; margin: 0;">
                                            <span class="biz-switch">
                                                <input type="checkbox" class="attribute-visible" checked>
                                                <span class="biz-slider"></span>
                                            </span>
                                            <?php bizmart_e('Visible on the product page', 'Visible sur la page produit', 'مرئي على صفحة المنتج'); ?>
                                        </label>
                                        <label style="display: flex; align-items: center; cursor: pointer; gap: 8px; font-size: 12px; margin: 0;">
                                            <span class="biz-switch">
                                                <input type="checkbox" class="attribute-variation" checked>
                                                <span class="biz-slider"></span>
                                            </span>
                                            <?php bizmart_e('Used for variations', 'Utilisé pour les variations', 'يُستخدم للتنويعات'); ?>
                                        </label>
                                    </div>
                                    <div class="biz-attr-inline-right">
                                        <button type="button" class="biz-attr-add-btn" onclick="BizProducts.addAttribute()"><?php bizmart_e('+ Add another attribute', '+ Ajouter un autre attribut', '+ إضافة سمة أخرى'); ?></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Variations Section -->
                    <div class="biz-section">
                        <div class="biz-toggle-section" onclick="BizProducts.toggleSection('biz-variations-section')">
                            <h3 class="biz-section-title"><?php bizmart_e('🎯 Variations', '🎯 Variations', '🎯 التنويعات'); ?></h3>
                            <span>▲</span>
                        </div>
                        <div id="biz-variations-section" class="biz-collapsible-content show">
                            <div style="margin-bottom: 20px;">
                                <button type="button" class="biz-btn" onclick="BizProducts.generateVariations()">
                                    <span style="font-size: 18px;">⚡</span>
                                    <?php bizmart_e('Generate automatically', 'Générer automatiquement', 'إنشاء تلقائي'); ?>
                                </button>
                                <button type="button" class="biz-btn biz-btn-secondary" onclick="BizProducts.addVariation()">
                                    <span style="font-size: 18px;">+</span>
                                    <?php bizmart_e('Add manually', 'Ajouter manuellement', 'إضافة يدوية'); ?>
                                </button>
                            </div>

                            <div id="biz-variations-container">
                                <!-- Variations will be added here -->
                            </div>
                        </div>
                    </div>

                    <!-- Images -->
                    <div class="biz-section">
                        <h3 class="biz-section-title"><?php bizmart_e('🖼️ Product Images', '🖼️ Images du Produit', '🖼️ صور المنتج'); ?></h3>
                        <div class="biz-form-group">
                            <label><?php bizmart_e('Main image', 'Image principale', 'الصورة الرئيسية'); ?></label>
                            <div class="biz-image-upload-area-compact" onclick="BizProducts.openMediaUploader('biz-variable-image-id', 'biz-variable-image-preview')">
                                <div class="biz-upload-icon">📷</div>
                                <p class="biz-upload-label"><?php bizmart_e('Click to upload', 'Cliquez pour télécharger', 'انقر للتحميل'); ?></p>
                            </div>
                            <input type="hidden" id="biz-variable-image-id">
                            <img id="biz-variable-image-preview" class="biz-image-preview">
                        </div>
                    </div>

                    <!-- Pricing -->
                    <div class="biz-section">
                        <h3 class="biz-section-title"><?php bizmart_e('💰 Base Pricing', '💰 Prix de Base', '💰 التسعير الأساسي'); ?></h3>
                        <div class="biz-form-grid-3">
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Base regular price', 'Prix régulier de base', 'السعر العادي الأساسي'); ?></label>
                                <div class="biz-input-prefix-wrapper">
                                    <span class="biz-input-prefix">$</span>
                                    <input type="number" step="0.01" min="0" id="biz-variable-base-regular" class="biz-input" placeholder="0.00">
                                </div>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Base sale price', 'Prix promotionnel de base', 'سعر التخفيض الأساسي'); ?></label>
                                <div class="biz-input-prefix-wrapper">
                                    <span class="biz-input-prefix">$</span>
                                    <input type="number" step="0.01" min="0" id="biz-variable-base-sale" class="biz-input" placeholder="0.00">
                                </div>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Base cost price', "Prix d'achat de base", 'سعر التكلفة الأساسي'); ?></label>
                                <div class="biz-input-prefix-wrapper">
                                    <span class="biz-input-prefix">$</span>
                                    <input type="number" step="0.01" min="0" id="biz-variable-base-cost" class="biz-input" placeholder="0.00">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="biz-sticky-save-bar" style="display: flex; gap: 12px; margin-top: 20px; align-items: center; border-top: 1px solid var(--biz-border); padding-top: 16px;">
                        <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createFromActiveTab()">
                            <span style="font-size: 16px;">🎯</span>
                            <?php bizmart_e('Create product', 'Créer le produit', 'إنشاء المنتج'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" onclick="BizProducts.resetForm('variable')">
                            <?php bizmart_e('↻ Reset', '↻ Réinitialiser', '↻ إعادة تعيين'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" onclick="BizProducts.saveProduct('draft'); return false;">
                            <?php bizmart_e('💾 Save draft', '💾 Enregistrer brouillon', '💾 حفظ كمسودة'); ?>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Grouped Product Tab -->
            <div id="biz-tab-grouped" class="biz-tab-content">
                <form id="biz-form-grouped">
                    <div class="biz-section">
                        <h3 class="biz-section-title"><?php bizmart_e('📦 Grouped Product', '📦 Produit Groupé', '📦 منتج مجمع'); ?></h3>
                        <p style="color: #6b7280; margin-bottom: 12px; font-size: 12px; margin-top: 0;"><?php bizmart_e('Create a grouped product that contains multiple simple products', 'Créez un produit groupé qui contient plusieurs produits simples', 'إنشاء منتج مجمع يحتوي على عدة منتجات بسيطة'); ?></p>

                        <div class="biz-form-row-name-sku" style="gap: 12px;">
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Group name', 'Nom du groupe', 'اسم المجموعة'); ?></label>
                                <input type="text" id="biz-grouped-name" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('Pack/kit name', 'Nom du pack/kit', 'اسم الحزمة/الطقم')); ?>" required>
                            </div>
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Group SKU', 'SKU du groupe', 'SKU المجموعة'); ?></label>
                                <input type="text" id="biz-grouped-sku" class="biz-input" placeholder="<?php echo esc_attr(bizmart_text('GROUP-SKU', 'SKU-GROUPE', 'SKU-المجموعة')); ?>" required>
                            </div>
                        </div>

                        <div class="biz-form-group">
                            <label><?php bizmart_e('Description', 'Description', 'الوصف'); ?></label>
                            <textarea id="biz-grouped-description" class="biz-textarea biz-textarea-variable-desc" placeholder="<?php echo esc_attr(bizmart_text('Pack description...', 'Description du pack...', 'وصف الحزمة...')); ?>"></textarea>
                        </div>

                        <div class="biz-form-group">
                            <label><?php bizmart_e('Included products', 'Produits inclus', 'المنتجات المضمنة'); ?></label>
                            <div style="max-height: 120px; overflow-y: auto; border: 0.5px solid var(--biz-border); border-radius: 8px; padding: 10px; background: var(--biz-bg-input);">
                                <?php foreach ($simple_products as $product): ?>
                                    <label style="display: flex; align-items: center; margin-bottom: 6px; padding: 6px 8px; border-radius: 6px; background: #ffffff; border: 0.5px solid var(--biz-border); font-size: 12px; cursor: pointer;">
                                        <input type="checkbox" value="<?php echo esc_attr($product->get_id()); ?>" class="biz-grouped-product" style="margin-right: 8px;">
                                        <strong style="color: #0f172a;"><?php echo esc_html($product->get_name()); ?></strong>
                                        <span style="color: var(--biz-text-muted); margin-left: auto; font-weight: 600; font-size: 11px;"><?php echo wp_kses_post(wc_price($product->get_price())); ?></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="biz-sticky-save-bar" style="display: flex; gap: 12px; margin-top: 20px; align-items: center; border-top: 1px solid var(--biz-border); padding-top: 16px;">
                        <button type="button" class="biz-btn biz-btn-success" onclick="BizProducts.createFromActiveTab()">
                            <span style="font-size: 16px;">📦</span>
                            <?php bizmart_e('Create product', 'Créer le produit', 'إنشاء المنتج'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" onclick="BizProducts.resetForm('grouped')">
                            <?php bizmart_e('↻ Reset', '↻ Réinitialiser', '↻ إعادة تعيين'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" onclick="BizProducts.saveProduct('draft'); return false;">
                            <?php bizmart_e('💾 Save draft', '💾 Enregistrer brouillon', '💾 حفظ كمسودة'); ?>
                        </button>
                    </div>
                </form>
            </div>

            <!-- External Product Tab -->
            <div id="biz-tab-external" class="biz-tab-content">
                <form id="biz-form-external">
                    <div class="biz-zw-section">
                        <h3 class="biz-section-title"><?php bizmart_e('🔗 External Product', '🔗 Produit Externe', '🔗 منتج خارجي'); ?></h3>
                        <p style="color: #6b7280; margin-bottom: 10px; font-size: 11px; margin-top: 0; line-height: 1.3;"><?php bizmart_e('Redirect customers to an external site to purchase', "Redirigez les clients vers un site externe pour l'achat", 'إعادة توجيه العملاء إلى موقع خارجي للشراء'); ?></p>

                        <div class="biz-zw-grid-2-2" style="margin-bottom: 10px;">
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Product name', 'Nom du produit', 'اسم المنتج'); ?></label>
                                <input type="text" id="biz-external-name" class="biz-input biz-zw-input" placeholder="<?php echo esc_attr(bizmart_text('External product name', 'Nom du produit externe', 'اسم المنتج الخارجي')); ?>" required>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('SKU', 'SKU', 'رمز المنتج'); ?></label>
                                <input type="text" id="biz-external-sku" class="biz-input biz-zw-input" placeholder="<?php echo esc_attr(bizmart_text('EXT-SKU', 'SKU-EXT', 'SKU-خارجي')); ?>">
                            </div>
                        </div>

                        <div class="biz-zw-grid-2-2" style="margin-bottom: 10px;">
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Product URL', 'URL du produit', 'رابط المنتج'); ?></label>
                                <input type="url" id="biz-external-url" class="biz-input biz-zw-input" placeholder="https://..." required>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Button text', 'Texte du bouton', 'نص الزر'); ?></label>
                                <input type="text" id="biz-external-button-text" class="biz-input biz-zw-input" placeholder="<?php echo esc_attr(bizmart_text('Buy now', 'Acheter maintenant', 'اشتر الآن')); ?>">
                            </div>
                        </div>

                        <div class="biz-zw-grid-2" style="margin-bottom: 10px;">
                            <div class="biz-form-group">
                                <label><?php echo esc_html(sprintf(bizmart_text('Price (%s)', 'Prix (%s)', 'السعر (%s)'), bizmart_get_currency_symbol())); ?></label>
                                <div class="biz-zw-input-prefix-wrapper">
                                    <span class="biz-input-prefix">$</span>
                                    <input type="number" step="0.01" min="0" id="biz-external-price" class="biz-input biz-zw-input" placeholder="0.00">
                                </div>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Category', 'Catégorie', 'الفئة'); ?></label>
                                <select id="biz-external-category" class="biz-select biz-zw-input">
                                    <option value=""><?php bizmart_e('Select a category', 'Sélectionner une catégorie', 'اختر فئة'); ?></option>
                                    <?php foreach ($product_categories as $category): ?>
                                        <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="biz-form-group" style="margin-bottom: 10px;">
                            <label><?php bizmart_e('Description', 'Description', 'الوصف'); ?></label>
                            <textarea id="biz-external-description" class="biz-textarea biz-zw-textarea" placeholder="<?php echo esc_attr(bizmart_text('External product description...', 'Description du produit externe...', 'وصف المنتج الخارجي...')); ?>"></textarea>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="biz-sticky-save-bar" style="display: flex; gap: 12px; margin-top: 10px; align-items: center; border-top: 1px solid var(--biz-border); padding-top: 10px;">
                        <button type="button" class="biz-btn biz-btn-success" style="height: 32px !important; font-size: 13px !important;" onclick="BizProducts.createFromActiveTab()">
                            <span style="font-size: 15px;">🔗</span>
                            <?php bizmart_e('Create product', 'Créer le produit', 'إنشاء المنتج'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" style="height: 32px !important; font-size: 13px !important;" onclick="BizProducts.resetForm('external')">
                            <?php bizmart_e('↻ Reset', '↻ Réinitialiser', '↻ إعادة تعيين'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" style="height: 32px !important; font-size: 13px !important;" onclick="BizProducts.saveProduct('draft'); return false;">
                            <?php bizmart_e('💾 Save draft', '💾 Enregistrer brouillon', '💾 حفظ كمسودة'); ?>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Digital Product Tab -->
            <div id="biz-tab-digital" class="biz-tab-content">
                <form id="biz-form-digital">
                    <div class="biz-zw-section">
                        <h3 class="biz-section-title"><?php bizmart_e('💾 Digital Product', '💾 Produit Numérique', '💾 منتج رقمي'); ?></h3>
                        <p style="color: #6b7280; margin-bottom: 10px; font-size: 11px; margin-top: 0; line-height: 1.3;"><?php bizmart_e('Downloadable products with digital files', 'Produits téléchargeables avec fichiers numériques', 'منتجات قابلة للتحميل مع ملفات رقمية'); ?></p>

                        <div class="biz-zw-grid-2-2" style="margin-bottom: 10px;">
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Product name', 'Nom du produit', 'اسم المنتج'); ?></label>
                                <input type="text" id="biz-digital-name" class="biz-input biz-zw-input" placeholder="<?php echo esc_attr(bizmart_text('Digital product name', 'Nom du produit numérique', 'اسم المنتج الرقمي')); ?>" required>
                            </div>
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('SKU', 'SKU', 'رمز المنتج'); ?></label>
                                <input type="text" id="biz-digital-sku" class="biz-input biz-zw-input" placeholder="<?php echo esc_attr(bizmart_text('DIGITAL-SKU', 'SKU-DIGITAL', 'SKU-رقمي')); ?>" required>
                            </div>
                        </div>

                        <div class="biz-zw-grid-3" style="margin-bottom: 10px;">
                            <div class="biz-form-group">
                                <label class="required"><?php bizmart_e('Regular price', 'Prix régulier', 'السعر العادي'); ?></label>
                                <div class="biz-zw-input-prefix-wrapper">
                                    <span class="biz-input-prefix">$</span>
                                    <input type="number" step="0.01" min="0" id="biz-digital-regular-price" class="biz-input biz-zw-input" placeholder="0.00" required>
                                </div>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Sale price', 'Prix promotionnel', 'سعر التخفيض'); ?></label>
                                <div class="biz-zw-input-prefix-wrapper">
                                    <span class="biz-input-prefix">$</span>
                                    <input type="number" step="0.01" min="0" id="biz-digital-sale-price" class="biz-input biz-zw-input" placeholder="0.00">
                                </div>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Cost price', "Prix d'achat", 'سعر التكلفة'); ?></label>
                                <div class="biz-zw-input-prefix-wrapper">
                                    <span class="biz-input-prefix">$</span>
                                    <input type="number" step="0.01" min="0" id="biz-digital-cost-price" class="biz-input biz-zw-input" placeholder="0.00">
                                </div>
                            </div>
                        </div>

                        <div class="biz-form-group" style="margin-bottom: 10px;">
                            <label><?php bizmart_e('Downloadable files', 'Fichiers téléchargeables', 'ملفات قابلة للتحميل'); ?></label>
                            <div class="biz-zw-upload-area" onclick="BizProducts.openFileUploader()">
                                <div class="biz-upload-icon">📎</div>
                                <p class="biz-upload-label"><?php bizmart_e('Click to add files · PDF, ZIP, MP3, etc.', 'Cliquez pour ajouter des fichiers · PDF, ZIP, MP3, etc.', 'انقر لإضافة ملفات · PDF، ZIP، MP3، إلخ.'); ?></p>
                            </div>
                            <div class="biz-gallery-images" id="biz-digital-files-list" style="margin-top: 6px;"></div>
                            <input type="hidden" id="biz-digital-file-ids">
                        </div>

                        <div class="biz-zw-grid-2" style="margin-bottom: 10px;">
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Download limit', 'Limite de téléchargement', 'حد التحميل'); ?></label>
                                <input type="number" min="0" id="biz-digital-download-limit" class="biz-input biz-zw-input" placeholder="<?php echo esc_attr(bizmart_text('Unlimited', 'Illimité', 'غير محدود')); ?> (<?php bizmart_e('Number of allowed downloads', 'Nombre de téléchargements autorisés', 'عدد التحميلات المسموح بها'); ?>)">
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Expiration (days)', 'Expiration (jours)', 'انتهاء الصلاحية (أيام)'); ?></label>
                                <input type="number" min="0" id="biz-digital-download-expiry" class="biz-input biz-zw-input" placeholder="<?php echo esc_attr(bizmart_text('Never', 'Jamais', 'أبدًا')); ?> (<?php bizmart_e('How long the link remains valid', 'Durée de validité du lien', 'مدة صلاحية الرابط'); ?>)">
                            </div>
                        </div>

                        <div class="biz-zw-grid-2" style="margin-bottom: 10px;">
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Category', 'Catégorie', 'الفئة'); ?></label>
                                <select id="biz-digital-category" class="biz-select biz-zw-input">
                                    <option value=""><?php bizmart_e('Select a category', 'Sélectionner une catégorie', 'اختر فئة'); ?></option>
                                    <?php foreach ($product_categories as $category): ?>
                                        <option value="<?php echo intval($category->term_id); ?>"><?php echo esc_html($category->name); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="biz-form-group">
                                <label><?php bizmart_e('Description', 'Description', 'الوصف'); ?></label>
                                <textarea id="biz-digital-description" class="biz-textarea biz-zw-textarea" placeholder="<?php echo esc_attr(bizmart_text('Digital product description...', 'Description du produit numérique...', 'وصف المنتج الرقمي...')); ?>"></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="biz-sticky-save-bar" style="display: flex; gap: 12px; margin-top: 10px; align-items: center; border-top: 1px solid var(--biz-border); padding-top: 10px;">
                        <button type="button" class="biz-btn biz-btn-success" style="height: 32px !important; font-size: 13px !important;" onclick="BizProducts.createFromActiveTab()">
                            <span style="font-size: 15px;">💾</span>
                            <?php bizmart_e('Create product', 'Créer le produit', 'إنشاء المنتج'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" style="height: 32px !important; font-size: 13px !important;" onclick="BizProducts.resetForm('digital')">
                            <?php bizmart_e('↻ Reset', '↻ Réinitialiser', '↻ إعادة تعيين'); ?>
                        </button>
                        <button type="button" class="biz-btn biz-btn-ghost" style="height: 32px !important; font-size: 13px !important;" onclick="BizProducts.saveProduct('draft'); return false;">
                            <?php bizmart_e('💾 Save draft', '💾 Enregistrer brouillon', '💾 حفظ كمسودة'); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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

    window.BizProducts = {
        adminLang: '<?php echo esc_js(function_exists('bizmart_admin_lang') ? bizmart_admin_lang() : 'en'); ?>',
        t: function(en, fr, ar) {
            if (this.adminLang === 'ar') {
                const dict = (window.BizmartI18n && BizmartI18n.ar) ? BizmartI18n.ar : null;
                return ar || (dict && dict[en]) || en;
            }
            return (this.adminLang === 'fr') ? (fr || en) : en;
        },
        nonce: '<?php echo esc_attr(wp_create_nonce("bizmart-analytics-nonce")); ?>',
        tags: { simple: [], variable: [], external: [], digital: [], grouped: [] },
        isCreating: false,
        nextStatus: null,
        actionButtons: {},
        currentFooterTab: null,
        availableAttributeTerms: {},

        init: function() {
            try {
                this.bindEvents();
                this.initializeTagInputs();
                this.setupStockManagement();
                this.setupActionFooter();
                this.renderAttributeTermOptions(1, []);
                console.log('BizProducts initialized successfully');
                if (typeof this.showNotification === 'function') {
                    this.showNotification(this.t('BizProducts ready — enhanced UI active', 'BizProducts prêt — UI améliorée active', 'تم تجهيز BizProducts — الواجهة المحسّنة نشطة'), 'success');
                }
            } catch (e) {
                console.error('Error in BizProducts.init:', e);
            }
        },

        bindEvents: function() {
            // Tab switching
            $(document).on('click', '.biz-tab', function() {
                const tab = $(this).data('tab');
                if (tab) BizProducts.switchTab(tab);
            });

            // Toggle sections
            $(document).on('click', '.biz-toggle-section', function() {
                const target = $(this).attr('onclick');
                if (target) {
                    const match = target.match(/'([^']+)'/);
                    if (match) {
                        BizProducts.toggleSection(match[1]);
                    }
                }
            });

            // Attribute value input (add on Enter)
            $(document).on('keypress', '.biz-attribute-values-input', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    const rowId = $(this).closest('.biz-attribute-row').data('id');
                    const value = $(this).val();
                    BizProducts.insertAttributeTag(rowId, value);
                    $(this).val('');
                }
            });

            // Add single term from picker
            $(document).on('click', '.biz-attr-term-option', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const rowId = $(this).data('row');
                const value = $(this).data('value');
                if (rowId && value) {
                    BizProducts.insertAttributeTag(rowId, value);
                }
            });

            // Add all existing terms
            $(document).on('click', '.biz-attr-term-add-all', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const rowId = $(this).data('row');
                if (rowId) {
                    BizProducts.addAllAttributeTerms(rowId);
                }
            });

            // Remove attribute tag - ROBUST VERSION
            $(document).on('click', '.biz-tag-remove', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                const $tag = $(this).closest('.biz-tag');
                const $row = $tag.closest('.biz-attribute-row');
                const rowId = $row.data('id');
                
                // Only proceed if it's an attribute row (has rowId)
                if (rowId) {
                    // Get the value being removed
                    const value = $tag.attr('data-value') || $tag.contents().filter(function() {
                        return this.nodeType === 3; // Text nodes only
                    }).text().trim();
                    
                    // Remove the tag
                    $tag.remove();
                    
                    // Update the hidden input
                    if (typeof BizProducts.updateAttributeValues === 'function') {
                        BizProducts.updateAttributeValues(rowId);
                    }
                    
                    // Re-enable the term in the picker
                    const $picker = $(`.biz-attribute-term-picker[data-row="${rowId}"]`);
                    $picker.find('.biz-attr-term-option').each(function() {
                        const $btn = $(this);
                        const btnValue = $btn.data('value');
                        // Loose comparison for safety
                        if (btnValue && value && btnValue.toString().toLowerCase() === value.toString().toLowerCase()) {
                            $btn.prop('disabled', false).css('opacity', '1');
                        }
                    });
                } else {
                    // It might be a product tag (not attribute)
                    // The inline onclick handler handles those, but we prevent bubbling here
                    // so we don't need to do anything else.
                }
            });
        },

        switchTab: function(tab) {
            $('.biz-tab').removeClass('active');
            $(`.biz-tab[data-tab="${tab}"]`).addClass('active');

            $('.biz-tab-content').removeClass('active');
            $(`#biz-tab-${tab}`).addClass('active');

            this.renderFooterActions(tab);

            // Safety: if buttons were moved while a previous action disabled them,
            // restore clickability when not creating.
            if (!this.isCreating && typeof this.enableProductButtons === 'function') {
                this.enableProductButtons();
            }
        },

        toggleSection: function(targetId) {
            const $content = $(`#${targetId}`);
            const $toggle = $content.prev('.biz-toggle-section').find('span');

            if ($content.hasClass('show')) {
                $content.removeClass('show');
                $toggle.text('▼');
            } else {
                $content.addClass('show');
                $toggle.text('▲');
            }
        },

        toggleShippingSection: function(isVirtual) {
            const $section = $('#biz-simple-shipping-section');
            if (isVirtual) {
                $section.removeClass('show');
            } else {
                $section.addClass('show');
            }
        },

        initializeTagInputs: function() {
            ['simple', 'variable', 'external', 'digital', 'grouped'].forEach(type => {
                $(`#biz-${type}-tags-input`).on('keypress', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        const tag = $(this).val().trim();
                        if (tag && !BizProducts.tags[type].includes(tag)) {
                            BizProducts.tags[type].push(tag);
                            BizProducts.addTagElement(type, tag);
                            $(this).val('');
                        }
                    }
                });
            });
        },

        addTagElement: function(type, tag) {
            const $container = $(`#biz-${type}-tags-container`);
            const $tagElement = $(`
                <span class="biz-tag">
                    ${tag}
                    <span class="biz-tag-remove" onclick="BizProducts.removeTag('${type}', '${tag}')">×</span>
                </span>
            `);
            $container.prepend($tagElement);
            $(`#biz-${type}-tags`).val(BizProducts.tags[type].join(','));
        },

        removeTag: function(type, tag) {
            BizProducts.tags[type] = BizProducts.tags[type].filter(t => t !== tag);
            $(`#biz-${type}-tags`).val(BizProducts.tags[type].join(','));
            // Remove the tag element
            $(`#biz-${type}-tags-container .biz-tag`).filter(function() {
                return $(this).contents().first().text().trim() === tag;
            }).remove();
        },

        setupStockManagement: function() {
            $('#biz-simple-manage-stock').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#biz-simple-stock-quantity-group').show();
                } else {
                    $('#biz-simple-stock-quantity-group').hide();
                }
            });
        },

        insertAttributeTag: function(rowId, value) {
            const val = (value || '').trim();
            if (!val) return;

            const $container = $(`#biz-attribute-values-${rowId}`);
            if (!$container.length) return;

            // Check for duplicates (case-insensitive)
            let exists = false;
            $container.find('.biz-tag').each(function() {
                const tagText = $(this).contents().filter(function() {
                    return this.nodeType === 3; // Text nodes only
                }).text().trim();
                
                if (tagText.toLowerCase() === val.toLowerCase()) {
                    exists = true;
                    return false;
                }
            });
            
            if (exists) {
                console.log('Tag already exists:', val);
                return;
            }

            // Create the tag element WITHOUT inline onclick
            const $tagElement = $(`
                <span class="biz-tag" data-value="${val.replace(/"/g, '&quot;')}">
                    ${val}
                    <span class="biz-tag-remove">×</span>
                </span>
            `);
            
            $container.prepend($tagElement);
            this.updateAttributeValues(rowId);
            
            // Disable the corresponding term in the picker
            this.disableTermInPicker(rowId, val);
        },

        disableTermInPicker: function(rowId, termValue) {
            const $picker = $(`.biz-attribute-term-picker[data-row="${rowId}"]`);
            if (!$picker.length) return;
            
            $picker.find('.biz-attr-term-option').each(function() {
                const $button = $(this);
                const buttonValue = $button.data('value');
                if (buttonValue && buttonValue === termValue) {
                    $button.prop('disabled', true).css('opacity', '0.5');
                }
            });
        },

        enableTermInPicker: function(rowId, termValue) {
            const $picker = $(`.biz-attribute-term-picker[data-row="${rowId}"]`);
            if (!$picker.length) return;
            
            $picker.find('.biz-attr-term-option').each(function() {
                const $button = $(this);
                const buttonValue = $button.data('value');
                if (buttonValue && buttonValue.toLowerCase() === termValue.toLowerCase()) {
                    $button.prop('disabled', false).css('opacity', '1');
                }
            });
        },

        renderAttributeTermOptions: function(rowId, terms) {
            const $picker = $(`.biz-attribute-term-picker[data-row="${rowId}"]`);
            if (!$picker.length) return;

            // Store available terms
            this.availableAttributeTerms[rowId] = terms || [];

            // Get current selected values to disable them in the picker
            const selectedValues = [];
            const $row = $(`.biz-attribute-row[data-id="${rowId}"]`);
            $row.find('.biz-tag').each(function() {
                const tagText = $(this).contents().filter(function() {
                    return this.nodeType === 3; // Text nodes only
                }).text().trim();
                if (tagText) selectedValues.push(tagText);
            });

            if (!terms || terms.length === 0) {
                $picker.html('<span class="biz-attribute-term-picker-empty">Aucune valeur existante</span>');
                return;
            }

            // Build the picker buttons
            let buttonsHtml = '';
            
            // "Add all" button
            buttonsHtml += `<button type="button" class="biz-attr-term-add-all" data-row="${rowId}">${BizProducts.t('Add all values', 'Ajouter toutes les valeurs')}</button>`;
            
            // Individual term buttons
            terms.forEach(term => {
                const termName = term.name || term;
                const isSelected = selectedValues.some(v => v.toLowerCase() === termName.toLowerCase());
                const disabledAttr = isSelected ? 'disabled' : '';
                const opacityStyle = isSelected ? 'style="opacity: 0.5;"' : '';
                
                buttonsHtml += `
                    <button type="button" class="biz-attr-term-option" 
                            data-row="${rowId}" 
                            data-value="${termName.replace(/"/g, '&quot;')}"
                            ${disabledAttr}
                            ${opacityStyle}>
                        ${termName}
                    </button>
                `;
            });

            $picker.html(buttonsHtml);
        },

        addAllAttributeTerms: function(rowId) {
            const terms = this.availableAttributeTerms[rowId] || [];
            const $picker = $(`.biz-attribute-term-picker[data-row="${rowId}"]`);
            
            if (terms.length === 0) {
                console.log('No terms to add');
                return;
            }
            
            // Disable all term buttons immediately
            $picker.find('.biz-attr-term-option').prop('disabled', true).css('opacity', '0.5');
            
            // Add each term
            terms.forEach(term => {
                const termName = term.name || term;
                this.insertAttributeTag(rowId, termName);
            });
        },

        setupActionFooter: function() {
            const $slot = $('#biz-product-footer-actions');
            if (!$slot.length) {
                return;
            }

            // Rebuild the map every time to avoid stale/partial state
            this.actionButtons = {};

            // Capture action blocks from anywhere (inside modal content or already in footer)
            const $blocks = $('.biz-action-buttons');
            $blocks.each(function() {
                const $block = $(this);
                const tab = ($block.attr('data-tab') || '').toString().trim();
                if (tab) {
                    BizProducts.actionButtons[tab] = $block.detach();
                }
            });

            // Render actions for current active tab if possible
            const $active = $('.biz-tab-content.active').attr('id') || '';
            const match = $active.match(/^biz-tab-(.+)$/);
            const activeTab = match ? match[1] : 'simple';
            this.currentFooterTab = null;
            this.renderFooterActions(activeTab);

            if (!this.isCreating && typeof this.enableProductButtons === 'function') {
                this.enableProductButtons();
            }
        },

        renderFooterActions: function(tab) {
            const $slot = $('#biz-product-footer-actions');
            if (!$slot.length || !this.actionButtons) {
                return;
            }

            const targetTab = tab || 'simple';

            // If we don't have the target yet, attempt to capture it from DOM
            if (!this.actionButtons[targetTab]) {
                const $block = $(`.biz-action-buttons[data-tab="${targetTab}"]`);
                if ($block.length) {
                    this.actionButtons[targetTab] = $block.detach();
                }
            }

            // Don't clear the footer if we still can't find actions
            if (!this.actionButtons[targetTab]) {
                return;
            }

            if (this.currentFooterTab && this.currentFooterTab !== targetTab && this.actionButtons[this.currentFooterTab]) {
                this.actionButtons[this.currentFooterTab].detach();
            }

            const $buttons = this.actionButtons[targetTab];
            if ($buttons && !$buttons.parent().is($slot)) {
                $slot.prepend($buttons);
            }

            // Keep enabled/disabled UI consistent after moving DOM nodes
            if (typeof this.disableProductButtons === 'function' && typeof this.enableProductButtons === 'function') {
                if (this.isCreating) this.disableProductButtons();
                else this.enableProductButtons();
            }

            this.currentFooterTab = targetTab;
        },

        createCategory: function(type) {
            const categoryName = $(`#biz-${type}-new-category`).val().trim();
            if (!categoryName) return;

            $.ajax({
                url: window.BizmartInvoices.config.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'bizmart_create_product_category',
                    nonce: window.BizmartInvoices.config.nonce,
                    name: categoryName
                },
                success: function(response) {
                    if (response.success) {
                        const option = `<option value="${response.data.id}" selected>${response.data.name}</option>`;
                        $(`#biz-${type}-categories`).append(option);
                        $(`#biz-${type}-new-category`).val('');
                        BizProducts.showNotification(BizProducts.t('Category created successfully!', 'Catégorie créée avec succès!'), 'success');
                    } else {
                        BizProducts.showNotification(BizProducts.t('Error creating category', 'Erreur lors de la création de la catégorie'), 'error');
                    }
                }
            });
        },

        openMediaUploader: function(inputId, previewId) {
            const mediaUploader = wp.media({
                title: BizProducts.t('Choose an image', 'Choisir une image'),
                button: { text: BizProducts.t('Use this image', 'Utiliser cette image') },
                multiple: false
            });

            mediaUploader.on('select', function() {
                const attachment = mediaUploader.state().get('selection').first().toJSON();
                $(`#${inputId}`).val(attachment.id);
                $(`#${previewId}`).attr('src', attachment.url).show();
            });

            mediaUploader.open();
        },

        openGalleryUploader: function(type) {
            const mediaUploader = wp.media({
                title: BizProducts.t('Choose images', 'Choisir des images'),
                button: { text: BizProducts.t('Add to gallery', 'Ajouter à la galerie') },
                multiple: true
            });

            mediaUploader.on('select', function() {
                const attachments = mediaUploader.state().get('selection').toJSON();
                const ids = attachments.map(att => att.id);
                const currentIds = $(`#biz-${type}-gallery-ids`).val();
                const allIds = currentIds ? currentIds + ',' + ids.join(',') : ids.join(',');

                $(`#biz-${type}-gallery-ids`).val(allIds);

                attachments.forEach(att => {
                    const $img = $(`<img src="${att.url}" style="width: 80px; height: 80px; object-fit: cover; border-radius: 6px; margin: 4px;">`);
                    $(`#biz-${type}-gallery`).append($img);
                });
            });

            mediaUploader.open();
        },

        openFileUploader: function() {
            const mediaUploader = wp.media({
                title: BizProducts.t('Choose files', 'Choisir des fichiers'),
                button: { text: BizProducts.t('Add files', 'Ajouter les fichiers') },
                multiple: true,
                library: { type: '' }
            });

            mediaUploader.on('select', function() {
                const attachments = mediaUploader.state().get('selection').toJSON();
                const ids = attachments.map(att => att.id);
                const currentIds = $('#biz-digital-file-ids').val();
                const allIds = currentIds ? currentIds + ',' + ids.join(',') : ids.join(',');

                $('#biz-digital-file-ids').val(allIds);

                attachments.forEach(att => {
                    const $file = $(`
                        <div style="display: flex; align-items: center; gap: 8px; padding: 8px; background: #f9fafb; border-radius: 6px; margin-bottom: 8px;">
                            <span style="font-size: 20px;">📄</span>
                            <span>${att.filename}</span>
                            <button type="button" onclick="$(this).parent().remove()" style="margin-left: auto; background: #ef4444; color: white; border: none; border-radius: 4px; padding: 4px 8px; cursor: pointer;">×</button>
                        </div>
                    `);
                    $('#biz-digital-files-list').append($file);
                });
            });

            mediaUploader.open();
        },

        onExistingAttributeSelect: function(select) {
            const $select = $(select);
            const $row = $select.closest('.biz-attribute-row');
            const rowId = $row.data('id');
            const attributeSlug = $select.val();
            
            if (attributeSlug === 'new') {
                // Show the manual attribute name input
                $row.find('.attribute-name').show().focus();
                $row.find('.biz-attribute-values-input').prop('disabled', false);
                BizProducts.renderAttributeTermOptions(rowId, []);
                return;
            }
            
            if (attributeSlug) {
                // Get the selected attribute label
                const selectedOption = $select.find('option:selected');
                const attributeLabel = selectedOption.data('label') || attributeSlug;
                
                // Set the attribute name
                $row.find('.attribute-name').val(attributeLabel).show();
                
                const $picker = $(`.biz-attribute-term-picker[data-row="${rowId}"]`);
                if ($picker.length) {
                    $picker.html(`<span class="biz-attribute-term-picker-empty">${BizProducts.t('Loading values...', 'Chargement des valeurs...')}</span>`);
                }
                
                // Fetch existing terms for this attribute via AJAX
                $.ajax({
                    url: window.BizmartInvoices.config.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'bizmart_get_attribute_terms',
                        nonce: window.BizmartInvoices.config.nonce,
                        attribute_name: attributeSlug
                    },
                    success: function(response) {
                        if (response.success) {
                            // Reset current tags to avoid duplicates
                            $row.find('.biz-tag').remove();
                            BizProducts.updateAttributeValues(rowId);

                            // Render available terms as buttons
                            const terms = (response.data && response.data.terms) ? response.data.terms : [];
                            BizProducts.renderAttributeTermOptions(rowId, terms);

                            // Enable adding new terms
                            $row.find('.biz-attribute-values-input').prop('disabled', false);
                        } else {
                            BizProducts.renderAttributeTermOptions(rowId, []);
                            $row.find('.biz-attribute-values-input').prop('disabled', false);
                        }
                    }
                });
            } else {
                // Clear if "Choose existing attribute" is selected
                $row.find('.attribute-name').val('');
                $row.find('.biz-attribute-values-input').siblings('.biz-tag').remove();
                $row.find('.biz-attribute-values-input').prop('disabled', true);
                BizProducts.renderAttributeTermOptions(rowId, []);
                BizProducts.updateAttributeValues(rowId);
            }
        },

        updateAttributeValues: function(rowId) {
            const $row = $(`.biz-attribute-row[data-id="${rowId}"]`);
            if (!$row.length) return;
            
            const tags = [];
            $row.find('.biz-tag').each(function() {
                const tagText = $(this).contents().filter(function() {
                    return this.nodeType === 3; // Text nodes only
                }).text().trim();
                if (tagText) tags.push(tagText);
            });
            
            $(`#biz-attribute-values-hidden-${rowId}`).val(tags.join(','));
            
            // Update the attribute term picker state
            const selectedValues = tags.map(v => v.toLowerCase());
            const $picker = $(`.biz-attribute-term-picker[data-row="${rowId}"]`);
            $picker.find('.biz-attr-term-option').each(function() {
                const $btn = $(this);
                const btnValue = $btn.data('value');
                const isSelected = selectedValues.includes(btnValue.toLowerCase());
                $btn.prop('disabled', isSelected).css('opacity', isSelected ? '0.5' : '1');
            });
        },

        addAttribute: function() {
            const $attributes = $('#biz-variable-attributes');
            const attrCount = $attributes.children().length + 1;

            // Get existing attributes for the dropdown
            let existingAttributesOptions = '';
            <?php
            $attribute_taxonomies = wc_get_attribute_taxonomies();
            foreach ($attribute_taxonomies as $tax) {
                echo "existingAttributesOptions += '<option value=\"" . esc_attr($tax->attribute_name) . "\" data-label=\"" . esc_attr($tax->attribute_label) . "\">" . esc_html($tax->attribute_label) . "</option>';";
            }
            ?>
            
            const $attribute = $(`
                <div class="biz-attribute-row" data-id="${attrCount}">
                    <div class="biz-form-grid-2">
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Select an existing attribute', 'Sélectionner un attribut existant')}</label>
                            <select class="biz-select existing-attribute-select" onchange="BizProducts.onExistingAttributeSelect(this)">
                                <option value="">${BizProducts.t('-- Choose an existing attribute --', '-- Choisir un attribut existant --')}</option>
                                ${existingAttributesOptions}
                                <option value="new">${BizProducts.t('+ Create a new attribute', '+ Créer un nouvel attribut')}</option>
                            </select>
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Or create a new attribute', 'Ou créer un nouvel attribut')}</label>
                            <input type="text" class="biz-input attribute-name" placeholder="${BizProducts.t('Attribute name (e.g., Color, Size)', "Nom de l'attribut (ex: Couleur, Taille)")}" style="display: none;">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Attribute values', "Valeurs de l'attribut")}</label>
                            <div class="biz-tag-input" id="biz-attribute-values-${attrCount}">
                                <input type="text" class="biz-attribute-values-input" placeholder="${BizProducts.t('Add a value, press Enter', 'Ajouter une valeur, appuyez sur Entrée')}">
                            </div>
                            <input type="hidden" class="attribute-values" id="biz-attribute-values-hidden-${attrCount}">
                            <div class="biz-attribute-term-picker" data-row="${attrCount}"></div>
                            <small style="color: #6b7280;">${BizProducts.t('Separate values with commas or add them one by one', 'Séparer les valeurs par des virgules ou ajoutez-les une par une')}</small>
                        </div>
                    </div>
                    <div class="biz-form-grid-3">
                        <div class="biz-form-group">
                            <label style="display: flex; align-items: center; cursor: pointer;">
                                <span class="biz-switch">
                                    <input type="checkbox" class="attribute-visible" checked>
                                    <span class="biz-slider"></span>
                                </span>
                                ${BizProducts.t('Visible on the product page', 'Visible sur la page produit')}
                            </label>
                        </div>
                        <div class="biz-form-group">
                            <label style="display: flex; align-items: center; cursor: pointer;">
                                <span class="biz-switch">
                                    <input type="checkbox" class="attribute-variation" checked>
                                    <span class="biz-slider"></span>
                                </span>
                                ${BizProducts.t('Used for variations', 'Utilisé pour les variations')}
                            </label>
                        </div>
                        <button type="button" class="biz-btn" onclick="$(this).closest('.biz-attribute-row').remove()">${BizProducts.t('Remove', 'Supprimer')}</button>
                    </div>
                </div>
            `);
            
            $attributes.append($attribute);

            // Initialize tag input for manual entry
            $(`#biz-attribute-values-${attrCount} .biz-attribute-values-input`).on('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    const value = $(this).val().trim();
                    if (value) {
                        const rowId = $(this).closest('.biz-attribute-row').data('id');
                        BizProducts.insertAttributeTag(rowId, value);
                        $(this).val('');
                    }
                }
            });

            this.renderAttributeTermOptions(attrCount, []);
        },

        generateVariations: function() {
            // Collect all attributes
            const attributes = [];
            $('.biz-attribute-row').each(function() {
                const name = $(this).find('.attribute-name').val();
                const rowId = $(this).data('id');

                // Values are maintained by the tag UI into this hidden field.
                // The legacy .attribute-values field may be empty.
                let valuesInput = '';
                if (rowId !== undefined && rowId !== null && rowId !== '') {
                    const $hidden = $('#biz-attribute-values-hidden-' + rowId);
                    if ($hidden.length) {
                        valuesInput = $hidden.val() || '';
                    }
                }
                if (!valuesInput) {
                    valuesInput = $(this).find('.attribute-values').val() || '';
                }

                const values = valuesInput
                    ? valuesInput.split(',').map(v => String(v).trim()).filter(v => v)
                    : [];
                const isVariation = $(this).find('.attribute-variation').is(':checked');

                if (name && values.length > 0 && isVariation) {
                    attributes.push({
                        name: name,
                        values: values
                    });
                }
            });

            if (attributes.length === 0) {
                BizProducts.showNotification(
                    BizProducts.t('Please define attributes for variations first', 'Veuillez d\'abord définir des attributs pour les variations'),
                    'error'
                );
                return;
            }

            // Generate all combinations
            const combinations = BizProducts.generateCombinations(attributes);
            BizProducts.createVariationRows(combinations);
        },

        generateCombinations: function(attributes) {
            if (attributes.length === 0) return [];

            const combinations = [[]];

            attributes.forEach(attr => {
                const newCombinations = [];
                combinations.forEach(comb => {
                    attr.values.forEach(value => {
                        newCombinations.push([...comb, { name: attr.name, value: value }]);
                    });
                });
                combinations.length = 0;
                combinations.push(...newCombinations);
            });

            return combinations;
        },

        createVariationRows: function(combinations) {
            const $container = $('#biz-variations-container');
            $container.empty();

            combinations.forEach((comb, index) => {
                const attributesStr = comb.map(attr => `${attr.name}|${attr.value}`).join(', ');

                const $variation = $(`
                    <div class="biz-variation-row">
                        <h4>${BizProducts.t('Variation', 'Variation')} ${index + 1}: ${attributesStr}</h4>
                        <input type="hidden" class="variation-attributes" value="${attributesStr}">
                        <div class="biz-form-grid-3">
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Regular price', 'Prix régulier')}</label>
                                <input type="number" step="0.01" min="0" class="biz-input variation-regular-price" placeholder="0.00">
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Sale price', 'Prix promotionnel')}</label>
                                <input type="number" step="0.01" min="0" class="biz-input variation-sale-price" placeholder="0.00">
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Cost price', "Prix d'achat")}</label>
                                <input type="number" step="0.01" min="0" class="biz-input variation-cost-price" placeholder="0.00">
                            </div>
                            <div class="biz-form-group">
                                <label>SKU</label>
                                <input type="text" class="biz-input variation-sku" placeholder="SKU-VAR-${index + 1}">
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Stock', 'Stock')}</label>
                                <input type="number" min="0" step="1" inputmode="numeric" pattern="[0-9]*" class="biz-input variation-stock" placeholder="0">
                            </div>
                            <div class="biz-form-group">
                                <label>${BizProducts.t('Image', 'Image')}</label>
                                <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('var-image-${index}', 'var-preview-${index}')" style="padding: 20px;">
                                    <div style="font-size: 24px; color: #9ca3af;">📷</div>
                                </div>
                                <input type="hidden" id="var-image-${index}">
                                <img id="var-preview-${index}" class="biz-image-preview" style="display: none;">
                            </div>
                        </div>
                        <div class="biz-form-group" style="border-top: 1px solid #e5e7eb; padding-top: 15px; margin-top: 10px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                                <label style="font-weight: 600;">🏷️ ${BizProducts.t('Variation Barcodes', 'Barcodes de la Variation')}</label>
                                <div style="display: flex; gap: 8px;">
                                    <button type="button" class="biz-btn biz-btn-secondary add-barcode-btn" data-product-type="variation" data-variation-row-id="${index + 1}" style="padding: 6px 12px; font-size: 12px;">➕ ${BizProducts.t('Add Barcode', 'Ajouter')}</button>
                                    <button type="button" class="biz-btn biz-btn-secondary generate-barcode-btn" data-product-type="variation" data-variation-row-id="${index + 1}" style="padding: 6px 12px; font-size: 12px;">⚡ ${BizProducts.t('Generate EAN-13', 'Générer EAN-13')}</button>
                                </div>
                            </div>
                            <div class="biz-barcodes-grid biz-barcodes-tbody" data-product-type="variation" data-variation-row-id="${index + 1}">
                                <div class="biz-no-barcodes-placeholder" style="text-align: center; color: #9ca3af; padding: 20px 0; grid-column: 1 / -1;">${BizProducts.t('No barcodes configured.', 'Aucun code-barres configuré.')}</div>
                            </div>
                        </div>
                        <button type="button" class="biz-btn" onclick="$(this).closest('.biz-variation-row').remove()" style="margin-top: 10px;">${BizProducts.t('Remove this variation', 'Supprimer cette variation')}</button>
                    </div>
                `);

                $container.append($variation);
            });
        },

        addVariation: function() {
            const $container = $('#biz-variations-container');
            const varCount = $container.children().length + 1;

            const $variation = $(`
                <div class="biz-variation-row">
                    <h4>${BizProducts.t('Variation', 'Variation')} ${varCount}</h4>
                    <div class="biz-form-grid-2" style="margin-bottom: 16px;">
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Attributes', 'Attributs')}</label>
                            <input type="text" class="biz-input variation-attributes" placeholder="${BizProducts.t('Color|Red, Size|M', 'Couleur|Rouge, Taille|M')}">
                        </div>
                    </div>
                    <div class="biz-form-grid-3">
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Regular price', 'Prix régulier')}</label>
                            <input type="number" step="0.01" min="0" class="biz-input variation-regular-price" placeholder="0.00">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Sale price', 'Prix promotionnel')}</label>
                            <input type="number" step="0.01" min="0" class="biz-input variation-sale-price" placeholder="0.00">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Cost price', "Prix d'achat")}</label>
                            <input type="number" step="0.01" min="0" class="biz-input variation-cost-price" placeholder="0.00">
                        </div>
                        <div class="biz-form-group">
                            <label>SKU</label>
                            <input type="text" class="biz-input variation-sku" placeholder="SKU-VAR-${varCount}">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Stock', 'Stock')}</label>
                            <input type="number" min="0" step="1" inputmode="numeric" pattern="[0-9]*" class="biz-input variation-stock" placeholder="0">
                        </div>
                        <div class="biz-form-group">
                            <label>${BizProducts.t('Image', 'Image')}</label>
                            <div class="biz-image-upload-area" onclick="BizProducts.openMediaUploader('var-image-${varCount}', 'var-preview-${varCount}')" style="padding: 20px;">
                                <div style="font-size: 24px; color: #9ca3af;">📷</div>
                            </div>
                            <input type="hidden" id="var-image-${varCount}">
                            <img id="var-preview-${varCount}" class="biz-image-preview" style="display: none;">
                        </div>
                    </div>
                    <div class="biz-form-group" style="border-top: 1px solid #e5e7eb; padding-top: 15px; margin-top: 10px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                            <label style="font-weight: 600;">🏷️ ${BizProducts.t('Variation Barcodes', 'Barcodes de la Variation')}</label>
                            <div style="display: flex; gap: 8px;">
                                <button type="button" class="biz-btn biz-btn-secondary add-barcode-btn" data-product-type="variation" data-variation-row-id="${varCount}" style="padding: 6px 12px; font-size: 12px;">➕ ${BizProducts.t('Add Barcode', 'Ajouter')}</button>
                                <button type="button" class="biz-btn biz-btn-secondary generate-barcode-btn" data-product-type="variation" data-variation-row-id="${varCount}" style="padding: 6px 12px; font-size: 12px;">⚡ ${BizProducts.t('Generate EAN-13', 'Générer EAN-13')}</button>
                            </div>
                        </div>
                        <div class="biz-barcodes-grid biz-barcodes-tbody" data-product-type="variation" data-variation-row-id="${varCount}">
                            <div class="biz-no-barcodes-placeholder" style="text-align: center; color: #9ca3af; padding: 20px 0; grid-column: 1 / -1;">${BizProducts.t('No barcodes configured.', 'Aucun code-barres configuré.')}</div>
                        </div>
                    </div>
                    <button type="button" class="biz-btn" onclick="$(this).closest('.biz-variation-row').remove()" style="margin-top: 10px;">${BizProducts.t('Remove this variation', 'Supprimer cette variation')}</button>
                </div>
            `);

            $container.append($variation);
        },

        saveProduct: function(status) {
            const desired = (status || 'draft').toString();
            this.nextStatus = desired;

            // Determine active tab from the active content container
            const activeId = $('.biz-tab-content.active').attr('id') || 'biz-tab-simple';
            const match = activeId.match(/^biz-tab-(.+)$/);
            const activeTab = match ? match[1] : 'simple';

            if (activeTab === 'simple') {
                // Simple tab has a status select; keep it consistent
                $(`#biz-simple-status`).val(desired);
                this.createSimpleProduct();
                return;
            }

            if (activeTab === 'variable') return this.createVariableProduct();
            if (activeTab === 'grouped') return this.createGroupedProduct();
            if (activeTab === 'external') return this.createExternalProduct();
            if (activeTab === 'digital') return this.createDigitalProduct();

            // Fallback
            this.createSimpleProduct();
        },

        createFromActiveTab: function() {
            // Detect which tab is currently active
            const activeId = $('.biz-tab-content.active').attr('id') || 'biz-tab-simple';
            const match = activeId.match(/^biz-tab-(.+)$/);
            const activeTab = match ? match[1] : 'simple';

        createFromActiveTab: function() {
            // Detect which tab is currently active
            const activeId = $('.biz-tab-content.active').attr('id') || 'biz-tab-simple';
            const match = activeId.match(/^biz-tab-(.+)$/);
            const activeTab = match ? match[1] : 'simple';

            console.log('createFromActiveTab: active tab is', activeTab);

            // Call the appropriate handler based on active tab
            if (activeTab === 'simple') return this.createSimpleProduct();
            if (activeTab === 'variable') return this.createVariableProduct();
            if (activeTab === 'grouped') return this.createGroupedProduct();
            if (activeTab === 'external') return this.createExternalProduct();
            if (activeTab === 'digital') return this.createDigitalProduct();
        },

        createSimpleProduct: function() {
            console.log('=== createSimpleProduct called ===');
            console.log('Looking for #biz-simple-name, found:', $('#biz-simple-name').length, 'elements');
            console.log('Value:', $('#biz-simple-name').val());
            
            const data = {
                type: 'simple',
                name: $('#biz-simple-name').val(),
                sku: $('#biz-simple-sku').val(),
                regular_price: $('#biz-simple-regular-price').val(),
                sale_price: $('#biz-simple-sale-price').val(),
                cost_price: $('#biz-simple-cost-price').val(),
                short_description: $('#biz-simple-short-description').val(),
                description: $('#biz-simple-description').val(),
                categories: $('#biz-simple-categories').val(),
                tags: BizProducts.tags.simple,
                image_id: $('#biz-simple-image-id').val(),
                gallery_ids: $('#biz-simple-gallery-ids').val(),
                manage_stock: $('#biz-simple-manage-stock').is(':checked'),
                stock_quantity: $('#biz-simple-stock-quantity').val(),
                stock_status: $('#biz-simple-stock-status').val(),
                backorders: $('#biz-simple-backorders').val(),
                sold_individually: $('#biz-simple-sold-individually').is(':checked'),
                virtual: $('#biz-simple-virtual').is(':checked'),
                weight: $('#biz-simple-weight').val(),
                length: $('#biz-simple-length').val(),
                width: $('#biz-simple-width').val(),
                height: $('#biz-simple-height').val(),
                shipping_class: $('#biz-simple-shipping-class').val(),
                cross_sells: $('#biz-simple-cross-sells').val(),
                upsells: $('#biz-simple-upsells').val(),
                purchase_note: $('#biz-simple-purchase-note').val(),
                menu_order: $('#biz-simple-menu-order').val(),
                publish_date: $('#biz-simple-publish-date').val(),
                status: $('#biz-simple-status').val(),
                reviews: $('#biz-simple-reviews').val(),
                barcodes: BizProducts.serializeBarcodes($('.biz-barcodes-tbody[data-product-type="simple"]'))
            };

            this.createProduct(data);
        },

        createVariableProduct: function() {
            console.log('=== createVariableProduct called ===');
            console.log('Looking for #biz-variable-name, found:', $('#biz-variable-name').length, 'elements');
            console.log('Value:', $('#biz-variable-name').val());

            const openVariationsSection = () => {
                const $section = $('#biz-variations-section');
                if (!$section.hasClass('show')) {
                    $section.addClass('show');
                    $section.prev('.biz-toggle-section').find('span').text('▲');
                }
                const sectionEl = $section.get(0);
                if (sectionEl && typeof sectionEl.scrollIntoView === 'function') {
                    sectionEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
            };
            
            const attributes = [];
            $('#biz-tab-variable .biz-attribute-row').each(function() {
                const name = $(this).find('.attribute-name').val();
                const rowId = $(this).data('id');

                let valuesInput = '';
                if (rowId !== undefined && rowId !== null && rowId !== '') {
                    const $hidden = $('#biz-attribute-values-hidden-' + rowId);
                    if ($hidden.length) {
                        valuesInput = $hidden.val() || '';
                    }
                }
                if (!valuesInput) {
                    valuesInput = $(this).find('.attribute-values').val() || '';
                }

                const values = valuesInput
                    ? valuesInput.split(',').map(v => String(v).trim()).filter(v => v)
                    : [];
                const visible = $(this).find('.attribute-visible').is(':checked');
                const variation = $(this).find('.attribute-variation').is(':checked');

                if (name && values.length > 0) {
                    attributes.push({
                        name: name,
                        values: values,
                        visible: visible,
                        variation: variation
                    });
                }
            });

            const variations = [];
            $('#biz-tab-variable .biz-variation-row').each(function(index) {
                const attributes = $(this).find('.variation-attributes').val();
                const regularPrice = $(this).find('.variation-regular-price').val();
                const salePrice = $(this).find('.variation-sale-price').val();
                const costPrice = $(this).find('.variation-cost-price').val();
                const sku = $(this).find('.variation-sku').val();
                const stock = $(this).find('.variation-stock').val();
                const imageId = $(this).find('input[type="hidden"]:not(.variation-attributes)').val();
                
                // Read from variation barcode card list using global or local serialization helper
                const barcodes = BizProducts.serializeBarcodes($(this).find('.biz-barcodes-tbody[data-product-type="variation"]'));

                variations.push({
                    attributes: attributes,
                    regular_price: regularPrice,
                    sale_price: salePrice,
                    cost_price: costPrice,
                    sku: sku,
                    stock_quantity: stock,
                    image_id: imageId,
                    barcodes: barcodes
                });
            });

            if (!variations.length) {
                openVariationsSection();
                this.showNotification(
                    this.t(
                        'Create at least one variation before saving this product.',
                        'Créez au moins une variation avant d\'enregistrer ce produit.',
                        'أنشئ تنويعة واحدة على الأقل قبل حفظ هذا المنتج.'
                    ),
                    'error'
                );
                return;
            }

            const data = {
                type: 'variable',
                name: $('#biz-variable-name').val(),
                sku: $('#biz-variable-sku').val(),
                short_description: $('#biz-variable-short-description').val(),
                description: $('#biz-variable-description').val(),
                categories: $('#biz-variable-categories').val(),
                tags: BizProducts.tags.variable,
                image_id: $('#biz-variable-image-id').val(),
                attributes: attributes,
                variations: variations,
                base_regular_price: $('#biz-variable-base-regular').val(),
                base_sale_price: $('#biz-variable-base-sale').val(),
                base_cost_price: $('#biz-variable-base-cost').val()
            };

            console.log('Variable product data:', data);
            this.createProduct(data);
        },

        createGroupedProduct: function() {
            console.log('=== createGroupedProduct called ===');
            console.log('Looking for #biz-grouped-name, found:', $('#biz-grouped-name').length, 'elements');
            console.log('Value:', $('#biz-grouped-name').val());
            
            const groupedProducts = [];
            $('#biz-tab-grouped .biz-grouped-product:checked').each(function() {
                groupedProducts.push($(this).val());
            });

            const data = {
                type: 'grouped',
                name: $('#biz-grouped-name').val(),
                sku: $('#biz-grouped-sku').val(),
                description: $('#biz-grouped-description').val(),
                categories: $('#biz-grouped-category').val(),
                grouped_products: groupedProducts
            };

            this.createProduct(data);
        },

        createExternalProduct: function() {
            console.log('=== createExternalProduct called ===');
            console.log('Looking for #biz-external-name, found:', $('#biz-external-name').length, 'elements');
            console.log('Value:', $('#biz-external-name').val());
            
            const data = {
                type: 'external',
                name: $('#biz-external-name').val(),
                sku: $('#biz-external-sku').val(),
                price: $('#biz-external-price').val(),
                external_url: $('#biz-external-url').val(),
                button_text: $('#biz-external-button-text').val(),
                description: $('#biz-external-description').val(),
                categories: $('#biz-external-category').val()
            };

            this.createProduct(data);
        },

        createDigitalProduct: function() {
            console.log('=== createDigitalProduct called ===');
            console.log('Looking for #biz-digital-name, found:', $('#biz-digital-name').length, 'elements');
            console.log('Value:', $('#biz-digital-name').val());
            
            const data = {
                type: 'digital',
                name: $('#biz-digital-name').val(),
                sku: $('#biz-digital-sku').val(),
                regular_price: $('#biz-digital-regular-price').val(),
                sale_price: $('#biz-digital-sale-price').val(),
                cost_price: $('#biz-digital-cost-price').val(),
                description: $('#biz-digital-description').val(),
                categories: $('#biz-digital-category').val(),
                download_files: $('#biz-digital-file-ids').val(),
                download_limit: $('#biz-digital-download-limit').val(),
                download_expiry: $('#biz-digital-download-expiry').val()
            };

            this.createProduct(data);
        },

        createProduct: function(data) {
            // Prevent duplicate creation
            if (this.isCreating) {
                console.warn('Product creation already in progress');
                return;
            }

            // Ensure status is always propagated to the unified backend handler
            if (!data.status) {
                data.status = this.nextStatus || 'publish';
            }
            this.nextStatus = null;

            // Debug: log the data being sent
            console.log('createProduct called with data:', data);
            console.log('data.name value:', data.name);
            console.log('data.name type:', typeof data.name);

            if (!data.name || data.name.trim() === '') {
                this.showNotification(this.t('Product name is required', 'Le nom du produit est requis', 'اسم المنتج مطلوب'), 'error');
                console.error('Validation failed: name is empty or whitespace');
                return;
            }

            const isUpdate = !!(data && (data.id || data.product_id));

            // Set creating flag and disable buttons
            this.isCreating = true;
            this.disableProductButtons();
            this.showNotification(isUpdate ? this.t('⏳ Updating product...', '⏳ Mise à jour du produit...', '⏳ جارٍ تحديث المنتج...') : this.t('⏳ Creating product...', '⏳ Création du produit en cours...', '⏳ جارٍ إنشاء المنتج...'), 'success');

            // Get the global nonce and URL
            const ajaxUrl = typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
            const nonce = '<?php echo esc_attr(wp_create_nonce('bizmart-analytics-nonce')); ?>';
            
            console.log('Creating product with:', data);

            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'bizmart_create_product',
                    nonce: nonce,
                    product_data: JSON.stringify(data)
                },
                timeout: 30000, // 30 second timeout
                success: (response) => {
                    console.log('Product creation response:', response);
                    this.isCreating = false;
                    this.enableProductButtons();
                    
                    if (response.success) {
                        this.showNotification(
                            (isUpdate ? this.t('✅ Product updated successfully! ID: ', '✅ Produit mis à jour avec succès! ID: ', '✅ تم تحديث المنتج بنجاح! المعرف: ') : this.t('✅ Product created successfully! ID: ', '✅ Produit créé avec succès! ID: ', '✅ تم إنشاء المنتج بنجاح! المعرف: ')) + response.data.id,
                            'success'
                        );
                        
                        // Auto-add product to invoice
                        if (window.BizmartInvoices && window.BizmartInvoices.addItemRow) {
                            const invoiceProduct = Object.assign({}, response.data || {});
                            const invoiceLabel = invoiceProduct.sku
                                ? `${invoiceProduct.name} (${invoiceProduct.sku})`
                                : invoiceProduct.name;

                            invoiceProduct.text = invoiceLabel;
                            window.BizmartInvoices.addItemRow();

                            setTimeout(() => {
                                const $lastRow = $('#biz-items-tbody tr:last');
                                const $select = $lastRow.find('.biz-product-select2');
                                if (!$select.length) {
                                    return;
                                }

                                $select.append(new Option(invoiceLabel, invoiceProduct.id, false, true)).trigger('change.select2');
                                $select.trigger({
                                    type: 'select2:select',
                                    params: {
                                        data: invoiceProduct
                                    }
                                });
                            }, 100);
                        }
                        
                        if (!isUpdate) { this.resetForm(data.type); }
                        
                        // Close modal after short delay
                        setTimeout(() => {
                            if (window.BizmartInvoices && window.BizmartInvoices.closeProductModal) {
                                window.BizmartInvoices.closeProductModal();
                            }
                        }, 1500);
                    } else {
                        this.showNotification(
                            this.t('❌ Error: ', '❌ Erreur: ', '❌ خطأ: ') + (response.data || this.t('Unknown error', 'Erreur inconnue', 'خطأ غير معروف')),
                            'error'
                        );
                    }
                },
                error: (jqXHR, textStatus, errorThrown) => {
                    console.error('Product creation error:', jqXHR, textStatus, errorThrown);
                    this.isCreating = false;
                    this.enableProductButtons();
                    
                    if (textStatus === 'timeout') {
                        this.showNotification(
                            this.t(
                                '❌ Request timed out (30s). The product may have been created anyway.',
                                '❌ Délai d\'attente dépassé (30s). Le produit peut avoir été créé malgré tout.'
                            ),
                            'error'
                        );
                    } else {
                        this.showNotification(this.t('❌ Connection error: ', '❌ Erreur de connexion: ', '❌ خطأ في الاتصال: ') + textStatus, 'error');
                    }
                }
            });
        },

        disableProductButtons: function() {
            const $buttons = $('[onclick*="createSimpleProduct"], [onclick*="createVariableProduct"], [onclick*="createGroupedProduct"], [onclick*="createExternalProduct"], [onclick*="createDigitalProduct"], [onclick*="saveProduct"]');
            $buttons.prop('disabled', true).addClass('loading').css({'opacity': '0.6', 'cursor': 'not-allowed'});
        },

        enableProductButtons: function() {
            const $buttons = $('[onclick*="createSimpleProduct"], [onclick*="createVariableProduct"], [onclick*="createGroupedProduct"], [onclick*="createExternalProduct"], [onclick*="createDigitalProduct"], [onclick*="saveProduct"]');
            $buttons.prop('disabled', false).removeClass('loading').css({'opacity': '1', 'cursor': 'pointer'});
        },

        resetForm: function(type) {
            $(`#biz-${type}-form input, #biz-${type}-form textarea, #biz-${type}-form select`).val('');
            $(`#biz-${type}-form .biz-image-preview`).hide().attr('src', '');
            $(`#biz-${type}-form .biz-gallery-images`).empty();
            $(`#biz-${type}-form input[type="checkbox"]`).prop('checked', false);
            $(`#biz-${type}-form input[type="hidden"]`).val('');
            $(`#biz-${type}-form .biz-tag`).remove();
            $(`#biz-${type}-form .biz-variation-row`).remove();
            $(`#biz-${type}-form .biz-attribute-row:not(:first)`).remove();
            $(`#biz-${type}-form .biz-attribute-row .attribute-name, #biz-${type}-form .biz-attribute-row .attribute-values`).val('');
            $(`#biz-${type}-form .biz-attribute-row .attribute-visible, #biz-${type}-form .biz-attribute-row .attribute-variation`).prop('checked', true);
            BizProducts.tags[type] = [];
            $(`#biz-${type}-tags`).val('');

            // Reset shipping section visibility
            if (type === 'simple') {
                $('#biz-simple-shipping-section').removeClass('show');
                $('#biz-simple-stock-quantity-group').hide();
            }
        },

        showNotification: function(message, type) {
            const $notification = $('#biz-notification');
            $notification.stop(true, true).removeClass('success error').addClass(type).html(message).fadeIn(300);
            // Keep the notification visible for longer on success
            const duration = type === 'success' ? 8000 : 5000;
            setTimeout(() => $notification.fadeOut(500), duration);
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        BizProducts.init();
    });

})(jQuery);
</script>
<?php })(); ?>