/**
 * ================================================================
 * LASSO IMPORTER - CLIENT-SIDE BATCHING LOGIC
 * ================================================================
 */

(function($) {
    'use strict';
    
    const BATCH_SIZE = 50; // Process 50 products at a time
    
    let totalProducts = 0;
    let currentBatch = 0;
    let totalBatches = 0;
    let processedCount = 0;
    let allLassoProducts = [];
    let productMap = {}; // Lasso ID → DripBox ID
    
    /**
     * Start Import Button
     */
    $('#dbx-start-import').on('click', function() {
    // Check backup confirmation
    if (!$('#dbx-backup-confirm').is(':checked')) {
        alert('⚠️ Please confirm that you have backed up your database before proceeding.');
        $('#dbx-backup-confirm').focus();
        return;
    }
    
    if (!confirm('This will import all Lasso products to DripBox.\n\nYour original Lasso products will remain untouched.\n\nContinue?')) {
        return;
    }
        
        $(this).prop('disabled', true).text('Starting...');
        $('#dbx-import-progress').show();
        
        // Step 1: Collect all Lasso data
        collectLassoData();
    });
    
    /**
     * STEP 1: Collect Lasso products from database
     */
    function collectLassoData() {
        updateProgress('Collecting Lasso products from database...', 0);
        
        $.ajax({
            url: dripboxImporter.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_collect_lasso',
                nonce: dripboxImporter.nonce
            },
            success: function(response) {
                if (response.success) {
                    allLassoProducts = response.data.products;
                    totalProducts = allLassoProducts.length;
                    totalBatches = Math.ceil(totalProducts / BATCH_SIZE);
                    
                    console.log('✅ Collected ' + totalProducts + ' products');
                    console.log('📦 Will process in ' + totalBatches + ' batches');
                    
                    // Step 2: Start batch processing
                    processBatch(0);
                } else {
                    showError('Failed to collect products: ' + response.data.message);
                }
            },
            error: function(xhr, status, error) {
                showError('Connection error: ' + error);
            }
        });
    }
    
    /**
     * STEP 2: Process one batch at a time
     */
    function processBatch(batchIndex) {
        // Check if all batches are done
        if (batchIndex >= totalBatches) {
            console.log('✅ All batches processed!');
            // Step 3: Replace shortcodes
            replaceShortcodes();
            return;
        }
        
        currentBatch = batchIndex + 1;
        
        // Get products for this batch
        const start = batchIndex * BATCH_SIZE;
        const end = Math.min(start + BATCH_SIZE, totalProducts);
        const batchProducts = allLassoProducts.slice(start, end);
        
        console.log('📦 Processing batch ' + currentBatch + ' of ' + totalBatches + ' (' + batchProducts.length + ' products)');
        
        // Update UI
        const batchPercent = (batchIndex / totalBatches) * 80; // 0-80% for batches
        updateProgress(
            'Converting batch ' + currentBatch + ' of ' + totalBatches + '...',
            batchPercent
        );
        
        // Send batch to server for conversion
        $.ajax({
            url: dripboxImporter.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_convert_batch',
                nonce: dripboxImporter.nonce,
                batch: JSON.stringify(batchProducts),
                batch_index: batchIndex
            },
            success: function(response) {
                if (response.success) {
                    // Merge mapping
                    $.extend(productMap, response.data.map);
                    
                    // Update count
                    processedCount += response.data.count;
                    $('#dbx-progress-count').text(processedCount + ' / ' + totalProducts + ' products imported');
                    
                    console.log('✅ Batch ' + currentBatch + ' done: ' + response.data.count + ' products saved');
                    
                    // Process next batch (with small delay to avoid overwhelming server)
                    setTimeout(function() {
                        processBatch(batchIndex + 1);
                    }, 500);
                    
                } else {
                    showError('Error in batch ' + currentBatch + ': ' + response.data.message);
                }
            },
            error: function(xhr, status, error) {
                showError('Connection error in batch ' + currentBatch + ': ' + error);
            }
        });
    }
    
    /**
     * STEP 3: Replace shortcodes in all posts
     */
    function replaceShortcodes() {
        console.log('🔄 Replacing shortcodes in posts...');
        
        updateProgress('Updating shortcodes in your posts...', 85);
        
        $.ajax({
            url: dripboxImporter.ajax_url,
            type: 'POST',
            data: {
                action: 'dripbox_replace_shortcodes',
                nonce: dripboxImporter.nonce,
                map: JSON.stringify(productMap)
            },
            success: function(response) {
                if (response.success) {
                    console.log('✅ Import complete!');
                    showResults(response.data);
                } else {
                    showError('Error replacing shortcodes: ' + response.data.message);
                }
            },
            error: function(xhr, status, error) {
                showError('Connection error while updating posts: ' + error);
            }
        });
    }
    
    /**
     * Update progress bar and text
     */
    function updateProgress(message, percent) {
        $('#dbx-progress-text').text(message);
        $('#dbx-progress-fill').css('width', percent + '%');
    }
    
    /**
     * Show final results
     */
    function showResults(data) {
        updateProgress('Import complete!', 100);
        
        setTimeout(function() {
            $('#dbx-import-progress').hide();
            $('#dbx-import-results').show();
            
            $('#dbx-result-message').html(
                '<strong>🎉 ' + data.products_count + ' products imported successfully!</strong><br>' +
                '<br>' +
                data.posts_updated + ' posts were updated with new DripBox shortcodes.<br>' +
                'Your articles are now using DripBox instead of Lasso!'
            );
        }, 1000);
    }
    
    /**
     * Show error message
     */
    function showError(message) {
        console.error('❌ Error:', message);
        
        $('#dbx-import-progress').hide();
        
        alert('Import Failed\n\n' + message + '\n\nPlease try again or contact support if the problem persists.');
        
        // Re-enable button
        $('#dbx-start-import').prop('disabled', false).html('<span class="dashicons dashicons-download"></span> Start Import');
    }
    
})(jQuery);
