 /**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Product Page JS - Loaded Product
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - REDO / RETRY
 * ||   - HEAD
 * ||   - PRODUCT TAG 
 * ||   - BRAND
 * ||   - CATEGORY
 * ||   - WOO
 * ||   - IMAGES
 * ||   - TEXT CORRECTIONS 
 * ||   - SAVE
 * || 
 * =============================================================================
 */

jQuery(function($) {
    const params = new URLSearchParams(window.location.search);
    if (params.get('page') !== 'blue-raven' || !params.has('product')) return;
    const checkButton = setInterval(() => {
        const button = $('.parent-container #save-woo-product');
        if (button.length) {
            clearInterval(checkButton); 
            $('#product.enterra-nav-button-my-product').click();

            // --- Get the values from HTML ---

            const type = $('#product-type').attr('data-type'); 
            const isVirtual = $('#mark-as-virtual').attr('data-is-virtual') === 'true';
            const isDownloadable = $('#mark-as-downloadable').attr('data-is-downloadable') === 'true';

            // --- Trigger actions based on these values ---
            if (type) {
                $('#product-type').val(type).trigger('change');
            }

            if (isVirtual) {
                $('#mark-as-virtual').trigger('click', true);
            }

            if (isDownloadable) {
                $('#mark-as-downloadable').trigger('click', true);
            }
        }
    }, 50); // check every 50ms
});jQuery(function ($) {
    
    let productType = '';
    let ve_file_frame;
    let media_file_frame;
    let file_frame;
    
    $(document).off('.my-product-page');
    $(document)

/*
============================================================
    HEAD
============================================================
*/

    /* =========== Toggle between My Product Sub Pages ( Products | WooCommerce | Sales | Images | SEO ) =========== */
    
        .on('click.my-product-page', '.enterra-nav-button-my-product', function (e) {
            e.preventDefault();
            
            $('.enterra-nav-button-my-product').removeClass('active');
            $(this).addClass('active');
            
            const targetContainer = $(this).data('container');
            
            $('.product-container').css('display', 'none');
            $(`.${targetContainer}`).css('display', 'block');
        })

        .on('click.my-product-page', '#ve-schedule-sale', function (e) {$('#ve-sales-dates').toggle();})
        
/*
============================================================
    PRODUCT TAG 
============================================================
*/

    // ===========  Select Suggested Tag, Add to List  =========== //
        
        .on('click.my-product-page', '.textpad-object', function(e) {
            e.preventDefault();
            
            const id = $(this).data('id');
            
            if(id == 'no-add-tag') return;
            
            const text = $(this).text();
            const $textPad = $(this).closest('.text-pad'); 
            
            $textPad.hide();
            
            const $container = $textPad.closest('[id$="-add"]'); 
            const $tagList = $container.next('[id$="-list"]'); 
            
            if ($tagList.find(`.br-tag-item p[data-id="${id}"]`).length === 0) {
                const $tagItem = $(
                    `<div class='br-block-item br-tag-item flex-sb blue-tag' style='min-width: 3rem; margin: 0.25rem;'>
                        <p data-id="${id}" class='spacing-right-small'>${text}</p>
                        <span class="br-block-remove remove-tag" style="padding-top: 0.1rem;">❌</span>
                    </div>`
                );
                
                const countSpan = $('#tag-count');
                const currentCount = parseInt(countSpan.text(), 10) || 0;
                countSpan.text(currentCount + 1);
                
                $tagList.append($tagItem);
                
                const tagCount = parseInt($('#tag-count').text(), 10) || 0;
                if (tagCount >= 10) { return; }
        
                $container.find('input[type="text"]').val('').select();
            }
        })
        
    // ===========  Add New Tag Button, Add to List =========== //
    
        .on('click.my-product-page', '#add-new-tag-button', function(e) {
            e.preventDefault();
            
            const input = $('#add-new-tag');
            const text = input.val();
            
            if(text == ''){ alert('Just type the tag name into the input field to add it.'); return; }else{
                const id = text.toLowerCase().replace(/[^a-z0-9\s-]/g, '').replace(/[\s-]+/g, '-').replace(/^-+|-+$/g, '');  
                const $textPad = $('.text-pad');
                $textPad.hide();
               
                if ($(`#tag-list .br-tag-item p[data-id="${id}"]`).length === 0) {
                    const $tagItem = $(
                        `<div class='br-block-item br-tag-item flex-sb grey-tag' style='min-width: 3rem; margin: 0.25rem;'>
                            <p data-id="${id}" class='spacing-right-small'>${text}</p>
                            <span class="br-block-remove remove-tag" style="padding-top: 0.1rem;">❌</span>
                        </div>`
                    );
                    
                    const countSpan = $('#tag-count');
                    const currentCount = parseInt(countSpan.text(), 10) || 0;
                    countSpan.text(currentCount + 1);
                    
                    $('#tag-list').append($tagItem);
                    input.val('');
                    input.select();
                }
            }
        })
        
    // =========== Off Select, Hide dropdown =========== //
    
        .on('blur.my-product-page', '[id$="-add"] input[type="text"]', function() {
            const $container = $(this).closest('[id$="-add"]');
            setTimeout(function() { const $textPad = $container.find('.text-pad');$textPad.empty().hide();}, 200);
        })
    
    // =========== Remove Tag =========== //
        
        .on('click.my-product-page', '.remove-tag', function(e) {
            e.preventDefault();
            $(this).closest('.br-tag-item').remove();
        
            const countSpan = $('#tag-count');
            const currentCount = parseInt(countSpan.text(), 10) || 0;
            countSpan.text(Math.max(0, currentCount - 1)); 
        })

/*
============================================================
    CATEGORY
============================================================
*/
    
    // =========== Toggle Add New Category =========== //
        
        .on('click.my-product-page', '#add-new-category', function(e) {e.preventDefault();$('#add-category').toggle();})
        
    // =========== Save New Category =========== //
        
        .on('click.my-product-page', '#save-new-category', function(e) {
            e.preventDefault();
            
            const categoryName = $('#new-category').val().trim();
            const parentSlug = $('#parentNewCategory').val();

            if (!categoryName) { alert('Please enter a category name.'); return;}
            
            const content = [categoryName, parentSlug];
            
            BlueRaven_postOperation(content, "add category", false).then(response => {
                response = JSON.parse(response);
                
                if(response == "{success: false, data: 'A term with the name provided already exists with this parent.'}"){
                    alert("A term with the name provided already exists with this parent");
                }else if(response != false){
                    $("#product-category-block").html(response.data.html);
                    alert(categoryName + " Has been added to your Category List.");
                }else{
                    alert("something went wrong. Please contact Support.");
                }
            });
        })
        
    // =========== Add Category To Product =========== //
    
        .on('change.my-product-page', '#product-category', function () {
            const text = $(this).val();
            if (!text) return;
            const id = text.toLowerCase().replace(/[^a-z0-9\s-]/g, '').replace(/[\s-]+/g, '-').replace(/^-+|-+$/g, '');  
        
            /// -- Check for duplicates 
    
            if ($('#category-list').find(`[data-id="${id}"]`).length > 0) { $(this).val(''); return; }
            const $categoryItem = $(`<div class='br-block-item br-category-item flex-sb blue-tag' style='min-width: 3rem; margin: 0.25rem;'><p data-id="${id}" class='spacing-right-small'>${text}</p><span class="br-block-remove remove-category" style="padding-top: 0.1rem;">❌</span></div>`);
        
            $('#category-list').append($categoryItem);
            $(this).val('');
        })
        
    // =========== Remove Category From Product =========== //        
        
        .on('click.my-product-page', '.remove-category', function(e) {e.preventDefault(); $(this).closest('.br-category-item').remove();})

/*
============================================================
    BRAND
============================================================
*/
        
    // =========== Toggle Add New Brand =========== //
        
        .on('click.my-product-page', '#add-new-brand', function(e) {e.preventDefault(); $('#add-brand').toggle();})
        
    // =========== Save New Brand =========== //
    
        .on('click.my-product-page', '#save-new-brand', function(e) {
            e.preventDefault();
            
            const brandName = $('#new-brand').val().trim();
            const parentSlug = $('#parentNewBrand').val();

            if (!brandName) {alert('Please enter a Brand name.');return;}
            
            const content = [brandName, parentSlug];
            
            BlueRaven_postOperation(content, "add brand", false).then(response => {
                response = JSON.parse(response);
                if (response.success === false && response.data === 'A term with the name provided already exists with this parent.') {
                    alert("A term with the name provided already exists with this parent");
                } else if (response && response.success && response.data && response.data.html) {
                    $("#product-brand-block").html(response.data.html);
                    alert(brandName + " has been added to your Brands List.");
                } else {
                    alert("Something went wrong. Please contact Support.");
                }
            });
        })
        
    // =========== Add Brand To Product =========== //
    
        .on('change.my-product-page', '#product-brand', function () {
            const text = $(this).val();
            if (!text) return;
            const id = text.toLowerCase().replace(/[^a-z0-9\s-]/g, '').replace(/[\s-]+/g, '-').replace(/^-+|-+$/g, '');
        
            /// -- Check for duplicates 
            
            if ($('#brand-list').find(`[data-id="${id}"]`).length > 0) {$(this).val('');return;}
            const $brandItem = $(`<div class='br-block-item br-brand-item flex-sb blue-tag' style='min-width: 3rem; margin: 0.25rem;'><p data-id="${id}" class='spacing-right-small'>${text}</p><span class="br-block-remove remove-brand" style="padding-top: 0.1rem;">❌</span></div>`);
        
            $('#brand-list').append($brandItem);
            $(this).val('');
        })
        
    // =========== Remove Brand From Product =========== //    
    
        .on('click.my-product-page', '.remove-brand', function(e) {e.preventDefault(); $(this).closest('.br-brand-item').remove();})
        
/*
============================================================
    WOO
============================================================
*/              
    /* =========== General Product Data =========== */
    
        .on('change.my-product-page', '#product-type', function () {
            const type = $(this).val();
            
            const $attributes = $('#attributes-list-table').find('tr');
        
            const hideColumn3 = () => $attributes.each(function () { $(this).find('th, td').eq(3).hide(); });
            const showColumn3 = () => $attributes.each(function () { $(this).find('th, td').eq(3).show(); });
        
            $('#simple-product-settings, #download-block, #external-affiliate-block, #shipping-block, #price-block, #purchase-note-block, #stock-sold-individually, #sale, #products-variations-block, #grouped-products-add-block, #cross-sell-add-block, #stock-block').hide();
            $('#mark-as-virtual, #mark-as-downloadable').prop('checked', false);
            
            switch (type) {
                case 'simple':
                    $('#simple-product-settings, #price-block, #shipping-block, #purchase-note-block, #stock-sold-individually, #sale, #cross-sell-add-block, #stock-block').show();
                    if (!$("#track-stock-check").is(":checked")) {$("#tracked-stock-status").show()}else{$("#tracked-stock-status").hide()}
                    hideColumn3();
                    break;
        
                case 'external':
                    $('#track-stock-block').attr('style', 'display: none !important');
                    $('#external-affiliate-block, #price-block, #sku-block, #sale').show();
                    if (!$("#track-stock-check").is(":checked")) {$("#tracked-stock-status").show()}else{$("#tracked-stock-status").hide()}
                    hideColumn3();
                    break;
        
                case 'grouped':
                    $('#track-stock-block').attr('style', 'display: none !important');
                    $('#grouped-products-add-block').show();
                    if (!$("#track-stock-check").is(":checked")) {$("#tracked-stock-status").show()}else{$("#tracked-stock-status").hide()}
                    hideColumn3();
                    break;
        
                case 'variable':
                    $('#shipping-block, #purchase-note-block, #stock-sold-individually, #products-variations-block, #cross-sell-add-block, #stock-block').show();
                    showColumn3();
                    break;
            }
        
            productType = type;
        })
    
    /* =========== Download =========== */
    
        .on('change.my-product-page','#mark-as-downloadable', function () {
            if ($(this).is(':checked')) {
                $('#download-block').show();
            } else {
                $('#download-block').hide();
            }
        })
    
    /* =========== Virtual =========== */
    
        .on('change.my-product-page', '#mark-as-virtual', function () {
            if ($(this).is(':checked')) {
                $('#shipping-block').hide();
            } else {
                $('#shipping-block').show();
            }
        })
            
    /* =========== STOCK =========== */
    
        .on('click.my-product-page', '#track-stock-check', function (e) {
            $("#tracked-stock").toggle();
            $("#tracked-low-stock").toggle();
            $("#show-backorders").toggle();

            if ($('#product-type').val() !== 'variable') {
                $("#tracked-stock-status").toggle();
            }
        })        
            
    
    /* =========== Downloads =========== */    
    
        .on('click.my-product-page', '#add-file', function(e) {
            e.preventDefault();
        
            if ($('#download-file-table-body tr').length === 0) {
                $('#download-file-table').show();
            }
            
            var newRow = $('<tr>');
            let currentRowIndex = $('#download-file-table-body tr').length + 1; 
            
            newRow.append('<td>' + currentRowIndex + '</td>');
            newRow.append('<td><input type="text" class="br-input" style="width:100%" name="fileName' + currentRowIndex + '" placeholder="Enter file name"></td>');
            newRow.append('<td><input type="text" class="file-url br-input" style="width:100%" name="fileURL' + currentRowIndex + '" placeholder="Enter file URL"></td>');
            newRow.append('<td><button class="upload-btn enterra-button enterra-secondary-button-color" data-row-index="' + currentRowIndex + '">Upload</button></td>');
            newRow.append('<td><button class="remove-download text-button" data-row-index="' + currentRowIndex + '">❌</button></td>');
        
            $('#download-file-table-body').append(newRow);
            
        })
        
        .on('click.my-product-page', '.upload-btn', function(e) {
            e.preventDefault();
            const currentRowIndex = $(this).data('row-index');
            
            if (file_frame) {file_frame.off(); file_frame = null;}
            
            file_frame = wp.media({
                title: 'Select or Upload a File',
                button: {
                    text: 'Use this file'
                },
                multiple: false
            });
            
            file_frame.currentRowIndex = currentRowIndex;
            file_frame.on('select', function() {
                const attachment = file_frame.state().get('selection').first().toJSON();
                $('input[name="fileURL' + file_frame.currentRowIndex + '"]').val(attachment.url);
            });
            
            file_frame.open();
        })
        
        .on('click.my-product-page', '.remove-download', function(e) {
            e.preventDefault();
            const currentRowIndex = $(this).data('row-index');
            
            $(this).closest('tr').remove();

            $('#download-file-table-body tr').each(function(index) {
                let newIndex = index + 1;
                
                $(this).find('td:first').text(newIndex); 
                $(this).find('input[name^="fileName"]').attr('name', 'fileName' + newIndex);
                $(this).find('input[name^="fileURL"]').attr('name', 'fileURL' + newIndex);
                $(this).find('.upload-btn').attr('data-row-index', newIndex);
                $(this).find('.remove-download').attr('data-row-index', newIndex);
            });
        
            if ($('#download-file-table-body tr').length === 0) {
                $('#download-file-table').hide();
            }
        })
        
    /* =========== Attribites =========== */   
    
        .on('click.my-product-page change.my-product-page', '#add-attributes, #product-add-existing-attributes', function(e) {
            e.preventDefault();
        
            let name = '';
            if (this.id === 'product-add-existing-attributes' && e.type === 'change') { 
                name = $(this).val();  
                if (!name) return;
            } else if (this.id === 'product-add-existing-attributes' && e.type !== 'change') {
                return;
            }
        
            const $tableBody = $('#attributes-list-table-body');
            const $existingRows = $tableBody.find('tr');
            
            if ($existingRows.length === 0) {
                $('#attributes-list-table').show();
            }

    /* =========== Calculate the next index based on existing rows =========== */   

            const currentRowIndex = $existingRows.length + 1;
        
            const newRow = $(`
                <tr>
                    <td class="col-name">
                        <input type="text" class="br-input" style="width:100%" name="attribute_name_${currentRowIndex}" placeholder="Attribute Name" value="${name}">
                    </td>
                    <td class="col-values">
                        <input type="text" class="file-url br-input" style="width:100%" name="attribute_value_${currentRowIndex}" placeholder="Enter options for customers to choose from, e.g., Blue or Large. Use | to separate options.">
                    </td>
                    <td class="col-visible">
                        <label class="br-checkbox spacing-right" style="width: 50%;">
                            <input type="checkbox" value="visible" style="display: none;" id="attribute_check_${currentRowIndex}" name="attribute_check_${currentRowIndex}">
                            <span class="br-check-mark"></span>
                            <label for="attribute_check_${currentRowIndex}"></label>
                        </label>
                    </td>
                    <td class="col-variations">
                        <label class="br-checkbox spacing-right" style="width: 50%;">
                            <input type="checkbox" value="variations" style="display: none;" id="attribute_variations_${currentRowIndex}" name="attribute_variations_${currentRowIndex}">
                            <span class="br-check-mark"></span>
                            <label for="attribute_variations_${currentRowIndex}"></label>
                        </label>
                    </td>
                    <td>
                        <button type="button" class="remove-attribute text-button" data-row-index="${currentRowIndex}">❌</button>
                    </td>
                </tr>
            `);
        
            $tableBody.append(newRow);
        
            if (typeof productType !== 'undefined' && productType !== 'variable') {
                $attributes = $('#attributes-list-table').find('tr')
                $attributes.each(function () { $(this).find('th, td').eq(3).hide(); })
            }
        })
        
        .on('click.my-product-page', '.remove-attribute', function(e) {
            e.preventDefault();
            
            $(this).closest('tr').remove();
    
            $('#attributes-list-table-body tr').each(function(index) {
                const i = index + 1;
    
                $(this).find('input[name^="attribute_name_"]').attr('name', 'attribute_name_' + i);
                $(this).find('input[name^="attribute_value_"]').attr('name', 'attribute_value_' + i);
                $(this).find('input[name^="attribute_check_"]').attr('name', 'attribute_check_' + i);
                $(this).find('input[name^="attribute_variations_"]').attr('name', 'attribute_variations_' + i);
                $(this).find('.remove-attribute').attr('data-row-index', i);
            });
    
            rowAttributesIndex = $('#attributes-list-table-body tr').length + 1;
    
            if (rowAttributesIndex === 1) $('#attributes-list-table').hide();
        })
        
    /* =========== Save Attribute =========== */   

        .on('click.my-product-page', '#save-attributes', function(e) {  e.preventDefault(); BlueRaven_saveAttributes(true); })
        
    /* =========== Variations =========== */   
    
        .on('click.my-product-page', '#add-variations', function(e) {
            e.preventDefault();
            
            const $tableBody = $('#variations-list-table-body');
            const $rows = $tableBody.find('tr');

            const currentRowIndex = $rows.length + 1;
            let dropdowns = '';
        
            // Go through each attribute row
            $('#attributes-list-table-body tr').each(function(index) {
                const attributeName = $(this).find('input[name^="attribute_name_"]').val()?.trim();
                const attributeValuesRaw = $(this).find('input[name^="attribute_value_"]').val()?.trim();
        
                if (attributeName && attributeValuesRaw) {
                    const isChecked = $(`#attribute_variations_${index + 1}`).is(':checked');
                    
                    if (isChecked) {
                        
                        const values = attributeValuesRaw.split('|').map(v => v.trim()).filter(v => v !== '');
                        const selectName = `variation[${currentRowIndex}][attributes][${attributeName}]`;
                        
                        let options = values.map(val => `<option value="${val}">${val}</option>`).join('');
                        dropdowns += `
                            <div class='flex-left'>
                                <label for="${selectName}" class='text-center' style='width:10rem;'><p class='no-margin-padding spacing-right-small text-center'>${attributeName}</p></label>
                                <select name="${selectName}" class="variation-attribute-dropdown br-dropdown" style="width: 30rem; padding: 0.5rem; margin-right: 1rem">
                                    ${options}
                                </select>
                            </div><br/>
                        `;
                    }
                }
            });
            
            if (dropdowns === '') {alert('Either you have no attributes or all your attributes have "Variations" disabled.');return;}
            if ($rows.length === 0) $('#variations-list-table').show();
        
            const newRow = $(`
                <tr data-id='${currentRowIndex}'>
                    <td style='align-content: baseline; padding-top: 1.2rem;'>
                        <input type="hidden" name="variation[${currentRowIndex}][id]" value="${currentRowIndex}">
                        #${currentRowIndex}
                    </td>
                    <td>${dropdowns}</td>
                    <td style='align-content: baseline;'><button type="button" class="edit-variation text-button" data-row-index="${currentRowIndex}"><a>Edit</a></button></td>
                    <td style='align-content: baseline;'><button type="button" class="remove-variation text-button" data-row-index="${currentRowIndex}">❌</button></td>
                </tr>
            `);
        
            $tableBody.append(newRow);
        })
        
        .on('click.my-product-page', '.remove-variation', function(e) {
            e.preventDefault();

            const confirmDelete = confirm('Are you sure you want to remove this variation from your product?');
            if (!confirmDelete) return;
            
            const dataId = $(this).closest('tr').data('id');
            const pID = $('#product-id-input').val();

            $(this).closest('tr').remove();

            const $tableBody = $('#variations-list-table-body');
                
            if ($tableBody.children().length === 0) {$('#variations-list-table').hide();}
            
    /* =========== Re-index remaining rows =========== */

            $('#variations-list-table-body tr').each(function(index) {
                const rowNumber = index + 1;
            
                $(this).find('input[type="hidden"]').val(rowNumber);
                $(this).find('td:first').html(`<input type="hidden" name="variation[${rowNumber}][id]" value="${rowNumber}">#${rowNumber}`);
                $(this).find('select').each(function() { const attrName = $(this).attr('name').split('[').pop().split(']')[0]; $(this).attr('name', `variation[${rowNumber}][attributes][${attrName}]`);});
                $(this).find('.edit-variation, .remove-variation').attr('data-row-index', rowNumber);
            });
        
            BlueRaven_postOperation([dataId, pID], 'remove varation').then(() => {
                const visibleRows = $('#variations-list-table-body').find('tr:visible').length;
                if (visibleRows === 0)  $('#variations-list-table').hide();
            });
        })
        
        .on('click.my-product-page', '.edit-variation', function(e) {
            e.preventDefault();
            const $button = $(this);
            const $row = $(this).closest("tr");
            const $selects = $row.find("select");


            if ($('#variations-item-edit').is(':visible')) {
                const confirmStop = confirm("Are you sure you want to stop editing?");
                if (confirmStop) {$('#variations-item-edit').hide();$button.text('Edit');$selects.prop('disabled', true);}
            } else {
                $button.text('Editing');
                const row = this.closest("tr");
                $selects.prop('disabled', false);

    /* =========== 1. menuPos: index of the row in the tbody =========== */

                const allRows = Array.from(document.querySelectorAll("#variations-list-table-body tr"));
                const menuPos = allRows.indexOf(row) + 1;

    /* =========== 2. attributes: get all attributes and values =========== */

                const selects = row.querySelectorAll("select");
                const attributes = [];
                selects.forEach(select => {
                    const nameMatch = select.name.match(/\[attributes]\[(.*?)\]/);
                    if (nameMatch) {
                        const attributeName = nameMatch[1];
                        const value = select.value;
                        attributes.push([attributeName, value]);
                    }
                });
    
    /* =========== 3. variableName: create "red - small" style string =========== */

                const variableName = attributes.map(([_, value]) => value).join(" - ");

    /* =========== 3. Ve ID: =========== */
 
                const veID = this.closest('tr').getAttribute('data-id');
                
    /* =========== 4. product ID: =========== */

                const pid = $('#product-id-input').val();
                const content = [menuPos, attributes, variableName, veID, pid]
                BlueRaven_postOperation(content, 'load variations edit block', false).then(html => { $('#variations-item-edit').html(html);$('#variations-item-edit').show();});
            }
        })
        
        .on('click.my-product-page', '#ve-add-file', function(e) {
            e.preventDefault();

    /* =========== Show table if it's hidden (no rows) =========== */        
     
            if ($('#ve-download-file-table-body tr').length === 0) {
                $('#ve-download-file-table').show();
            }
   
    /* =========== Calculate new row index based on existing rows =========== */        

            let currentRowIndex = $('#ve-download-file-table-body tr').length + 1;
            let file_frame;
            
            var newRow = $('<tr>');
            newRow.append('<td>' + currentRowIndex + '</td>');
            newRow.append('<td><input type="text" class="br-input" style="width:100%" name="ve-fileName' + currentRowIndex + '" placeholder="Enter file name"></td>');
            newRow.append('<td><input type="text" class="file-url br-input" style="width:100%" name="ve-fileURL' + currentRowIndex + '" placeholder="Enter file URL"></td>');
            newRow.append('<td><button class="ve-upload-btn enterra-button enterra-secondary-button-color" data-row-index="' + currentRowIndex + '">Upload</button></td>');
            newRow.append('<td><button class="ve-remove-download text-button" data-row-index="' + currentRowIndex + '">❌</button></td>');
            
            $('#ve-download-file-table-body').append(newRow);
            
            $('.ve-upload-btn[data-row-index="' + currentRowIndex + '"]').on('click.my-product-page', function(e) {
                e.preventDefault();
                
                if (file_frame) { file_frame.open();return;}
                
                file_frame = wp.media({
                    title: 'Select or Upload a File',
                    button: {text: 'Use this file'},
                    multiple: false
                });
                
                file_frame.on('select', function() {
                    const attachment = file_frame.state().get('selection').first().toJSON();
                    $('input[name="ve-fileURL' + currentRowIndex + '"]').val(attachment.url);
                });
                
                file_frame.open();
            });
            
            $('.ve-remove-download[data-row-index="' + currentRowIndex + '"]').on('click.my-product-page', function(e) {
                e.preventDefault();
                $(this).closest('tr').remove();

    /* =========== Re-index remaining rows =========== */   

                $('#ve-download-file-table-body tr').each(function(index) {
                    let newIndex = index + 1;
                    $(this).find('td:first').text(newIndex); 
                    $(this).find('input[name^="ve-fileName"]').attr('name', 've-fileName' + newIndex);
                    $(this).find('input[name^="ve-fileURL"]').attr('name', 've-fileURL' + newIndex);
                    $(this).find('.ve-upload-btn').attr('data-row-index', newIndex);
                    $(this).find('.ve-remove-download').attr('data-row-index', newIndex);
                });

    /* =========== Hide table if no rows remain =========== */   

                if ($('#ve-download-file-table-body tr').length === 0) $('#ve-download-file-table').hide();

            });
        })
        
        .on('click.my-product-page','#ve-post-image', function(e) {
            e.preventDefault();
    
            if (ve_file_frame) {ve_file_frame.open();return;}
    
            ve_file_frame = wp.media({
                title: 'Select or Upload a File',
                button: {text: 'Use this file'},
                multiple: false
            });
    
            ve_file_frame.on('select', function() {
                const attachment = ve_file_frame.state().get('selection').first().toJSON();
                
                $('#ve-image-alt').val(attachment.alt || '');
                $('#ve-post-image').attr('src', attachment.url);
            });
    
            ve_file_frame.open();
        })
        
        .on('click.my-product-page', '#ve-download', e => $('#ve-download-block').toggle($(e.currentTarget).is(':checked')))
        .on('click.my-product-page', '#ve-manage-stock', e => $('#ve-stock-block').toggle($(e.currentTarget).is(':checked')))
        .on('click.my-product-page', '#ve-virtual', e => $('#ve-shipping').toggle(!$(e.currentTarget).is(':checked')))
        
/*
============================================================
    IMAGES
============================================================
*/   
    
    /* =========== Images =========== */ 
    
        .on('click.my-product-page', '#add-image', function(e) { e.preventDefault();BlueRaven_postOperation('', "add image block", false).then(html => { $("#image-add-content").append(html);});})
        .on('click.my-product-page', '.remove-image-block', function(e) { e.preventDefault(); $(this).closest('.image-block').remove();})
        .on('click.my-product-page', '.media-post-image', function(e) {
            e.preventDefault();
        
            const $block = $(this).closest('.image-block'); 
            const $image = $(this);
            const $altInput = $block.find('.media-post-image-alt');
        
            if (media_file_frame) {
                media_file_frame.off('select'); 
                media_file_frame.on('select', function () {
                    const attachment = media_file_frame.state().get('selection').first().toJSON();
                    $altInput.val(attachment.alt || '');
                    $image.attr('src', attachment.url);
                });
                media_file_frame.open();
                return;
            }
        
            media_file_frame = wp.media({
                title: 'Select or Upload a File',
                button: {text: 'Use this file'},
                multiple: false
            });
        
            media_file_frame.on('select', function () {
                const attachment = media_file_frame.state().get('selection').first().toJSON();
                $altInput.val(attachment.alt || '');
                $image.attr('src', attachment.url);
            });
        
            media_file_frame.open();
        })
        
        .on('change.my-product-page', '.br-star-checkbox', function() { if ($(this).is(':checked')) $('#image-add-content .br-star-checkbox').not(this).prop('checked', false); })
        
        .on('click.my-product-page', '.save-alt-text', function(e) { 
            e.preventDefault();
            
            const $wrapper = $(this).closest('.image-block');
            const imageURL = $wrapper.find('img.media-post-image').attr('src');
            const altText = $wrapper.find('input[name="alt-text"]').val();
        
            let content = [imageURL, altText]
            
            BlueRaven_postOperation(content, 'save alt text', '')
                .then(() => {$wrapper.css('opacity', '0'); setTimeout(() => {$wrapper.css('opacity', '1'); }, 500);})
                .catch(() => {console.error("cant save image")});
        })
            
/*
============================================================
    TEXT CORRECTIONS 
============================================================
*/             

        .on('input.my-product-page', '#product-price', function() {
            let inputVal = $(this).val();
            let filteredVal = inputVal.replace(/[^0-9.]/g, '');
            let decimalCount = filteredVal.split('.').length - 1;
            if (decimalCount > 1) {let parts = filteredVal.split('.');filteredVal = parts[0] + '.' + parts.slice(1).join('');}
            $(this).val(filteredVal);
        })
            
/*
============================================================
    SAVE 
============================================================
*/      

    /* =========== Save Description Text =========== */

        .on('click.my-product-page', '#save-description-text', function(e) {
            e.preventDefault();
          
            let text = $('#long-description').html().trim();
            let id = $('#product-id-input').val();
          
            BlueRaven_postOperation([text, id], "save long description");
        })
        
    /* =========== Save Short Description Text =========== */

        .on('click.my-product-page', '#save-short-description-text', function(e) {
            e.preventDefault();
          
            let text = $('#short-description').html().trim();
            let id = $('#product-id-input').val();
            
            BlueRaven_postOperation([text, id], "save short description");
        })
        
    /* =========== Save Product =========== */
        
        .on('click.my-product-page', '#save-draft, #save-woo-draft, #save-woo-product', function(e) {
            e.preventDefault();

            const $btn = $(this);
            $btn.prop('disabled', true);
            $('#loading-icon').show();
            
    /* =========== ERROR =========== */         
    
           if (parseFloat($('#sales-price').val()) >= parseFloat($('#product-price').val())) alert('Sale price needs to be less than Regular price');
        
    /* =========== Save type =========== */
    
            $("#product-save-type").val($(this).attr('id'));
            BlueRaven_saveAttributes(false);

    /* =========== Save Variations =========== */

            if ($('#variations-item-edit').css('display') != 'none') if (confirm("Please save your variation first.")) {$btn.prop('disabled', false); $('#loading-icon').hide();return; }

    /* =========== Build Content that are not simaple inputs =========== */
    
            $('#long-description-input').val($('#long-description').html().trim());
            $('#short-description-input').val($('#short-description').html().trim());
            $('#product-tags-input').val(Array.from(document.querySelectorAll('#tag-list p')).map(p => p.textContent.trim()).join(', '));
            $('#product-category-input').val(Array.from(document.querySelectorAll('#category-list p')).map(p => p.textContent.trim()).join(', '));
            $('#product-brand-input').val(Array.from(document.querySelectorAll('#brand-list p')).map(p => p.textContent.trim()).join(', '));
            $('#product-cross-input').val($('#cross-sell-add-list p').map(function() {return $(this).data('id');}).get().filter(id => id).join(', '));
            $('#product-upsells-input').val($('#upsells-add-list p').map(function() {return $(this).data('id');}).get().filter(id => id).join(', '));
            $('#product-grouped-input').val($('#grouped-products-add-list p').map(function() {return $(this).data('id');}).get().filter(id => id).join(', '));

    /* =========== Ensure Track stock quantity for this product is set =========== */

            if (!$('#track-stock-check').is(':checked')) {$('#product-stock-quantity').val(null);$('#low-stock-threshold').val(null);}

    /* =========== Downloads =========== */

            if (!$('#mark-as-downloadable').is(':checked')) {$('#download-file-table-body').html('');}

    /* =========== Get all image elements =========== */        
        
            const allImages = Array.from(document.querySelectorAll('img.media-post-image'));
            
    /* =========== Find the starred image (if any) =========== */            
    
            let starredImage = null;
            const nonStarredImages = [];
            
            for (const img of allImages) {
                const starCheckbox = img.closest('.image-block')?.querySelector('.br-star-checkbox');
                const src = img.src.trim();
            
                if (starCheckbox?.checked) {
                    starredImage = src;
                } else {
                    nonStarredImages.push(src);
                }
            }
            
    /* =========== Images =========== */            
    
            ///-- Combine starred and non-starred images without duplicates
            
            let finalImages = [...(starredImage ? [starredImage] : []),...nonStarredImages.filter(src => src !== starredImage)];
            
            ///-- Filter out placeholder images
            
            finalImages = finalImages.filter(url => !url.includes("blue-raven/assets/media/blue_raven_place_holder.webp"));
            
            ///-- Set the input value
            
            $('#product-image-input').val(finalImages.join(', '));

    /* =========== Submit content =========== */
    
            const formData = $('#my-product-form').serialize();

            BlueRaven_postOperation(formData, "save draft").then(() => {
                $btn.prop('disabled', false);
                $('#loading-icon').hide();
            });
        })
    
    /* =========== Save Variation Edits =========== */

        .on('click.my-product-page', '#save-variations-edits', function(e) {
            e.preventDefault();
    
            const imgSrc = $('#ve-post-image').attr('src');
            if (!imgSrc.includes('blue_raven_place_holder.webp')) { 
                $('#ve-product-img').val(imgSrc);
            }
            
            $('#variations-item-edit').toggle();

            if (!$('#ve-manage-stock').is(':checked')) { 
                $('#ve-product-stock-quantity').val(null); 
                $('#ve-low-stock-threshold').val(null);
            }
            if (!$('#ve-download').is(':checked')) $('#ve-download-file-table-body').html('');

            // Create FormData object instead of serializing
            const formData = new FormData(document.getElementById('my-product-form'));
            
            // Convert FormData to a plain object
            const formDataObj = {};
            formData.forEach((value, key) => {
                formDataObj[key] = value;
            });
            
            BlueRaven_postOperation(formDataObj, "save variation").then(() => {$('.edit-variation').text('Edit'); $(".variation-attribute-dropdown").prop("disabled", true);});

        })
        
        $('.enterra-nav-button-my-product:first').click();
        
        function BlueRaven_saveAttributes(isAlert) {
            const urlParams = new URLSearchParams(window.location.search);
            const productId = urlParams.get('product');
            const attributes = [];
            const variationAttributes = [];

            $('#attributes-list-table-body tr').each(function() {
                const $row = $(this);
                const $nameInput = $row.find('.col-name input');
                const $valuesInput = $row.find('.col-values input');
                const $visibleCheckbox = $row.find('.col-visible input[type="checkbox"]');
                const $variationsCheckbox = $row.find('.col-variations input[type="checkbox"]');
                
                if ($nameInput.length && $valuesInput.length) {
                    const attribute = {
                        name: $nameInput.val().trim(),
                        values: $valuesInput.val().split('|').map(v => v.trim()).filter(v => v),
                        visible: $visibleCheckbox.length ? $visibleCheckbox.is(':checked') : false,
                        variations: $variationsCheckbox.length ? $variationsCheckbox.is(':checked') : false
                    };
                    attributes.push(attribute);
                    if (attribute.variations) variationAttributes.push(attribute);
                }
            });

            const content = {
                productId: productId,
                attributes: attributes
            };
            
            // Make sure BlueRaven_postOperation sends this as proper JSON
            BlueRaven_postOperation(content, "save attributes", isAlert).then(() => {
                if(isAlert){
                    $('tr[data-id]').each(function() {
                        const $row = $(this);
                        const variationId = $row.data('id');
                        let $attributesCell = $row.find('td').eq(1); 
                        
                        // Get the currently selected values
                        const selectedValues = [];
                        $row.find('.variation-attribute-dropdown').each(function() {
                            selectedValues.push($(this).val());
                        });
                        
                        $attributesCell.empty();
                        
                        variationAttributes.forEach((attr, index) => {
                            const dropdownHtml = `
                                <div class="flex-left">
                                    <label for="variation[${variationId}][attributes][${attr.name}]" class="text-center" style="width:10rem;">
                                        <p class="no-margin-padding spacing-right-small text-center">${attr.name}</p>
                                    </label>
                                    <select name="variation[${variationId}][attributes][${attr.name}]" class="variation-attribute-dropdown br-dropdown" style="width: 30rem; padding: 0.5rem; margin-right: 1rem" disabled>
                                        ${attr.values.map(value => `<option value="${value}" ${value === selectedValues[index] ? 'selected' : ''}>${value}</option>`).join('')}
                                    </select>
                                </div><br>
                            `;
                            $attributesCell.append(dropdownHtml);
                        });
                    });
                }
            });
        }
});
       