/**
 * GGM Commerce Import/Export JavaScript
 */
(function($) {
    'use strict';

    // State management
    var state = {
        currentModal: null,
        importStep: 1,
        uploadedFile: null,
        csvData: null,
        jsonData: null,
        importFormat: null,
        mapping: {},
        importOptions: {},
        importInProgress: false,
        backgroundJobId: null
    };

    // Initialize
    $(document).ready(function() {
        initEventHandlers();
    });

    /**
     * Initialize event handlers
     */
    function initEventHandlers() {
        // Export button
        $(document).on('click', '.ggmc-export-btn', function(e) {
            e.preventDefault();
            openExportModal();
        });

        // Import button
        $(document).on('click', '.ggmc-import-btn', function(e) {
            e.preventDefault();
            openImportModal();
        });

        // Close modal
        $(document).on('click', '.ggmc-modal-close, .ggmc-modal-cancel', function(e) {
            e.preventDefault();
            closeModal();
        });

        // Click outside modal to close
        $(document).on('click', '.ggmc-modal-overlay', function(e) {
            if ($(e.target).hasClass('ggmc-modal-overlay')) {
                closeModal();
            }
        });

        // Radio option selection
        $(document).on('click', '.ggmc-radio-option', function() {
            var $radio = $(this).find('input[type="radio"]');
            $radio.prop('checked', true);
            $(this).siblings().removeClass('selected');
            $(this).addClass('selected');
        });

        // Export actions
        $(document).on('click', '.ggmc-export-submit', handleExport);
        $(document).on('click', '.ggmc-download-template', handleDownloadTemplate);
        $(document).on('click', '.ggmc-export-images', handleExportImages);

        // Export format change - toggle UI elements
        $(document).on('change', 'input[name="export_format"]', handleExportFormatChange);

        // Image handling change - show/hide image package button
        $(document).on('change', 'input[name="image_handling"]', handleImageHandlingChange);

        // Import actions
        $(document).on('click', '.ggmc-import-next', handleImportNext);
        $(document).on('click', '.ggmc-import-back', handleImportBack);
        $(document).on('click', '.ggmc-import-start', handleStartImport);

        // Import complete - refresh page to show new products
        $(document).on('click', '.ggmc-import-done', function(e) {
            e.preventDefault();
            window.location.reload();
        });

        // Download skipped images CSV report
        $(document).on('click', '.ggmc-download-skipped-csv', function(e) {
            e.preventDefault();
            if (state.lastSkippedImages && state.lastSkippedImages.length > 0) {
                downloadSkippedImagesCSV(state.lastSkippedImages);
            }
        });

        // View past import reports
        $(document).on('click', '.ggmc-view-import-reports', function(e) {
            e.preventDefault();
            openImportReportsModal();
        });

        // Delete single import report
        $(document).on('click', '.ggmc-delete-report', function(e) {
            e.preventDefault();
            var index = $(this).data('index');
            if (confirm('Delete this import report?')) {
                deleteImportReport(index);
            }
        });

        // Delete all import reports
        $(document).on('click', '.ggmc-delete-all-reports', function(e) {
            e.preventDefault();
            if (confirm('Delete all import reports?')) {
                deleteAllImportReports();
            }
        });

        // Download report from past reports list
        $(document).on('click', '.ggmc-download-report-csv', function(e) {
            e.preventDefault();
            var index = $(this).data('index');
            if (state.importReports && state.importReports[index]) {
                var report = state.importReports[index];
                downloadSkippedImagesCSV(report.skipped_images || []);
            }
        });

        // Image re-association tool
        $(document).on('click', '.ggmc-reassociate-btn', function(e) {
            e.preventDefault();
            openImageReassociationModal();
        });
        $(document).on('click', '.ggmc-scan-media', handleScanMedia);
        $(document).on('click', '.ggmc-upload-manifest', handleUploadManifest);
        $(document).on('click', '.ggmc-apply-associations', handleApplyAssociations);
        $(document).on('change', '.ggmc-match-checkbox', updateSelectedAssociations);

        // File upload
        $(document).on('click', '.ggmc-file-upload', function() {
            $(this).find('input[type="file"]').click();
        });

        $(document).on('change', '.ggmc-file-upload input[type="file"]', handleFileSelect);

        // Drag and drop
        $(document).on('dragover', '.ggmc-file-upload', function(e) {
            e.preventDefault();
            $(this).addClass('drag-over');
        });

        $(document).on('dragleave', '.ggmc-file-upload', function(e) {
            e.preventDefault();
            $(this).removeClass('drag-over');
        });

        $(document).on('drop', '.ggmc-file-upload', function(e) {
            e.preventDefault();
            $(this).removeClass('drag-over');
            var files = e.originalEvent.dataTransfer.files;
            if (files.length > 0) {
                handleFileUpload(files[0]);
            }
        });

        // Remove file
        $(document).on('click', '.ggmc-file-info-remove', function(e) {
            e.stopPropagation();
            state.uploadedFile = null;
            state.csvData = null;
            updateFileDisplay();
        });

        // Mapping select change
        $(document).on('change', '.ggmc-mapping-select', function() {
            var csvColumn = $(this).data('column');
            var fieldValue = $(this).val();
            state.mapping[csvColumn] = fieldValue;
            updateMappingStatus($(this).closest('tr'), fieldValue);
        });
    }

    /**
     * Open export modal
     */
    function openExportModal() {
        var html = getExportModalHTML();
        showModal(html);

        // Apply initial state based on selected format (JSON by default)
        setTimeout(function() {
            handleExportFormatChange();
            handleImageHandlingChange();
        }, 50);
    }

    /**
     * Open import modal
     */
    function openImportModal() {
        state.importStep = 1;
        state.uploadedFile = null;
        state.csvData = null;
        state.mapping = {};

        var html = getImportModalHTML();
        showModal(html);
    }

    /**
     * Show modal
     */
    function showModal(html) {
        if ($('.ggmc-modal-overlay').length) {
            $('.ggmc-modal-overlay').remove();
        }

        $('body').append('<div class="ggmc-modal-overlay">' + html + '</div>');

        setTimeout(function() {
            $('.ggmc-modal-overlay').addClass('active');
        }, 10);

        state.currentModal = $('.ggmc-modal-overlay');
    }

    /**
     * Close modal
     */
    function closeModal() {
        if (state.importInProgress) {
            if (!confirm(ggmcImportExport.strings.confirmCancel)) {
                return;
            }
        }

        $('.ggmc-modal-overlay').removeClass('active');
        setTimeout(function() {
            $('.ggmc-modal-overlay').remove();
            state.currentModal = null;
        }, 300);
    }

    /**
     * Get export modal HTML
     */
    function getExportModalHTML() {
        return `
            <div class="ggmc-modal ggmc-modal-wide">
                <div class="ggmc-modal-header">
                    <h2>${ggmcImportExport.strings.exportTitle}</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <div class="ggmc-form-group">
                        <label>${ggmcImportExport.strings.exportFormat}</label>
                        <div class="ggmc-radio-options">
                            <label class="ggmc-radio-option selected">
                                <input type="radio" name="export_format" value="json" checked>
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">
                                        JSON (Recommended)
                                        <span class="ggmc-badge ggmc-badge-success">Complete</span>
                                    </div>
                                    <div class="ggmc-radio-option-desc">Full backup with all entity metadata - categories, tags, attributes (with icons, units, groups), variations, tax rates, and all relationships.</div>
                                </div>
                            </label>
                            <label class="ggmc-radio-option">
                                <input type="radio" name="export_format" value="simple">
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">
                                        ${ggmcImportExport.strings.simpleFormat}
                                        <span class="ggmc-badge ggmc-badge-warning">Basic</span>
                                    </div>
                                    <div class="ggmc-radio-option-desc">${ggmcImportExport.strings.simpleFormatDesc} Note: Some entity metadata may not be exported.</div>
                                </div>
                            </label>
                            <label class="ggmc-radio-option">
                                <input type="radio" name="export_format" value="advanced">
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">
                                        ${ggmcImportExport.strings.advancedFormat}
                                        <span class="ggmc-badge ggmc-badge-warning">Basic</span>
                                    </div>
                                    <div class="ggmc-radio-option-desc">${ggmcImportExport.strings.advancedFormatDesc} Note: Some entity metadata may not be exported.</div>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div class="ggmc-form-group">
                        <label>${ggmcImportExport.strings.whatToExport}</label>
                        <div class="ggmc-radio-options">
                            <label class="ggmc-radio-option selected">
                                <input type="radio" name="export_scope" value="all" checked>
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">${ggmcImportExport.strings.allProducts} (${ggmcImportExport.productCount})</div>
                                </div>
                            </label>
                            ${ggmcImportExport.selectedCount > 0 ? `
                            <label class="ggmc-radio-option">
                                <input type="radio" name="export_scope" value="selected">
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">${ggmcImportExport.strings.selectedOnly} (${ggmcImportExport.selectedCount})</div>
                                </div>
                            </label>
                            ` : ''}
                        </div>
                    </div>

                    <div class="ggmc-form-group ggmc-image-options">
                        <label>Image Handling</label>
                        <div class="ggmc-radio-options">
                            <label class="ggmc-radio-option selected">
                                <input type="radio" name="image_handling" value="urls" checked>
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">Include Image URLs</div>
                                    <div class="ggmc-radio-option-desc">Images will be referenced by their current URLs. Best when images will remain accessible at the same location.</div>
                                </div>
                            </label>
                            <label class="ggmc-radio-option">
                                <input type="radio" name="image_handling" value="package">
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">Download Image Package (Separate ZIP)</div>
                                    <div class="ggmc-radio-option-desc">Download a separate ZIP file containing all images. Use this when migrating to a new server where current image URLs won't be accessible.</div>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div class="ggmc-form-group ggmc-include-options" id="csv-include-options">
                        <label>${ggmcImportExport.strings.includeData}</label>
                        <div class="ggmc-checkbox-group">
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="include_categories" value="1" checked>
                                ${ggmcImportExport.strings.categories}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="include_tags" value="1" checked>
                                ${ggmcImportExport.strings.tags}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="include_attributes" value="1" checked>
                                ${ggmcImportExport.strings.attributes}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="include_variations" value="1" checked>
                                ${ggmcImportExport.strings.variations}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="include_barcodes" value="1" checked>
                                ${ggmcImportExport.strings.barcodes}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="include_kits" value="1" checked>
                                ${ggmcImportExport.strings.kits}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="include_downloads" value="1" checked>
                                ${ggmcImportExport.strings.downloads}
                            </label>
                        </div>
                    </div>

                    <div class="ggmc-form-group" style="margin-top: 10px;">
                        <label class="ggmc-checkbox-option">
                            <input type="checkbox" name="include_trashed" value="1">
                            Include trashed products
                        </label>
                    </div>

                    <div class="ggmc-info-box" id="json-info-box">
                        <span class="dashicons dashicons-info-outline"></span>
                        <div class="ggmc-info-text">JSON export includes all data: tax rates, attribute groups, attributes (with icons, units, options), variation attributes, categories (with hierarchy and images), tags, products, and all relationships.</div>
                    </div>
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-download-template" id="template-btn">
                        <span class="dashicons dashicons-download"></span>
                        ${ggmcImportExport.strings.downloadTemplate}
                    </button>
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-export-images" id="export-images-btn" style="display: none;">
                        <span class="dashicons dashicons-format-gallery"></span>
                        Download Image Package
                    </button>
                    <button class="ggmc-btn ggmc-btn-primary ggmc-export-submit">
                        <span class="dashicons dashicons-upload"></span>
                        ${ggmcImportExport.strings.exportProducts}
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * Get import modal HTML
     */
    function getImportModalHTML() {
        return getImportStep1HTML();
    }

    /**
     * Get import step 1 HTML (Upload)
     */
    function getImportStep1HTML() {
        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>${ggmcImportExport.strings.importTitle} - ${ggmcImportExport.strings.step} 1</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    ${getStepIndicatorHTML(1)}

                    <div class="ggmc-file-upload">
                        <input type="file" accept=".csv,.json">
                        <div class="ggmc-file-upload-icon">
                            <span class="dashicons dashicons-upload"></span>
                        </div>
                        <div class="ggmc-file-upload-text">${ggmcImportExport.strings.dragDrop}</div>
                        <div class="ggmc-file-upload-hint">Supported: .csv and .json files (up to 50MB)</div>
                    </div>

                    <div class="ggmc-file-info-container"></div>

                    <div class="ggmc-form-group" style="margin-top: 20px;">
                        <label>${ggmcImportExport.strings.fileFormat}</label>
                        <div class="ggmc-radio-options">
                            <label class="ggmc-radio-option selected">
                                <input type="radio" name="import_format" value="auto" checked>
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">${ggmcImportExport.strings.autoDetect}</div>
                                    <div class="ggmc-radio-option-desc">${ggmcImportExport.strings.autoDetectDesc}</div>
                                </div>
                            </label>
                            <label class="ggmc-radio-option">
                                <input type="radio" name="import_format" value="woocommerce">
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">${ggmcImportExport.strings.wooFormat}</div>
                                    <div class="ggmc-radio-option-desc">${ggmcImportExport.strings.wooFormatDesc}</div>
                                </div>
                            </label>
                        </div>
                    </div>

                    <p style="text-align: center; margin-top: 20px;">
                        ${ggmcImportExport.strings.needTemplate}
                        <a href="#" class="ggmc-download-template">${ggmcImportExport.strings.downloadTemplateLink}</a>
                    </p>
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-modal-cancel">${ggmcImportExport.strings.cancel}</button>
                    <button class="ggmc-btn ggmc-btn-primary ggmc-import-next" disabled>
                        ${ggmcImportExport.strings.next}
                        <span class="dashicons dashicons-arrow-right-alt"></span>
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * Get import step 2 HTML (Field Mapping)
     */
    function getImportStep2HTML() {
        var mappingRows = '';
        var fieldOptions = getFieldOptionsHTML();

        state.csvData.headers.forEach(function(header) {
            var matchedField = state.mapping[header] || '';
            var statusClass = matchedField ? (state.mapping[header] === matchedField ? 'matched' : 'mapped') : 'skipped';
            var statusText = matchedField ? (statusClass === 'matched' ? '✓ Match' : '⚠ Mapped') : '⊘ Skip';

            mappingRows += `
                <tr>
                    <td><strong>${escapeHtml(header)}</strong></td>
                    <td class="ggmc-mapping-arrow">→</td>
                    <td>
                        <select class="ggmc-mapping-select" data-column="${escapeHtml(header)}">
                            ${fieldOptions.replace('value="' + matchedField + '"', 'value="' + matchedField + '" selected')}
                        </select>
                    </td>
                    <td>
                        <span class="ggmc-mapping-status ${statusClass}">${statusText}</span>
                    </td>
                </tr>
            `;
        });

        var previewRows = '';
        state.csvData.sample_rows.slice(0, 3).forEach(function(row) {
            var cells = '';
            state.csvData.headers.slice(0, 5).forEach(function(header) {
                cells += '<td>' + escapeHtml(truncate(row[header] || '', 30)) + '</td>';
            });
            previewRows += '<tr>' + cells + '</tr>';
        });

        var previewHeaders = state.csvData.headers.slice(0, 5).map(function(h) {
            return '<th>' + escapeHtml(h) + '</th>';
        }).join('');

        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>${ggmcImportExport.strings.importTitle} - ${ggmcImportExport.strings.step} 2</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    ${getStepIndicatorHTML(2)}

                    <p><strong>${ggmcImportExport.strings.fileInfo}:</strong> ${state.csvData.row_count} ${ggmcImportExport.strings.rowsDetected}</p>

                    <div class="ggmc-mapping-stats">
                        <div class="ggmc-mapping-stat">
                            <span class="ggmc-mapping-stat-value">${state.csvData.headers.length}</span>
                            <span class="ggmc-mapping-stat-label">${ggmcImportExport.strings.totalColumns}</span>
                        </div>
                        <div class="ggmc-mapping-stat" id="mapped-count">
                            <span class="ggmc-mapping-stat-value">0</span>
                            <span class="ggmc-mapping-stat-label">${ggmcImportExport.strings.mapped}</span>
                        </div>
                        <div class="ggmc-mapping-stat" id="skipped-count">
                            <span class="ggmc-mapping-stat-value">0</span>
                            <span class="ggmc-mapping-stat-label">${ggmcImportExport.strings.skipped}</span>
                        </div>
                    </div>

                    <div style="max-height: 300px; overflow-y: auto;">
                        <table class="ggmc-mapping-table">
                            <thead>
                                <tr>
                                    <th>${ggmcImportExport.strings.csvColumn}</th>
                                    <th></th>
                                    <th>${ggmcImportExport.strings.productField}</th>
                                    <th>${ggmcImportExport.strings.status}</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${mappingRows}
                            </tbody>
                        </table>
                    </div>

                    <div class="ggmc-preview-container">
                        <div class="ggmc-preview-title">${ggmcImportExport.strings.preview}</div>
                        <div class="ggmc-preview-table-wrapper">
                            <table class="ggmc-preview-table">
                                <thead><tr>${previewHeaders}</tr></thead>
                                <tbody>${previewRows}</tbody>
                            </table>
                        </div>
                    </div>

                    <div class="ggmc-save-mapping">
                        <input type="checkbox" id="save-mapping" name="save_mapping">
                        <label for="save-mapping">${ggmcImportExport.strings.saveMapping}</label>
                    </div>
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-import-back">
                        <span class="dashicons dashicons-arrow-left-alt"></span>
                        ${ggmcImportExport.strings.back}
                    </button>
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-modal-cancel">${ggmcImportExport.strings.cancel}</button>
                    <button class="ggmc-btn ggmc-btn-primary ggmc-import-next">
                        ${ggmcImportExport.strings.next}
                        <span class="dashicons dashicons-arrow-right-alt"></span>
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * Get import step 3 HTML (Options & Confirm)
     */
    function getImportStep3HTML() {
        // Get product count based on import type
        var productCount = 0;
        if (state.importFormat === 'json' && state.jsonData) {
            productCount = (state.jsonData.counts || {}).products || 0;
        } else if (state.csvData) {
            productCount = state.csvData.row_count || 0;
        }

        // Check if background processing should be recommended (>250 products)
        var showBackgroundOption = state.importFormat === 'json' && productCount > 250;

        var backgroundOptionHtml = '';
        if (showBackgroundOption) {
            backgroundOptionHtml = `
                <div class="ggmc-form-group">
                    <label>Processing Mode</label>
                    <div class="ggmc-radio-options">
                        <label class="ggmc-radio-option selected">
                            <input type="radio" name="processing_mode" value="background" checked>
                            <div class="ggmc-radio-option-content">
                                <div class="ggmc-radio-option-title">Background Processing (Recommended)</div>
                                <div class="ggmc-radio-option-desc">Import runs in the background using WP-Cron. You'll be notified when complete. Best for large imports to avoid timeouts.</div>
                            </div>
                        </label>
                        <label class="ggmc-radio-option">
                            <input type="radio" name="processing_mode" value="immediate">
                            <div class="ggmc-radio-option-content">
                                <div class="ggmc-radio-option-title">Immediate Processing</div>
                                <div class="ggmc-radio-option-desc">Process all products now. May timeout for very large imports. Keep this tab open until complete.</div>
                            </div>
                        </label>
                    </div>
                </div>
            `;
        }

        var largeImportWarning = '';
        if (productCount > 250) {
            largeImportWarning = `
                <div class="ggmc-info-box" style="margin-bottom: 15px;">
                    <span class="dashicons dashicons-info-outline"></span>
                    <div class="ggmc-info-text">
                        <strong>Large Import Detected:</strong> ${productCount} products will be imported.
                        ${showBackgroundOption ? 'Background processing is recommended for better reliability.' : ''}
                    </div>
                </div>
            `;
        }

        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>${ggmcImportExport.strings.importTitle} - ${ggmcImportExport.strings.step} 3</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    ${getStepIndicatorHTML(3)}

                    <p><strong>${ggmcImportExport.strings.readyToImport} ${productCount} ${ggmcImportExport.strings.products}</strong></p>

                    ${largeImportWarning}

                    ${backgroundOptionHtml}

                    <div class="ggmc-form-group">
                        <label>${ggmcImportExport.strings.duplicateHandling}</label>
                        <div class="ggmc-radio-options">
                            <label class="ggmc-radio-option">
                                <input type="radio" name="duplicate_handling" value="skip">
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">${ggmcImportExport.strings.skipDuplicates}</div>
                                    <div class="ggmc-radio-option-desc">${ggmcImportExport.strings.skipDuplicatesDesc}</div>
                                </div>
                            </label>
                            <label class="ggmc-radio-option selected">
                                <input type="radio" name="duplicate_handling" value="update" checked>
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">${ggmcImportExport.strings.updateExisting}</div>
                                    <div class="ggmc-radio-option-desc">${ggmcImportExport.strings.updateExistingDesc}</div>
                                </div>
                            </label>
                            <label class="ggmc-radio-option">
                                <input type="radio" name="duplicate_handling" value="create">
                                <div class="ggmc-radio-option-content">
                                    <div class="ggmc-radio-option-title">${ggmcImportExport.strings.createNew}</div>
                                    <div class="ggmc-radio-option-desc">${ggmcImportExport.strings.createNewDesc}</div>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div class="ggmc-form-group">
                        <label>${ggmcImportExport.strings.imageHandling}</label>
                        <div class="ggmc-checkbox-group" style="display: block;">
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="download_images" value="1" checked>
                                ${ggmcImportExport.strings.downloadImages}
                            </label>
                        </div>
                    </div>

                    <div class="ggmc-form-group">
                        <label>${ggmcImportExport.strings.dataHandling}</label>
                        <div class="ggmc-checkbox-group" style="display: block;">
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="create_categories" value="1" checked>
                                ${ggmcImportExport.strings.createCategories}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="create_tags" value="1" checked>
                                ${ggmcImportExport.strings.createTags}
                            </label>
                            <label class="ggmc-checkbox-option">
                                <input type="checkbox" name="create_attributes" value="1" checked>
                                ${ggmcImportExport.strings.createAttributes}
                            </label>
                        </div>
                    </div>

                    <div class="ggmc-warning-box">
                        <span class="ggmc-warning-icon dashicons dashicons-warning"></span>
                        <div class="ggmc-warning-text">${ggmcImportExport.strings.warningBackup}</div>
                    </div>
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-import-back">
                        <span class="dashicons dashicons-arrow-left-alt"></span>
                        ${ggmcImportExport.strings.back}
                    </button>
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-modal-cancel">${ggmcImportExport.strings.cancel}</button>
                    <button class="ggmc-btn ggmc-btn-success ggmc-import-start">
                        <span class="dashicons dashicons-yes-alt"></span>
                        ${ggmcImportExport.strings.startImport}
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * Get import progress HTML
     */
    function getImportProgressHTML(progress) {
        var percentage = progress.total > 0 ? Math.round((progress.processed / progress.total) * 100) : 0;

        var errorsList = '';
        if (progress.errors && progress.errors.length > 0) {
            progress.errors.slice(-5).forEach(function(err) {
                errorsList += `
                    <div class="ggmc-error-item">
                        <span class="ggmc-error-icon dashicons dashicons-warning"></span>
                        <div class="ggmc-error-content">
                            <span class="ggmc-error-row">${ggmcImportExport.strings.row} ${err.row}:</span>
                            <span class="ggmc-error-message">${escapeHtml(err.message)}</span>
                        </div>
                    </div>
                `;
            });
        }

        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>${ggmcImportExport.strings.importing}</h2>
                </div>
                <div class="ggmc-modal-body">
                    <div class="ggmc-progress-container">
                        <div class="ggmc-progress-bar">
                            <div class="ggmc-progress-fill" style="width: ${percentage}%"></div>
                        </div>
                        <div class="ggmc-progress-text">
                            <span>${percentage}%</span>
                            <span>${progress.processed} / ${progress.total}</span>
                        </div>
                    </div>

                    <div class="ggmc-stats-grid">
                        <div class="ggmc-stat-item created">
                            <div class="ggmc-stat-value">${progress.created}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.created}</div>
                        </div>
                        <div class="ggmc-stat-item updated">
                            <div class="ggmc-stat-value">${progress.updated}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.updated}</div>
                        </div>
                        <div class="ggmc-stat-item skipped">
                            <div class="ggmc-stat-value">${progress.skipped}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.skippedStat}</div>
                        </div>
                        <div class="ggmc-stat-item errors">
                            <div class="ggmc-stat-value">${progress.errors ? progress.errors.length : 0}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.errors}</div>
                        </div>
                    </div>

                    ${progress.current_product ? `
                    <div class="ggmc-current-status">
                        <div class="ggmc-current-status-label">${ggmcImportExport.strings.currentItem}</div>
                        <div class="ggmc-current-status-value">${escapeHtml(progress.current_product)}</div>
                    </div>
                    ` : ''}

                    ${errorsList ? `
                    <div class="ggmc-error-list">
                        ${errorsList}
                    </div>
                    ` : ''}
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-danger ggmc-modal-cancel" ${state.importInProgress ? '' : 'disabled'}>
                        ${ggmcImportExport.strings.cancel}
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * Get import complete HTML
     */
    function getImportCompleteHTML(progress) {
        // Store skipped images for CSV download
        state.lastSkippedImages = progress.skipped_images || [];

        var errorsList = '';
        if (progress.errors && progress.errors.length > 0) {
            progress.errors.forEach(function(err) {
                errorsList += `
                    <div class="ggmc-error-item">
                        <span class="ggmc-error-icon dashicons dashicons-warning"></span>
                        <div class="ggmc-error-content">
                            <span class="ggmc-error-row">${ggmcImportExport.strings.row} ${err.row}:</span>
                            <span class="ggmc-error-message">${escapeHtml(err.message)}</span>
                        </div>
                    </div>
                `;
            });
        }

        // Build skipped images report grouped by product
        var skippedImagesHTML = '';
        if (progress.skipped_images && progress.skipped_images.length > 0) {
            var grouped = {};
            progress.skipped_images.forEach(function(img) {
                var key = img.product || 'Unknown product';
                if (!grouped[key]) grouped[key] = [];
                grouped[key].push(img);
            });

            var items = '';
            Object.keys(grouped).forEach(function(product) {
                var imgs = grouped[product];
                var timeoutCount = imgs.filter(function(i) { return i.reason === 'timeout'; }).length;
                var failedCount = imgs.filter(function(i) { return i.reason === 'download_failed'; }).length;

                var details = [];
                if (timeoutCount > 0) details.push(timeoutCount + ' timed out');
                if (failedCount > 0) details.push(failedCount + ' failed to download');

                var urlList = '';
                imgs.forEach(function(img) {
                    var filename = img.url.split('/').pop();
                    var reason = img.reason === 'timeout' ? 'Timed out' : 'Failed';
                    urlList += '<div style="font-size: 11px; padding: 2px 0; color: #6b7280; word-break: break-all;">' +
                        '<span style="color: ' + (img.reason === 'timeout' ? '#f59e0b' : '#ef4444') + ';">[' + reason + ']</span> ' +
                        '<a href="' + escapeHtml(img.url) + '" target="_blank" style="color: #6b7280; text-decoration: underline;">' + escapeHtml(filename) + '</a>' +
                        '</div>';
                });

                items += `
                    <div class="ggmc-error-item" style="flex-direction: column; align-items: flex-start;">
                        <div style="display: flex; align-items: center; gap: 8px; width: 100%;">
                            <span class="ggmc-error-icon dashicons dashicons-format-gallery" style="color: #f59e0b;"></span>
                            <div class="ggmc-error-content">
                                <span class="ggmc-error-row" style="font-weight: 600;">${escapeHtml(product)}</span>
                                <span class="ggmc-error-message">${imgs.length} image${imgs.length !== 1 ? 's' : ''} skipped (${details.join(', ')})</span>
                            </div>
                        </div>
                        <div style="margin-left: 28px; margin-top: 4px; width: calc(100% - 28px);">
                            ${urlList}
                        </div>
                    </div>
                `;
            });

            skippedImagesHTML = `
                <div style="margin-top: 15px;">
                    <h4 style="margin: 0 0 8px; font-size: 13px; color: #f59e0b;">
                        <span class="dashicons dashicons-info" style="font-size: 16px; width: 16px; height: 16px; vertical-align: text-bottom;"></span>
                        ${progress.skipped_images.length} image${progress.skipped_images.length !== 1 ? 's' : ''} skipped during import
                    </h4>
                    <div class="ggmc-error-list" style="max-height: 150px;">
                        ${items}
                    </div>
                    <div style="margin-top: 10px; text-align: right;">
                        <button type="button" class="button ggmc-download-skipped-csv" style="font-size: 12px;">
                            <span class="dashicons dashicons-download" style="font-size: 14px; width: 14px; height: 14px; vertical-align: text-bottom;"></span>
                            Download Report (CSV)
                        </button>
                    </div>
                </div>
            `;
        }

        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>${ggmcImportExport.strings.importComplete}</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <div style="text-align: center; margin-bottom: 20px;">
                        <span class="dashicons dashicons-yes-alt" style="font-size: 48px; color: #10b981; width: 48px; height: 48px;"></span>
                    </div>

                    <div class="ggmc-stats-grid">
                        <div class="ggmc-stat-item created">
                            <div class="ggmc-stat-value">${progress.created}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.created}</div>
                        </div>
                        <div class="ggmc-stat-item updated">
                            <div class="ggmc-stat-value">${progress.updated}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.updated}</div>
                        </div>
                        <div class="ggmc-stat-item skipped">
                            <div class="ggmc-stat-value">${progress.skipped}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.skippedStat}</div>
                        </div>
                        <div class="ggmc-stat-item errors">
                            <div class="ggmc-stat-value">${progress.errors ? progress.errors.length : 0}</div>
                            <div class="ggmc-stat-label">${ggmcImportExport.strings.errors}</div>
                        </div>
                    </div>

                    ${errorsList ? `
                    <div class="ggmc-error-list" style="max-height: 200px;">
                        ${errorsList}
                    </div>
                    ` : ''}

                    ${skippedImagesHTML}
                </div>
                <div class="ggmc-modal-footer" style="display: flex; justify-content: space-between; align-items: center;">
                    <button type="button" class="button ggmc-view-import-reports" style="font-size: 12px;">View Past Reports</button>
                    <button class="ggmc-btn ggmc-btn-primary ggmc-import-done">${ggmcImportExport.strings.done}</button>
                </div>
            </div>
        `;
    }

    /**
     * Download skipped images data as CSV
     */
    function downloadSkippedImagesCSV(skippedImages) {
        if (!skippedImages || skippedImages.length === 0) return;

        var csv = 'Product,Image URL,Reason,Type\n';
        skippedImages.forEach(function(img) {
            var reason = img.reason === 'timeout' ? 'Timed out' : 'Download failed';
            var type = img.type === 'main' ? 'Main image' : 'Gallery';
            csv += '"' + (img.product || '').replace(/"/g, '""') + '",' +
                   '"' + (img.url || '').replace(/"/g, '""') + '",' +
                   '"' + reason + '",' +
                   '"' + type + '"\n';
        });

        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'skipped-images-' + new Date().toISOString().slice(0, 10) + '.csv';
        link.click();
        URL.revokeObjectURL(link.href);
    }

    /**
     * Open modal showing past import reports
     */
    function openImportReportsModal() {
        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_get_import_reports',
                nonce: ggmcImportExport.nonce
            },
            success: function(response) {
                if (response.success) {
                    state.importReports = response.data;
                    showImportReportsModal(response.data);
                }
            }
        });
    }

    /**
     * Show import reports modal
     */
    function showImportReportsModal(reports) {
        var content = '';

        if (!reports || reports.length === 0) {
            content = '<p style="text-align: center; color: #6b7280; padding: 20px 0;">No import reports found.</p>';
        } else {
            reports.forEach(function(report, index) {
                var skippedCount = report.skipped_images ? report.skipped_images.length : 0;
                var errorCount = report.errors ? report.errors.length : 0;

                content += `
                    <div style="padding: 12px; border: 1px solid #e5e7eb; border-radius: 6px; margin-bottom: 8px; background: #fafafa;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <strong style="font-size: 13px;">${escapeHtml(report.date)}</strong>
                                <div style="font-size: 12px; color: #6b7280; margin-top: 2px;">
                                    ${report.created} created, ${report.updated} updated, ${report.skipped} skipped
                                    ${errorCount > 0 ? ', <span style="color: #ef4444;">' + errorCount + ' errors</span>' : ''}
                                    ${skippedCount > 0 ? ', <span style="color: #f59e0b;">' + skippedCount + ' images skipped</span>' : ''}
                                </div>
                            </div>
                            <div style="display: flex; gap: 6px;">
                                ${skippedCount > 0 ? '<button class="button button-small ggmc-download-report-csv" data-index="' + index + '" title="Download skipped images CSV"><span class="dashicons dashicons-download" style="font-size: 14px; width: 14px; height: 14px; vertical-align: text-bottom;"></span></button>' : ''}
                                <button class="button button-small ggmc-delete-report" data-index="${index}" title="Delete report"><span class="dashicons dashicons-trash" style="font-size: 14px; width: 14px; height: 14px; vertical-align: text-bottom; color: #ef4444;"></span></button>
                            </div>
                        </div>
                    </div>
                `;
            });
        }

        var modal = `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>Import Reports</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body" style="max-height: 400px; overflow-y: auto;">
                    ${content}
                </div>
                <div class="ggmc-modal-footer" style="display: flex; justify-content: space-between;">
                    ${reports && reports.length > 0 ? '<button class="button ggmc-delete-all-reports" style="color: #ef4444;">Delete All</button>' : '<span></span>'}
                    <button class="ggmc-btn ggmc-btn-primary ggmc-modal-close">Close</button>
                </div>
            </div>
        `;

        if ($('.ggmc-modal').length) {
            $('.ggmc-modal').replaceWith(modal);
        } else {
            $('body').append(modal);
        }
    }

    /**
     * Delete a single import report
     */
    function deleteImportReport(index) {
        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_delete_import_report',
                nonce: ggmcImportExport.nonce,
                index: index
            },
            success: function(response) {
                if (response.success) {
                    openImportReportsModal(); // Refresh the list
                }
            }
        });
    }

    /**
     * Delete all import reports
     */
    function deleteAllImportReports() {
        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_delete_all_import_reports',
                nonce: ggmcImportExport.nonce
            },
            success: function(response) {
                if (response.success) {
                    openImportReportsModal(); // Refresh to show empty state
                }
            }
        });
    }

    /**
     * Get step indicator HTML
     */
    function getStepIndicatorHTML(currentStep) {
        var steps = [
            {num: 1, label: ggmcImportExport.strings.upload},
            {num: 2, label: ggmcImportExport.strings.mapFields},
            {num: 3, label: ggmcImportExport.strings.import}
        ];

        var html = '<div class="ggmc-step-indicator">';

        steps.forEach(function(step, index) {
            var className = '';
            if (step.num < currentStep) className = 'completed';
            else if (step.num === currentStep) className = 'active';

            html += `
                <div class="ggmc-step ${className}">
                    <span class="ggmc-step-number">${step.num}</span>
                    <span class="ggmc-step-label">${step.label}</span>
                </div>
            `;

            if (index < steps.length - 1) {
                html += '<div class="ggmc-step-connector"></div>';
            }
        });

        html += '</div>';
        return html;
    }

    /**
     * Get field options HTML for mapping dropdown
     */
    function getFieldOptionsHTML() {
        var html = '<option value="">' + ggmcImportExport.strings.skipColumn + '</option>';

        Object.keys(ggmcImportExport.availableFields).forEach(function(groupKey) {
            var group = ggmcImportExport.availableFields[groupKey];
            html += '<optgroup label="' + escapeHtml(group.label) + '">';

            Object.keys(group.fields).forEach(function(fieldKey) {
                var field = group.fields[fieldKey];
                html += '<option value="' + escapeHtml(fieldKey) + '">' + escapeHtml(field.label) + '</option>';
            });

            html += '</optgroup>';
        });

        return html;
    }

    /**
     * Handle file selection
     */
    function handleFileSelect(e) {
        var file = e.target.files[0];
        if (file) {
            handleFileUpload(file);
        }
    }

    /**
     * Handle file upload
     */
    function handleFileUpload(file) {
        var isJson = file.name.endsWith('.json');
        var isCsv = file.name.endsWith('.csv');

        if (!isJson && !isCsv) {
            alert('Invalid file type. Please upload a CSV or JSON file.');
            return;
        }

        var maxSize = isJson ? 50 * 1024 * 1024 : 10 * 1024 * 1024;
        if (file.size > maxSize) {
            alert(isJson ? 'File size exceeds 50MB limit.' : ggmcImportExport.strings.fileTooLarge);
            return;
        }

        state.uploadedFile = file;
        state.importFormat = isJson ? 'json' : 'csv';
        updateFileDisplay();

        // Upload and parse file
        var formData = new FormData();
        formData.append('action', isJson ? 'ggmc_upload_json_import' : 'ggmc_upload_import_file');
        formData.append('nonce', ggmcImportExport.nonce);
        formData.append('file', file);

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    if (isJson) {
                        state.jsonData = response.data;
                        state.csvData = null;
                        state.mapping = {};
                        $('.ggmc-import-next').prop('disabled', false);

                        // Show JSON format badge with summary
                        var formatBadge = '<span class="ggmc-format-badge ggm">JSON (Complete Backup)</span>';
                        $('.ggmc-file-info-meta').append(' ' + formatBadge);

                        // Show summary
                        var summary = response.data.summary || {};
                        var counts = summary.counts || {};
                        var summaryHtml = '<div class="ggmc-json-summary">' +
                            '<strong>Contents:</strong> ' +
                            (counts.products || 0) + ' products, ' +
                            (counts.categories || 0) + ' categories, ' +
                            (counts.tags || 0) + ' tags, ' +
                            (counts.attributes || 0) + ' attributes' +
                            '</div>';
                        $('.ggmc-file-info-container').append(summaryHtml);
                    } else {
                        state.csvData = response.data;
                        state.jsonData = null;
                        state.mapping = response.data.auto_mapping || {};
                        $('.ggmc-import-next').prop('disabled', false);

                        // Show format detection badge
                        var formatBadge = '';
                        if (response.data.detected_format === 'woocommerce') {
                            formatBadge = '<span class="ggmc-format-badge woocommerce">WooCommerce Format</span>';
                        } else if (response.data.detected_format === 'ggm_commerce') {
                            formatBadge = '<span class="ggmc-format-badge ggm">GGM Commerce Format</span>';
                        }

                        if (formatBadge) {
                            $('.ggmc-file-info-meta').append(' ' + formatBadge);
                        }
                    }
                } else {
                    alert(response.data.message || ggmcImportExport.strings.uploadError);
                    state.uploadedFile = null;
                    updateFileDisplay();
                }
            },
            error: function() {
                alert(ggmcImportExport.strings.uploadError);
                state.uploadedFile = null;
                updateFileDisplay();
            }
        });
    }

    /**
     * Update file display
     */
    function updateFileDisplay() {
        var $container = $('.ggmc-file-info-container');

        if (state.uploadedFile) {
            var size = formatFileSize(state.uploadedFile.size);
            $container.html(`
                <div class="ggmc-file-info">
                    <div class="ggmc-file-info-icon">
                        <span class="dashicons dashicons-media-spreadsheet"></span>
                    </div>
                    <div class="ggmc-file-info-details">
                        <div class="ggmc-file-info-name">${escapeHtml(state.uploadedFile.name)}</div>
                        <div class="ggmc-file-info-meta">${size}</div>
                    </div>
                    <button class="ggmc-file-info-remove">&times;</button>
                </div>
            `);
            $('.ggmc-import-next').prop('disabled', !state.csvData);
        } else {
            $container.html('');
            $('.ggmc-import-next').prop('disabled', true);
        }
    }

    /**
     * Handle export format change
     */
    function handleExportFormatChange() {
        var format = $('input[name="export_format"]:checked').val();

        if (format === 'json') {
            // JSON format - hide CSV include options, show JSON info box
            $('#csv-include-options').hide();
            $('#json-info-box').show();
            $('#template-btn').hide();
        } else {
            // CSV format - show CSV include options, hide JSON info box
            $('#csv-include-options').show();
            $('#json-info-box').hide();
            $('#template-btn').show();
        }
    }

    /**
     * Handle image handling change
     */
    function handleImageHandlingChange() {
        var handling = $('input[name="image_handling"]:checked').val();

        if (handling === 'package') {
            $('#export-images-btn').show();
        } else {
            $('#export-images-btn').hide();
        }
    }

    /**
     * Handle export
     */
    function handleExport() {
        var $btn = $(this);
        var format = $('input[name="export_format"]:checked').val();
        var scope = $('input[name="export_scope"]:checked').val();
        var imageHandling = $('input[name="image_handling"]:checked').val();

        // Determine which action to call based on format
        var action = (format === 'json') ? 'ggmc_export_json' : 'ggmc_export_products';

        var options = {
            format: format,
            image_handling: imageHandling,
            include_categories: $('input[name="include_categories"]').is(':checked') ? 1 : 0,
            include_tags: $('input[name="include_tags"]').is(':checked') ? 1 : 0,
            include_attributes: $('input[name="include_attributes"]').is(':checked') ? 1 : 0,
            include_variations: $('input[name="include_variations"]').is(':checked') ? 1 : 0,
            include_barcodes: $('input[name="include_barcodes"]').is(':checked') ? 1 : 0,
            include_kits: $('input[name="include_kits"]').is(':checked') ? 1 : 0,
            include_downloads: $('input[name="include_downloads"]').is(':checked') ? 1 : 0,
            include_trashed: $('input[name="include_trashed"]').is(':checked') ? 1 : 0
        };

        if (scope === 'selected') {
            options.product_ids = ggmcImportExport.selectedIds;
        }

        $btn.prop('disabled', true).html('<span class="ggmc-spinner"></span> ' + ggmcImportExport.strings.exporting);

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: action,
                nonce: ggmcImportExport.nonce,
                options: options
            },
            success: function(response) {
                if (response.success) {
                    // Trigger download
                    window.location.href = response.data.download_url;
                    closeModal();
                } else {
                    alert(response.data.message || ggmcImportExport.strings.exportError);
                }
            },
            error: function() {
                alert(ggmcImportExport.strings.exportError);
            },
            complete: function() {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-upload"></span> ' + ggmcImportExport.strings.exportProducts);
            }
        });
    }

    /**
     * Handle export image package
     */
    function handleExportImages() {
        var $btn = $(this);
        var scope = $('input[name="export_scope"]:checked').val();

        var options = {};
        if (scope === 'selected') {
            options.product_ids = ggmcImportExport.selectedIds;
        }

        $btn.prop('disabled', true).html('<span class="ggmc-spinner"></span> Preparing images...');

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_export_image_package',
                nonce: ggmcImportExport.nonce,
                options: options
            },
            success: function(response) {
                if (response.success) {
                    // Trigger download
                    window.location.href = response.data.download_url;
                } else {
                    alert(response.data.message || 'Failed to create image package');
                }
            },
            error: function() {
                alert('Failed to create image package');
            },
            complete: function() {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-format-gallery"></span> Download Image Package');
            }
        });
    }

    /**
     * Handle download template
     */
    function handleDownloadTemplate(e) {
        e.preventDefault();

        var format = $('input[name="export_format"]:checked').val() || 'simple';

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_download_template',
                nonce: ggmcImportExport.nonce,
                format: format
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = response.data.download_url;
                } else {
                    alert(response.data.message || ggmcImportExport.strings.templateError);
                }
            },
            error: function() {
                alert(ggmcImportExport.strings.templateError);
            }
        });
    }

    /**
     * Handle import next step
     */
    function handleImportNext() {
        if (state.importStep === 1) {
            // For JSON imports, skip field mapping and go directly to options
            if (state.importFormat === 'json') {
                state.importStep = 3;
                $('.ggmc-modal').replaceWith(getImportStep3HTML());
            } else {
                state.importStep = 2;
                $('.ggmc-modal').replaceWith(getImportStep2HTML());
                updateMappingCounts();
            }
        } else if (state.importStep === 2) {
            // Validate mapping (CSV only)
            var hasName = false;
            Object.values(state.mapping).forEach(function(field) {
                if (field === 'name') hasName = true;
            });

            if (!hasName) {
                alert(ggmcImportExport.strings.nameRequired);
                return;
            }

            state.importStep = 3;
            $('.ggmc-modal').replaceWith(getImportStep3HTML());
        }
    }

    /**
     * Handle import back step
     */
    function handleImportBack() {
        if (state.importStep === 2) {
            state.importStep = 1;
            $('.ggmc-modal').replaceWith(getImportStep1HTML());
            updateFileDisplay();
        } else if (state.importStep === 3) {
            state.importStep = 2;
            $('.ggmc-modal').replaceWith(getImportStep2HTML());
            updateMappingCounts();
        }
    }

    /**
     * Handle start import
     */
    function handleStartImport() {
        var options = {
            duplicate_handling: $('input[name="duplicate_handling"]:checked').val(),
            download_images: $('input[name="download_images"]').is(':checked') ? 1 : 0,
            create_categories: $('input[name="create_categories"]').is(':checked') ? 1 : 0,
            create_tags: $('input[name="create_tags"]').is(':checked') ? 1 : 0,
            create_attributes: $('input[name="create_attributes"]').is(':checked') ? 1 : 0
        };

        state.importOptions = options;
        state.importInProgress = true;

        // Check for background processing mode (JSON only)
        var processingMode = $('input[name="processing_mode"]:checked').val();
        if (state.importFormat === 'json' && processingMode === 'background') {
            handleBackgroundImport(options);
            return;
        }

        // Handle JSON import (immediate mode)
        if (state.importFormat === 'json') {
            handleJsonImport(options);
            return;
        }

        // Show progress modal for CSV
        $('.ggmc-modal').replaceWith(getImportProgressHTML({
            total: state.csvData.row_count,
            processed: 0,
            created: 0,
            updated: 0,
            skipped: 0,
            errors: [],
            current_product: ''
        }));

        // Start CSV import (initializes and processes first batch)
        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            timeout: 120000, // 2 minute timeout for image-heavy imports
            data: {
                action: 'ggmc_process_import',
                nonce: ggmcImportExport.nonce,
                file_path: state.csvData.file_path,
                mapping: state.mapping,
                options: options
            },
            success: function(response) {
                if (response.success) {
                    updateProgressDisplay(response.data);

                    // If not complete, continue processing batches
                    if (response.data.status === 'running') {
                        processNextBatch();
                    } else {
                        // Complete
                        state.importInProgress = false;
                        $('.ggmc-modal').replaceWith(getImportCompleteHTML(response.data));
                    }
                } else {
                    state.importInProgress = false;
                    alert(response.data.message || ggmcImportExport.strings.importError);
                    closeModal();
                }
            },
            error: function() {
                state.importInProgress = false;
                alert(ggmcImportExport.strings.importError);
                closeModal();
            }
        });
    }

    /**
     * Handle JSON import
     */
    function handleJsonImport(options) {
        var counts = state.jsonData.counts || {};
        var totalProducts = counts.products || 0;

        // Show progress modal
        $('.ggmc-modal').replaceWith(getImportProgressHTML({
            total: totalProducts,
            processed: 0,
            created: 0,
            updated: 0,
            skipped: 0,
            errors: [],
            current_product: 'Processing supporting data...'
        }));

        // Process JSON import
        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_process_json_import',
                nonce: ggmcImportExport.nonce,
                file_path: state.jsonData.file_path,
                options: options
            },
            timeout: 600000, // 10 minute timeout for large imports
            success: function(response) {
                state.importInProgress = false;

                if (response.success) {
                    var results = response.data.results || {};
                    var stats = results.stats || {};
                    var productStats = stats.products || {};
                    var variationStats = stats.variations || {};

                    // Build complete progress object
                    var progress = {
                        total: totalProducts,
                        processed: totalProducts,
                        created: (productStats.created || 0) + (variationStats.created || 0),
                        updated: (productStats.updated || 0) + (variationStats.updated || 0),
                        skipped: productStats.skipped || 0,
                        errors: (results.errors || []).map(function(e) {
                            return { row: 0, message: e.message };
                        }),
                        warnings: results.warnings || []
                    };

                    $('.ggmc-modal').replaceWith(getJsonImportCompleteHTML(results));
                } else {
                    var results = response.data.results || {};
                    if (results) {
                        $('.ggmc-modal').replaceWith(getJsonImportCompleteHTML(results));
                    } else {
                        alert(response.data.message || ggmcImportExport.strings.importError);
                        closeModal();
                    }
                }
            },
            error: function(xhr, status, error) {
                state.importInProgress = false;
                var message = 'Import failed';
                if (status === 'timeout') {
                    message = 'Import timed out. For very large imports, consider using background processing.';
                }
                alert(message);
                closeModal();
            }
        });
    }

    /**
     * Handle background import
     */
    function handleBackgroundImport(options) {
        var counts = state.jsonData.counts || {};
        var totalProducts = counts.products || 0;

        // Show initial background processing modal
        $('.ggmc-modal').replaceWith(getBackgroundImportStartingHTML());

        // Start background import
        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_start_background_import',
                nonce: ggmcImportExport.nonce,
                options: options
            },
            success: function(response) {
                if (response.success) {
                    state.backgroundJobId = response.data.job_id;

                    // Show background progress modal
                    $('.ggmc-modal').replaceWith(getBackgroundImportProgressHTML({
                        status: 'pending',
                        totalProducts: totalProducts,
                        processedProducts: 0,
                        currentBatch: 0,
                        totalBatches: Math.ceil(totalProducts / 50)
                    }));

                    // Start polling for status
                    pollBackgroundImportStatus();
                } else {
                    state.importInProgress = false;
                    alert(response.data.message || 'Failed to start background import');
                    closeModal();
                }
            },
            error: function() {
                state.importInProgress = false;
                alert('Failed to start background import');
                closeModal();
            }
        });
    }

    /**
     * Get background import starting HTML
     */
    function getBackgroundImportStartingHTML() {
        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>Starting Background Import...</h2>
                </div>
                <div class="ggmc-modal-body" style="text-align: center; padding: 40px;">
                    <div class="ggmc-spinner-large"></div>
                    <p style="margin-top: 20px;">Initializing background processing...</p>
                </div>
            </div>
        `;
    }

    /**
     * Get background import progress HTML
     */
    function getBackgroundImportProgressHTML(progress) {
        var percentage = progress.totalProducts > 0
            ? Math.round((progress.processedProducts / progress.totalProducts) * 100)
            : 0;

        var statusText = 'Pending...';
        var statusClass = 'pending';
        if (progress.status === 'running') {
            statusText = 'Processing...';
            statusClass = 'running';
        } else if (progress.status === 'complete') {
            statusText = 'Complete!';
            statusClass = 'complete';
        } else if (progress.status === 'failed' || progress.status === 'cancelled') {
            statusText = progress.status.charAt(0).toUpperCase() + progress.status.slice(1);
            statusClass = 'error';
        }

        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>Background Import</h2>
                </div>
                <div class="ggmc-modal-body">
                    <div class="ggmc-background-status ${statusClass}">
                        <span class="dashicons dashicons-${progress.status === 'running' ? 'update' : (progress.status === 'complete' ? 'yes-alt' : 'clock')}"></span>
                        <span>${statusText}</span>
                    </div>

                    <div class="ggmc-progress-container" style="margin: 20px 0;">
                        <div class="ggmc-progress-bar">
                            <div class="ggmc-progress-fill" style="width: ${percentage}%"></div>
                        </div>
                        <div class="ggmc-progress-text">
                            <span>${percentage}%</span>
                            <span>Batch ${progress.currentBatch} / ${progress.totalBatches}</span>
                        </div>
                    </div>

                    <div class="ggmc-background-info">
                        <p><strong>Products:</strong> ${progress.processedProducts} / ${progress.totalProducts}</p>
                        ${progress.stats ? `
                        <div class="ggmc-stats-grid" style="margin-top: 15px;">
                            <div class="ggmc-stat-item created">
                                <div class="ggmc-stat-value">${(progress.stats.products || {}).created || 0}</div>
                                <div class="ggmc-stat-label">Created</div>
                            </div>
                            <div class="ggmc-stat-item updated">
                                <div class="ggmc-stat-value">${(progress.stats.products || {}).updated || 0}</div>
                                <div class="ggmc-stat-label">Updated</div>
                            </div>
                            <div class="ggmc-stat-item skipped">
                                <div class="ggmc-stat-value">${(progress.stats.products || {}).skipped || 0}</div>
                                <div class="ggmc-stat-label">Skipped</div>
                            </div>
                            <div class="ggmc-stat-item errors">
                                <div class="ggmc-stat-value">${(progress.errors || []).length}</div>
                                <div class="ggmc-stat-label">Errors</div>
                            </div>
                        </div>
                        ` : ''}
                    </div>

                    <div class="ggmc-info-box" style="margin-top: 20px;">
                        <span class="dashicons dashicons-info-outline"></span>
                        <div class="ggmc-info-text">
                            This import is running in the background. You can safely close this window - you'll receive an email notification when it's complete.
                        </div>
                    </div>
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-background-close">Close & Continue in Background</button>
                    ${progress.status !== 'complete' && progress.status !== 'failed' && progress.status !== 'cancelled' ?
                        '<button class="ggmc-btn ggmc-btn-danger ggmc-background-cancel">Cancel Import</button>' : ''}
                    ${progress.status === 'complete' ?
                        '<button class="ggmc-btn ggmc-btn-primary ggmc-import-done">View Products</button>' : ''}
                </div>
            </div>
        `;
    }

    /**
     * Poll background import status
     */
    function pollBackgroundImportStatus() {
        if (!state.backgroundJobId) return;

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_get_background_import_status',
                nonce: ggmcImportExport.nonce,
                job_id: state.backgroundJobId
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data;
                    var progress = data.progress || {};

                    // Update display
                    $('.ggmc-modal').replaceWith(getBackgroundImportProgressHTML({
                        status: data.status,
                        totalProducts: progress.total_products || 0,
                        processedProducts: progress.processed_products || 0,
                        currentBatch: progress.current_batch || 0,
                        totalBatches: progress.total_batches || 0,
                        stats: progress.stats || {},
                        warnings: progress.warnings || [],
                        errors: progress.errors || []
                    }));

                    // Re-attach event handlers
                    attachBackgroundEventHandlers();

                    // Continue polling if not complete
                    if (data.status === 'pending' || data.status === 'running') {
                        setTimeout(pollBackgroundImportStatus, 3000); // Poll every 3 seconds
                    } else {
                        state.importInProgress = false;
                    }
                } else {
                    // Job not found or error
                    state.importInProgress = false;
                }
            },
            error: function() {
                // On error, continue polling with backoff
                setTimeout(pollBackgroundImportStatus, 5000);
            }
        });
    }

    /**
     * Attach background import event handlers
     */
    function attachBackgroundEventHandlers() {
        // Close button
        $('.ggmc-background-close').off('click').on('click', function(e) {
            e.preventDefault();
            state.importInProgress = false;
            closeModal();
        });

        // Cancel button
        $('.ggmc-background-cancel').off('click').on('click', function(e) {
            e.preventDefault();
            if (confirm('Are you sure you want to cancel this import? Any imported data will remain.')) {
                cancelBackgroundImport();
            }
        });
    }

    /**
     * Cancel background import
     */
    function cancelBackgroundImport() {
        if (!state.backgroundJobId) return;

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_cancel_background_import',
                nonce: ggmcImportExport.nonce,
                job_id: state.backgroundJobId
            },
            success: function(response) {
                state.importInProgress = false;
                state.backgroundJobId = null;
                if (response.success) {
                    alert('Import cancelled successfully.');
                }
                closeModal();
            },
            error: function() {
                alert('Failed to cancel import.');
            }
        });
    }

    /**
     * Get JSON import complete HTML
     */
    function getJsonImportCompleteHTML(results) {
        var stats = results.stats || {};
        var warnings = results.warnings || [];
        var errors = results.errors || [];
        var placeholders = results.placeholders || [];

        // Calculate totals
        var totalCreated = 0;
        var totalUpdated = 0;
        var totalSkipped = 0;

        Object.keys(stats).forEach(function(key) {
            totalCreated += stats[key].created || 0;
            totalUpdated += stats[key].updated || 0;
            totalSkipped += stats[key].skipped || 0;
        });

        var warningsHtml = '';
        if (warnings.length > 0) {
            warningsHtml = '<div class="ggmc-import-warnings"><h4>Warnings (' + warnings.length + ')</h4>';
            warnings.slice(0, 10).forEach(function(w) {
                warningsHtml += '<div class="ggmc-warning-item"><span class="dashicons dashicons-warning"></span>' + escapeHtml(w.message) + '</div>';
            });
            if (warnings.length > 10) {
                warningsHtml += '<div class="ggmc-more-warnings">...and ' + (warnings.length - 10) + ' more warnings</div>';
            }
            warningsHtml += '</div>';
        }

        var placeholdersHtml = '';
        if (placeholders.length > 0) {
            placeholdersHtml = '<div class="ggmc-import-placeholders"><h4>Placeholder Products Created</h4>' +
                '<p>The following SKUs were referenced by kit components but not found in the import. Placeholder products were created:</p>' +
                '<ul>';
            placeholders.forEach(function(sku) {
                placeholdersHtml += '<li>' + escapeHtml(sku) + '</li>';
            });
            placeholdersHtml += '</ul></div>';
        }

        return `
            <div class="ggmc-modal">
                <div class="ggmc-modal-header">
                    <h2>${ggmcImportExport.strings.importComplete}</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <div style="text-align: center; margin-bottom: 20px;">
                        <span class="dashicons dashicons-yes-alt" style="font-size: 48px; color: #10b981; width: 48px; height: 48px;"></span>
                    </div>

                    <div class="ggmc-import-summary">
                        <h4>Import Summary</h4>
                        <table class="ggmc-summary-table">
                            <tr><th>Entity</th><th>Created</th><th>Updated</th><th>Skipped</th></tr>
                            ${Object.keys(stats).map(function(key) {
                                return '<tr><td>' + key.replace(/_/g, ' ') + '</td><td>' +
                                    (stats[key].created || 0) + '</td><td>' +
                                    (stats[key].updated || 0) + '</td><td>' +
                                    (stats[key].skipped || 0) + '</td></tr>';
                            }).join('')}
                            <tr class="ggmc-summary-totals"><td><strong>Total</strong></td><td><strong>${totalCreated}</strong></td><td><strong>${totalUpdated}</strong></td><td><strong>${totalSkipped}</strong></td></tr>
                        </table>
                    </div>

                    ${warningsHtml}
                    ${placeholdersHtml}

                    ${errors.length > 0 ? `
                    <div class="ggmc-import-errors">
                        <h4>Errors (${errors.length})</h4>
                        ${errors.slice(0, 5).map(function(e) {
                            return '<div class="ggmc-error-item"><span class="dashicons dashicons-dismiss"></span>' + escapeHtml(e.message) + '</div>';
                        }).join('')}
                    </div>
                    ` : ''}
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-primary ggmc-import-done">${ggmcImportExport.strings.done}</button>
                </div>
            </div>
        `;
    }

    /**
     * Process next batch of imports
     */
    function processNextBatch() {
        if (!state.importInProgress) return;

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            timeout: 120000, // 2 minute timeout for image-heavy imports
            data: {
                action: 'ggmc_get_import_progress',
                nonce: ggmcImportExport.nonce
            },
            success: function(response) {
                if (response.success) {
                    updateProgressDisplay(response.data);

                    if (response.data.status === 'running' && state.importInProgress) {
                        // Small delay to prevent hammering the server, then process next batch
                        setTimeout(processNextBatch, 100);
                    } else if (response.data.status === 'complete') {
                        // Done!
                        state.importInProgress = false;
                        $('.ggmc-modal').replaceWith(getImportCompleteHTML(response.data));
                    } else {
                        // Error or unknown status
                        state.importInProgress = false;
                        closeModal();
                    }
                } else {
                    state.importInProgress = false;
                    alert(response.data.message || ggmcImportExport.strings.importError);
                    closeModal();
                }
            },
            error: function() {
                state.importInProgress = false;
                alert(ggmcImportExport.strings.importError);
                closeModal();
            }
        });
    }

    /**
     * Poll import progress (legacy - now redirects to processNextBatch)
     */
    function pollImportProgress() {
        processNextBatch();
    }

    /**
     * Update progress display
     */
    function updateProgressDisplay(progress) {
        var percentage = progress.total > 0 ? Math.round((progress.processed / progress.total) * 100) : 0;

        $('.ggmc-progress-fill').css('width', percentage + '%');
        $('.ggmc-progress-text span:first').text(percentage + '%');
        $('.ggmc-progress-text span:last').text(progress.processed + ' / ' + progress.total);

        $('.ggmc-stat-item.created .ggmc-stat-value').text(progress.created);
        $('.ggmc-stat-item.updated .ggmc-stat-value').text(progress.updated);
        $('.ggmc-stat-item.skipped .ggmc-stat-value').text(progress.skipped);
        $('.ggmc-stat-item.errors .ggmc-stat-value').text(progress.errors ? progress.errors.length : 0);
    }

    /**
     * Update mapping status indicator
     */
    function updateMappingStatus($row, fieldValue) {
        var $status = $row.find('.ggmc-mapping-status');

        if (fieldValue) {
            $status.removeClass('skipped mapped matched').addClass('mapped');
            $status.text('⚠ Mapped');
        } else {
            $status.removeClass('skipped mapped matched').addClass('skipped');
            $status.text('⊘ Skip');
        }

        updateMappingCounts();
    }

    /**
     * Update mapping counts
     */
    function updateMappingCounts() {
        var mapped = 0;
        var skipped = 0;

        Object.values(state.mapping).forEach(function(field) {
            if (field) {
                mapped++;
            } else {
                skipped++;
            }
        });

        $('#mapped-count .ggmc-mapping-stat-value').text(mapped);
        $('#skipped-count .ggmc-mapping-stat-value').text(skipped);
    }

    /**
     * Escape HTML
     */
    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Truncate string
     */
    function truncate(str, length) {
        if (!str) return '';
        return str.length > length ? str.substring(0, length) + '...' : str;
    }

    /**
     * Format file size
     */
    function formatFileSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    }

    // =====================================================
    // IMAGE RE-ASSOCIATION TOOL
    // =====================================================

    /**
     * Open image re-association modal
     */
    function openImageReassociationModal() {
        var html = getImageReassociationModalHTML();
        showModal(html);
    }

    /**
     * Get image re-association modal HTML
     */
    function getImageReassociationModalHTML() {
        return `
            <div class="ggmc-modal ggmc-modal-wide">
                <div class="ggmc-modal-header">
                    <h2>Image Re-association Tool</h2>
                    <button class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <div class="ggmc-info-box" style="margin-top: 0; margin-bottom: 20px;">
                        <span class="dashicons dashicons-info-outline"></span>
                        <div class="ggmc-info-text">
                            This tool helps match images in your media library to products. Use it after uploading product images to automatically associate them with the correct products.
                        </div>
                    </div>

                    <div class="ggmc-reassoc-options">
                        <div class="ggmc-form-group">
                            <label>Choose Method:</label>
                            <div class="ggmc-radio-options">
                                <label class="ggmc-radio-option selected">
                                    <input type="radio" name="reassoc_method" value="scan" checked>
                                    <div class="ggmc-radio-option-content">
                                        <div class="ggmc-radio-option-title">Auto-Scan Media Library</div>
                                        <div class="ggmc-radio-option-desc">Scan all images in the media library and match them to products based on SKU patterns in filenames.</div>
                                    </div>
                                </label>
                                <label class="ggmc-radio-option">
                                    <input type="radio" name="reassoc_method" value="manifest">
                                    <div class="ggmc-radio-option-content">
                                        <div class="ggmc-radio-option-title">Use Manifest File</div>
                                        <div class="ggmc-radio-option-desc">Upload the manifest.json file from an image package export for precise matching.</div>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>

                    <div id="ggmc-reassoc-results"></div>
                </div>
                <div class="ggmc-modal-footer">
                    <button class="ggmc-btn ggmc-btn-secondary ggmc-modal-cancel">Cancel</button>
                    <button class="ggmc-btn ggmc-btn-primary ggmc-scan-media">
                        <span class="dashicons dashicons-search"></span>
                        Scan Media Library
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * Handle scan media library
     */
    function handleScanMedia() {
        var $btn = $(this);
        var method = $('input[name="reassoc_method"]:checked').val();

        if (method === 'manifest') {
            // Show manifest upload UI
            showManifestUploadUI();
            return;
        }

        $btn.prop('disabled', true).html('<span class="ggmc-spinner"></span> Scanning...');

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_scan_media_for_products',
                nonce: ggmcImportExport.nonce
            },
            success: function(response) {
                if (response.success) {
                    showScanResults(response.data);
                } else {
                    alert(response.data.message || 'Scan failed');
                }
            },
            error: function() {
                alert('Scan failed. Please try again.');
            },
            complete: function() {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-search"></span> Scan Media Library');
            }
        });
    }

    /**
     * Show manifest upload UI
     */
    function showManifestUploadUI() {
        var html = `
            <div class="ggmc-manifest-upload">
                <h4>Upload Manifest File</h4>
                <p>Select the manifest.json file from your image package export:</p>
                <div class="ggmc-file-upload" style="margin-bottom: 15px;">
                    <input type="file" accept=".json" id="manifest-file-input">
                    <div class="ggmc-file-upload-icon">
                        <span class="dashicons dashicons-upload"></span>
                    </div>
                    <div class="ggmc-file-upload-text">Click to select manifest.json</div>
                </div>
            </div>
        `;

        $('#ggmc-reassoc-results').html(html);

        // Handle file selection
        $('#manifest-file-input').on('change', function(e) {
            var file = e.target.files[0];
            if (file) {
                uploadManifest(file);
            }
        });

        // Update button
        $('.ggmc-scan-media').text('Select Manifest File');
    }

    /**
     * Upload manifest file
     */
    function uploadManifest(file) {
        var formData = new FormData();
        formData.append('action', 'ggmc_upload_image_manifest');
        formData.append('nonce', ggmcImportExport.nonce);
        formData.append('manifest', file);

        $('#ggmc-reassoc-results').html('<div style="text-align: center; padding: 40px;"><div class="ggmc-spinner-large"></div><p>Processing manifest...</p></div>');

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    showManifestResults(response.data);
                } else {
                    alert(response.data.message || 'Failed to process manifest');
                    showManifestUploadUI();
                }
            },
            error: function() {
                alert('Failed to upload manifest. Please try again.');
                showManifestUploadUI();
            }
        });
    }

    /**
     * Handle upload manifest button click
     */
    function handleUploadManifest() {
        $('#manifest-file-input').click();
    }

    /**
     * Show scan results
     */
    function showScanResults(data) {
        var matchesHtml = '';

        if (data.matches.length > 0) {
            matchesHtml = `
                <div class="ggmc-reassoc-matches">
                    <h4>Found ${data.matches.length} Matches</h4>
                    <div class="ggmc-matches-actions">
                        <label class="ggmc-checkbox-option">
                            <input type="checkbox" id="select-all-matches" checked>
                            Select All
                        </label>
                    </div>
                    <div class="ggmc-matches-list" style="max-height: 300px; overflow-y: auto;">
                        <table class="ggmc-summary-table">
                            <thead>
                                <tr>
                                    <th style="width: 40px;"></th>
                                    <th>Image</th>
                                    <th>Product</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
            `;

            data.matches.forEach(function(match, index) {
                var statusText = match.has_image ? 'Has Image' : 'No Image';
                var statusClass = match.has_image ? 'warning' : 'success';

                matchesHtml += `
                    <tr>
                        <td><input type="checkbox" class="ggmc-match-checkbox" data-index="${index}" data-product="${match.product_id}" data-attachment="${match.attachment_id}" checked></td>
                        <td>
                            <div class="ggmc-match-image">
                                <img src="${match.url}" alt="" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;">
                                <span>${escapeHtml(match.filename)}</span>
                            </div>
                        </td>
                        <td>
                            <strong>${escapeHtml(match.product_name)}</strong><br>
                            <small>SKU: ${escapeHtml(match.product_sku)}</small>
                        </td>
                        <td><span class="ggmc-badge ggmc-badge-${statusClass}">${statusText}</span></td>
                    </tr>
                `;
            });

            matchesHtml += `
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        }

        var summaryHtml = `
            <div class="ggmc-reassoc-summary">
                <div class="ggmc-stats-grid">
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value">${data.total_media}</div>
                        <div class="ggmc-stat-label">Images Scanned</div>
                    </div>
                    <div class="ggmc-stat-item">
                        <div class="ggmc-stat-value">${data.total_products}</div>
                        <div class="ggmc-stat-label">Products</div>
                    </div>
                    <div class="ggmc-stat-item created">
                        <div class="ggmc-stat-value">${data.matches.length}</div>
                        <div class="ggmc-stat-label">Matches Found</div>
                    </div>
                    <div class="ggmc-stat-item skipped">
                        <div class="ggmc-stat-value">${data.products_without_images.length}</div>
                        <div class="ggmc-stat-label">Missing Images</div>
                    </div>
                </div>
            </div>
        `;

        var html = summaryHtml + matchesHtml;

        if (data.matches.length === 0) {
            html += `
                <div class="ggmc-warning-box" style="margin-top: 20px;">
                    <span class="ggmc-warning-icon dashicons dashicons-warning"></span>
                    <div class="ggmc-warning-text">No matches found. Make sure your image filenames contain the product SKU.</div>
                </div>
            `;
        }

        $('#ggmc-reassoc-results').html(html);
        state.scanMatches = data.matches;

        // Update footer
        if (data.matches.length > 0) {
            $('.ggmc-modal-footer').html(`
                <button class="ggmc-btn ggmc-btn-secondary ggmc-modal-cancel">Cancel</button>
                <button class="ggmc-btn ggmc-btn-success ggmc-apply-associations">
                    <span class="dashicons dashicons-yes-alt"></span>
                    Apply <span class="selected-count">${data.matches.length}</span> Associations
                </button>
            `);
        }

        // Select all handler
        $('#select-all-matches').on('change', function() {
            $('.ggmc-match-checkbox').prop('checked', $(this).is(':checked'));
            updateSelectedAssociations();
        });
    }

    /**
     * Show manifest results
     */
    function showManifestResults(data) {
        var matches = data.matches.matches || [];
        var missingImages = data.matches.missing_images || [];
        var missingProducts = data.matches.missing_products || [];

        var matchesHtml = '';

        if (matches.length > 0) {
            matchesHtml = `
                <div class="ggmc-reassoc-matches">
                    <h4>Found ${matches.length} Matches from Manifest</h4>
                    <div class="ggmc-matches-actions">
                        <label class="ggmc-checkbox-option">
                            <input type="checkbox" id="select-all-matches" checked>
                            Select All
                        </label>
                    </div>
                    <div class="ggmc-matches-list" style="max-height: 250px; overflow-y: auto;">
                        <table class="ggmc-summary-table">
                            <thead>
                                <tr>
                                    <th style="width: 40px;"></th>
                                    <th>Image</th>
                                    <th>Product</th>
                                    <th>Type</th>
                                </tr>
                            </thead>
                            <tbody>
            `;

            matches.forEach(function(match, index) {
                var typeText = match.is_primary ? 'Primary' : 'Gallery';
                var typeClass = match.is_primary ? 'success' : 'info';

                matchesHtml += `
                    <tr>
                        <td><input type="checkbox" class="ggmc-match-checkbox" data-index="${index}" data-product="${match.product_id}" data-attachment="${match.attachment_id}" data-primary="${match.is_primary ? 1 : 0}" checked></td>
                        <td>
                            <div class="ggmc-match-image">
                                <img src="${match.url}" alt="" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;">
                                <span>${escapeHtml(match.filename)}</span>
                            </div>
                        </td>
                        <td>
                            <strong>${escapeHtml(match.product_name)}</strong><br>
                            <small>SKU: ${escapeHtml(match.product_sku)}</small>
                        </td>
                        <td><span class="ggmc-badge ggmc-badge-${typeClass}">${typeText}</span></td>
                    </tr>
                `;
            });

            matchesHtml += `
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        }

        var summaryHtml = `
            <div class="ggmc-reassoc-summary">
                <div class="ggmc-stats-grid">
                    <div class="ggmc-stat-item created">
                        <div class="ggmc-stat-value">${matches.length}</div>
                        <div class="ggmc-stat-label">Matches</div>
                    </div>
                    <div class="ggmc-stat-item errors">
                        <div class="ggmc-stat-value">${missingImages.length}</div>
                        <div class="ggmc-stat-label">Missing Images</div>
                    </div>
                    <div class="ggmc-stat-item skipped">
                        <div class="ggmc-stat-value">${missingProducts.length}</div>
                        <div class="ggmc-stat-label">Missing Products</div>
                    </div>
                </div>
            </div>
        `;

        var warningsHtml = '';
        if (missingImages.length > 0) {
            warningsHtml += `
                <div class="ggmc-import-warnings" style="margin-top: 15px;">
                    <h4>Missing Images (${missingImages.length})</h4>
                    ${missingImages.slice(0, 5).map(function(m) {
                        return '<div class="ggmc-warning-item"><span class="dashicons dashicons-warning"></span>' + escapeHtml(m.filename) + ' for ' + escapeHtml(m.product_name) + '</div>';
                    }).join('')}
                    ${missingImages.length > 5 ? '<div class="ggmc-more-warnings">...and ' + (missingImages.length - 5) + ' more</div>' : ''}
                </div>
            `;
        }

        var html = summaryHtml + matchesHtml + warningsHtml;

        $('#ggmc-reassoc-results').html(html);
        state.scanMatches = matches;

        // Update footer
        if (matches.length > 0) {
            $('.ggmc-modal-footer').html(`
                <button class="ggmc-btn ggmc-btn-secondary ggmc-modal-cancel">Cancel</button>
                <button class="ggmc-btn ggmc-btn-success ggmc-apply-associations">
                    <span class="dashicons dashicons-yes-alt"></span>
                    Apply <span class="selected-count">${matches.length}</span> Associations
                </button>
            `);
        }

        // Select all handler
        $('#select-all-matches').on('change', function() {
            $('.ggmc-match-checkbox').prop('checked', $(this).is(':checked'));
            updateSelectedAssociations();
        });
    }

    /**
     * Update selected associations count
     */
    function updateSelectedAssociations() {
        var count = $('.ggmc-match-checkbox:checked').length;
        $('.selected-count').text(count);
    }

    /**
     * Handle apply associations
     */
    function handleApplyAssociations() {
        var $btn = $(this);
        var associations = [];

        $('.ggmc-match-checkbox:checked').each(function() {
            associations.push({
                product_id: $(this).data('product'),
                attachment_id: $(this).data('attachment'),
                is_primary: $(this).data('primary') == 1 || !$(this).data('primary') // Default to primary for scan matches
            });
        });

        if (associations.length === 0) {
            alert('Please select at least one association to apply.');
            return;
        }

        $btn.prop('disabled', true).html('<span class="ggmc-spinner"></span> Applying...');

        $.ajax({
            url: ggmcImportExport.ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_reassociate_images',
                nonce: ggmcImportExport.nonce,
                associations: associations
            },
            success: function(response) {
                if (response.success) {
                    var results = response.data.results;
                    showAssociationComplete(results);
                } else {
                    alert(response.data.message || 'Failed to apply associations');
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt"></span> Apply Associations');
                }
            },
            error: function() {
                alert('Failed to apply associations. Please try again.');
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt"></span> Apply Associations');
            }
        });
    }

    /**
     * Show association complete screen
     */
    function showAssociationComplete(results) {
        var html = `
            <div style="text-align: center; padding: 20px;">
                <span class="dashicons dashicons-yes-alt" style="font-size: 48px; color: #10b981; width: 48px; height: 48px;"></span>
                <h3 style="margin-top: 15px;">Associations Applied Successfully!</h3>
                <p>${results.updated} product(s) updated with new images.</p>
            </div>
        `;

        $('#ggmc-reassoc-results').html(html);

        $('.ggmc-modal-footer').html(`
            <button class="ggmc-btn ggmc-btn-primary ggmc-import-done">Done</button>
        `);
    }

})(jQuery);
