jQuery(document).ready(function($) {
    var config = window.BizmartEditConfig || {};
    if (config.isEdit && config.editData) {
        var d = config.editData;

        var d = config.editData;
        console.log('Bizmart Edit Mode:', d);

        // Switch Tab UI
        if (d.type) {
            var tabId = 'biz-tab-' + d.type;
            $('.biz-tab').removeClass('active'); 
            $('.biz-tab-content').removeClass('active');
            $('#' + tabId).addClass('active');
            
            // Also activate the tab button
            $(`.biz-tab[data-tab="${d.type}"]`).addClass('active');
        }

        // Populate Simple Product Form
        if (d.type === 'simple') {
            $('#biz-simple-name').val(d.name);
            $('#biz-simple-sku').val(d.sku);
            $('#biz-simple-regular-price').val(d.regular_price);
            $('#biz-simple-sale-price').val(d.sale_price);
            $('#biz-simple-cost-price').val(d.cost_price);
            
            // Trigger profit calculation
            if (typeof BizProducts !== 'undefined') BizProducts.calculateProfit('simple');
            $('#biz-simple-short-description').val(d.short_description);
            $('#biz-simple-description').val(d.description);
            
            if (d.manage_stock === 'yes' || d.manage_stock === true) {
                $('#biz-simple-manage-stock').prop('checked', true).trigger('change');
                $('#biz-simple-stock-quantity').val(d.stock_quantity);
            }
            $('#biz-simple-stock-status').val(d.stock_status);
            
            // Categories
            if (d.categories && d.categories.length) {
                $('#biz-simple-categories').val(d.categories);
            }

            // Populate Simple Barcodes
            if (d.barcodes && d.barcodes.length && typeof BizProducts !== 'undefined') {
                BizProducts.populateBarcodes($('.biz-barcodes-tbody[data-product-type="simple"]'), d.barcodes, 'barcode_primary_simple');
            }
            
            // Tags
            if (d.tags && d.tags.length && typeof BizProducts !== 'undefined') {
                d.tags.forEach(tag => BizProducts.addTag('simple', tag));
            }
            
            // Image
            if (d.image_id) {
                $('#biz-simple-image-id').val(d.image_id);
                // Get image URL via AJAX or display placeholder
            }
            
            // Change Submit Button
            var $btn = $('button[onclick^="BizProducts.createSimpleProduct"]');
            $btn.html('💾 ' + (typeof bizmart_text !== 'undefined' ? bizmart_text('Update Product', 'Mettre à jour', 'تحديث المنتج') : 'Update Product'));
        }
        
        // Populate Variable Product
        if (d.type === 'variable') {
            $('#biz-variable-name').val(d.name);
            $('#biz-variable-sku').val(d.sku);
            $('#biz-variable-short-description').val(d.short_description);
            $('#biz-variable-description').val(d.description);
            $('#biz-variable-base-regular').val(d.regular_price);
            $('#biz-variable-base-sale').val(d.sale_price);
            
            // Categories
            if (d.categories && d.categories.length) {
                $('#biz-variable-categories').val(d.categories);
            }
            
            // Tags
            if (d.tags && d.tags.length && typeof BizProducts !== 'undefined') {
                d.tags.forEach(tag => BizProducts.addTag('variable', tag));
            }
            
            // Image
            if (d.image_id) {
                $('#biz-variable-image-id').val(d.image_id);
            }
            
            // Rebuild Attributes
            if (d.attributes && d.attributes.length && typeof BizProducts !== 'undefined') {
                $('#biz-variable-attributes').empty();
                BizProducts.attributeCount = 0;
                
                d.attributes.forEach(function(attr) {
                    BizProducts.attributeCount++;
                    const id = BizProducts.attributeCount;
                    const attrName = attr.label || attr.name;
                    const attrValues = attr.options.join(', ');
                    
                    const attributeHtml = `
                        <div class="biz-attribute-row" data-id="${id}">
                            <div class="biz-form-grid-2">
                                <div class="biz-form-group">
                                    <label>Attribute Name</label>
                                    <input type="text" class="biz-input attribute-name" value="${attrName}" readonly style="background: #f9fafb;">
                                </div>
                                <div class="biz-form-group">
                                    <label>Attribute Values</label>
                                    <div class="biz-tag-input" id="biz-attribute-values-${id}">
                                        ${attr.options.map(v => `<span class="biz-tag">${v} <span class="biz-tag-remove">×</span></span>`).join('')}
                                        <input type="text" class="biz-attribute-values-input" placeholder="Add value">
                                    </div>
                                    <input type="hidden" class="attribute-values" id="biz-attribute-values-hidden-${id}" value="${attrValues}">
                                </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" ${attr.visible ? 'checked' : ''}>
                                            <span class="biz-slider"></span>
                                        </span>
                                        Visible on product page
                                    </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" ${attr.variation ? 'checked' : ''}>
                                            <span class="biz-slider"></span>
                                        </span>
                                        Used for variations
                                    </label>
                                </div>
                                <button type="button" class="biz-btn" onclick="BizProducts.removeAttribute(${id})">Remove</button>
                            </div>
                        </div>
                    `;
                    
                    $('#biz-variable-attributes').append(attributeHtml);
                    
                    // Bind tag input events
                    $(`#biz-attribute-values-${id} .biz-attribute-values-input`).on('keypress', function(e) {
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            const tag = $(this).val().trim();
                            if (tag) {
                                const rowId = $(this).closest('.biz-attribute-row').data('id');
                                const $container = $(`#biz-attribute-values-${rowId}`);
                                $container.prepend(`<span class="biz-tag">${tag} <span class="biz-tag-remove">×</span></span>`);
                                $(this).val('');
                                BizProducts.updateAttributeValues(rowId);
                            }
                        }
                    });
                });
            }
            
            // Rebuild Variations
            if (d.variations && d.variations.length && typeof BizProducts !== 'undefined') {
                $('#biz-variations-container').empty();
                BizProducts.variationCount = 0;
                
                d.variations.forEach(function(varData) {
                    BizProducts.variationCount++;
                    const id = BizProducts.variationCount;
                    
                    // Build attribute display string
                    const attrPairs = [];
                    for (const [name, value] of Object.entries(varData.attributes)) {
                        attrPairs.push({name: name, value: value});
                    }
                    const attrString = attrPairs.map(p => `${p.name}: ${p.value}`).join(', ');
                    const comboJson = JSON.stringify(attrPairs);
                    
                    const variationHtml = `
                        <div class="biz-variation-row" id="variation-${id}" data-combo='${comboJson}' data-variation-id="${varData.id}">
                            <div class="biz-variation-header">
                                <h4 class="biz-variation-title">Variation ${id}</h4>
                                <button type="button" class="biz-remove-variation" onclick="BizProducts.removeVariation(${id})">
                                    &times;
                                </button>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label>Attributes</label>
                                    <input type="text" class="biz-input variation-attributes-display" value="${attrString}" readonly>
                                </div>
                                <div class="biz-form-group">
                                    <label>Variation SKU</label>
                                    <input type="text" class="biz-input variation-sku" value="${varData.sku || ''}" data-id="${id}">
                                </div>
                                <div class="biz-form-group">
                                    <label>Regular price</label>
                                    <input type="number" step="0.01" min="0" class="biz-input variation-regular-price" value="${varData.regular_price || ''}" data-id="${id}">
                                </div>
                            </div>
                            
                            <div class="biz-form-grid-3">
                                <div class="biz-form-group">
                                    <label>Sale price</label>
                                    <input type="number" step="0.01" min="0" class="biz-input variation-sale-price" value="${varData.sale_price || ''}" data-id="${id}">
                                </div>
                                <div class="biz-form-group">
                                    <label>Cost price</label>
                                    <input type="number" step="0.01" min="0" class="biz-input variation-cost-price" value="${varData.cost_price || ''}" data-id="${id}">
                                </div>
                                <div class="biz-form-group">
                                    <label>Stock</label>
                                    <input type="number" min="0" step="1" inputmode="numeric" pattern="[0-9]*" class="biz-input variation-stock" value="${varData.stock_quantity || ''}" data-id="${id}">
                                </div>
                            </div>
                            <div class="biz-form-group" style="grid-column: span 3; 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;">🏷️ Variation Barcodes</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="${id}" style="padding: 6px 12px; font-size: 12px;">➕ Add Barcode</button>
                                        <button type="button" class="biz-btn biz-btn-secondary generate-barcode-btn" data-product-type="variation" data-variation-row-id="${id}" style="padding: 6px 12px; font-size: 12px;">⚡ Generate EAN-13</button>
                                    </div>
                                </div>
                                <div class="biz-barcodes-grid biz-barcodes-tbody" data-product-type="variation" data-variation-row-id="${id}">
                                    <div class="biz-no-barcodes-placeholder" style="text-align: center; color: #9ca3af; padding: 20px 0; grid-column: 1 / -1;">No barcodes configured.</div>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    $('#biz-variations-container').append(variationHtml);
                    if (varData.barcodes && varData.barcodes.length && typeof BizProducts !== 'undefined') {
                        BizProducts.populateBarcodes($(`#variation-${id} .biz-barcodes-tbody`), varData.barcodes, 'barcode_primary_var_' + id);
                    }
                });
            }
            // Change Submit Button
            var $vbtn = $('button[onclick^="BizProducts.createVariableProduct"]');
            $vbtn.html('💾 ' + (typeof bizmart_text !== 'undefined' ? bizmart_text('Update Product', 'Mettre à jour', 'تحديث المنتج') : 'Update Product'));
        }
    }
});
