/**
 * PinnerPress Migration Admin JavaScript
 *
 * @since 0.6.8
 */

(function($) {
    'use strict';

    /**
     * Migration functionality
     */
    var PinnerPressMigration = {
        
        /**
         * Initialize migration interface
         */
        init: function() {
            this.bindEvents();
        },
        
        /**
         * Bind event handlers
         */
        bindEvents: function() {
            $('#pinnerpress-scan-hubbub').on('click', this.scanHubbubData);
            $('#pinnerpress-migrate-hubbub').on('click', this.migrateFromHubbub);
            $('#pinnerpress-scan-tasty-pins').on('click', this.scanTastyPinsData);
            $('#pinnerpress-migrate-tasty-pins').on('click', this.migrateFromTastyPins);
            $('#pinnerpress-scan-essb').on('click', this.scanESSBData);
            $('#pinnerpress-migrate-essb').on('click', this.migrateFromESSB);
        },
        
        /**
         * Scan for Hubbub data
         */
        scanHubbubData: function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var $results = $('#pinnerpress-migration-results');
            var $migrateButton = $('#pinnerpress-migrate-hubbub');
            
            // Show loading state
            $button.prop('disabled', true).text(pinnerpress_migration_vars.scanning);
            $results.hide();
            $migrateButton.hide();
            
            // AJAX request
            $.ajax({
                url: pinnerpress_migration_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'pinnerpress_scan_hubbub_data',
                    nonce: pinnerpress_migration_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        PinnerPressMigration.displayScanResults(response.data);
                        
                        // Show migrate button if data found
                        if (response.data.options.length > 0 || response.data.posts_with_images > 0) {
                            $migrateButton.show();
                        }
                    } else {
                        PinnerPressMigration.showError(pinnerpress_migration_vars.scan_error);
                    }
                },
                error: function() {
                    PinnerPressMigration.showError(pinnerpress_migration_vars.ajax_error);
                },
                complete: function() {
                    $button.prop('disabled', false).text(pinnerpress_migration_vars.scan_button_text);
                }
            });
        },
        
        /**
         * Display scan results
         */
        displayScanResults: function(data) {
            var $results = $('#pinnerpress-migration-results');
            var html = '<h4>' + pinnerpress_migration_vars.scan_results_title + '</h4>';
            
            // Show Hubbub status
            if (data.hubbub_active) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>' + pinnerpress_migration_vars.hubbub_active + '</strong>';
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-error">';
                html += '<strong>' + pinnerpress_migration_vars.hubbub_inactive + '</strong>';
                html += '</div>';
            }
            
            // Show settings found
            if (data.options.length > 0) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>' + pinnerpress_migration_vars.settings_found + ':</strong> ' + data.options.length;
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>' + pinnerpress_migration_vars.settings_found + ':</strong> ' + data.options.length;
                html += '</div>';
            }
            
            // Show Pinterest URL/Username if found
            if (data.pinterest_url) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>' + pinnerpress_migration_vars.pinterest_url_found + ':</strong> ' + data.pinterest_url;
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += pinnerpress_migration_vars.no_pinterest_url;
                html += '</div>';
            }
            
            // Show hidden images info
            if (data.posts_with_images > 0) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>' + pinnerpress_migration_vars.posts_with_images + ':</strong> ' + data.posts_with_images;
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>' + pinnerpress_migration_vars.posts_with_images + ':</strong> ' + data.posts_with_images;
                html += '</div>';
            }
            
            if (data.total_images > 0) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>' + pinnerpress_migration_vars.total_images + ':</strong> ' + data.total_images;
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>' + pinnerpress_migration_vars.total_images + ':</strong> ' + data.total_images;
                html += '</div>';
            }
            
            // Show pin button position if found
            if (data.pin_button_position) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>Pin button position found:</strong> ' + data.pin_button_position;
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += 'No pin button position setting found';
                html += '</div>';
            }
            
            // Show button text settings if found
            if (data.button_text_settings && Object.keys(data.button_text_settings).length > 0) {
                if (data.button_text_settings.button_text) {
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>Button text found:</strong> "' + data.button_text_settings.button_text + '"';
                    html += '</div>';
                }
                if (data.button_text_settings.show_button_text) {
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>Show button text:</strong> ' + data.button_text_settings.show_button_text;
                    html += '</div>';
                }
                if (data.button_text_settings.minimum_image_width) {
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>Minimum image width:</strong> ' + data.button_text_settings.minimum_image_width + 'px';
                    html += '</div>';
                }
            }
            
            // Show options details if available
            if (data.options.length > 0) {
                html += '<details style="margin-top: 15px;">';
                html += '<summary>' + pinnerpress_migration_vars.hubbub_settings_details + '</summary>';
                html += '<ul style="margin-top: 10px;">';
                data.options.forEach(function(option) {
                    html += '<li><code>' + option.option_name + '</code>: ' + option.option_value.substring(0, 100);
                    if (option.option_value.length > 100) {
                        html += '...';
                    }
                    html += '</li>';
                });
                html += '</ul>';
                html += '</details>';
            }
            
            // Show debug information
            if (data.debug_info) {
                html += '<details style="margin-top: 15px;">';
                html += '<summary>Debug Information</summary>';
                html += '<div style="margin-top: 10px; font-family: monospace; font-size: 12px;">';
                html += '<p><strong>Active Plugins:</strong> ' + data.debug_info.active_plugins_count + '</p>';
                if (data.debug_info.active_plugins.length > 0) {
                    html += '<p><strong>Plugin List (first 20):</strong></p><ul>';
                    data.debug_info.active_plugins.forEach(function(plugin) {
                        html += '<li>' + plugin + '</li>';
                    });
                    html += '</ul>';
                }
                html += '<p><strong>Function Checks:</strong></p><ul>';
                for (var func in data.debug_info.functions_exist) {
                    html += '<li>' + func + ': ' + (data.debug_info.functions_exist[func] ? 'EXISTS' : 'NOT FOUND') + '</li>';
                }
                html += '</ul>';
                html += '</div>';
                html += '</details>';
            }
            
            // Show detailed database analysis
            if (data.database_analysis) {
                html += '<details style="margin-top: 15px;">';
                html += '<summary>Database Analysis (All Pinterest/Social Data Found)</summary>';
                html += '<div style="margin-top: 10px; font-family: monospace; font-size: 12px;">';
                
                if (data.database_analysis.all_options && data.database_analysis.all_options.length > 0) {
                    html += '<h4>WordPress Options:</h4>';
                    data.database_analysis.all_options.forEach(function(option) {
                        html += '<div style="margin: 5px 0; padding: 5px; border: 1px solid #ddd; background: #f9f9f9;">';
                        html += '<strong>' + option.option_name + ':</strong><br>';
                        html += '<span style="word-break: break-all;">' + option.option_value + '</span>';
                        html += '</div>';
                    });
                }
                
                if (data.database_analysis.postmeta_keys && data.database_analysis.postmeta_keys.length > 0) {
                    html += '<h4>Post Meta Keys Found:</h4>';
                    data.database_analysis.postmeta_keys.forEach(function(meta) {
                        html += '<div><strong>' + meta.meta_key + '</strong> (found in ' + meta.count + ' posts)</div>';
                    });
                }
                
                if (data.database_analysis.hubbub_tables && data.database_analysis.hubbub_tables.length > 0) {
                    html += '<h4>Custom Hubbub Tables:</h4>';
                    data.database_analysis.hubbub_tables.forEach(function(table) {
                        html += '<div>' + table[0] + '</div>';
                    });
                }
                
                html += '</div>';
                html += '</details>';
            }
            
            // Show Pinterest settings analysis
            if (data.pinterest_analysis) {
                html += '<details style="margin-top: 15px;">';
                html += '<summary>Pinterest Settings Analysis</summary>';
                html += '<div style="margin-top: 10px; font-family: monospace; font-size: 12px;">';
                
                // Show Pinterest username search results first
                if (data.pinterest_analysis.username_search && data.pinterest_analysis.username_search.length > 0) {
                    data.pinterest_analysis.username_search.forEach(function(result) {
                        if (result.extracted_username === 'PATTERN_NOT_MATCHED') {
                            html += '<h4>🔍 Debug Info for dpsp_settings:</h4>';
                            html += '<div style="background: #fff3cd; padding: 10px; margin: 5px 0; border: 1px solid #ffc107;">';
                            html += '<strong>Status:</strong> ' + result.pattern_found + '<br>';
                            html += '<strong>Regex Used:</strong> ' + result.debug_regex + '<br>';
                            html += '<strong>Contains "pinterest_username":</strong> ' + result.debug_contains_pinterest + '<br>';
                            html += '</div>';
                        } else {
                            html += '<h4>🔍 Found Pinterest username in dpsp_settings:</h4>';
                            html += '<div style="background: #e8f5e8; padding: 10px; margin: 5px 0; border: 1px solid #4CAF50;">';
                            html += '<strong>Option:</strong> ' + result.option_name + '<br>';
                            html += '<strong>Pattern Found:</strong> ' + result.pattern_found + '<br>';
                            html += '<strong>Extracted Username:</strong> ' + result.extracted_username + '<br>';
                            html += '<strong>Will construct URL:</strong> https://www.pinterest.com/' + result.extracted_username + '/<br>';
                            html += '</div>';
                        }
                    });
                } else {
                    html += '<div style="background: #fff3cd; padding: 10px; margin: 5px 0; border: 1px solid #ffc107;">';
                    html += '⚠️ No pinterest_username pattern found in dpsp_settings option';
                    html += '</div>';
                }
                
                // Show raw dpsp_settings data
                if (data.pinterest_analysis.dpsp_settings_raw) {
                    html += '<h4>Raw dpsp_settings Data:</h4>';
                    html += '<div style="background: #f0f0f0; padding: 10px; word-break: break-all; max-height: 300px; overflow-y: auto; font-size: 11px; border: 1px solid #ccc;">';
                    // Convert to string if it's an object
                    if (typeof data.pinterest_analysis.dpsp_settings_raw === 'object') {
                        html += JSON.stringify(data.pinterest_analysis.dpsp_settings_raw);
                    } else {
                        html += data.pinterest_analysis.dpsp_settings_raw;
                    }
                    html += '</div>';
                }
                
                if (data.pinterest_analysis.dpsp_raw) {
                    html += '<h4>DPSP Pinterest Share Images Settings:</h4>';
                    html += '<div style="background: #f0f0f0; padding: 10px; word-break: break-all; max-height: 200px; overflow-y: auto;">';
                    html += data.pinterest_analysis.dpsp_raw;
                    html += '</div>';
                }
                
                if (data.pinterest_analysis.dpsp_keys) {
                    html += '<h4>Available Keys:</h4>';
                    html += '<ul>';
                    data.pinterest_analysis.dpsp_keys.forEach(function(key) {
                        html += '<li>' + key + '</li>';
                    });
                    html += '</ul>';
                }
                
                if (data.pinterest_analysis.potential_username_fields) {
                    html += '<h4>Potential Username Fields:</h4>';
                    for (var field in data.pinterest_analysis.potential_username_fields) {
                        html += '<div><strong>' + field + ':</strong> ' + data.pinterest_analysis.potential_username_fields[field] + '</div>';
                    }
                }
                
                if (data.pinterest_analysis.other_pinterest_options) {
                    html += '<h4>Other Pinterest Options:</h4>';
                    for (var option in data.pinterest_analysis.other_pinterest_options) {
                        html += '<div><strong>' + option + ':</strong> ' + data.pinterest_analysis.other_pinterest_options[option] + '</div>';
                    }
                }
                
                html += '</div>';
                html += '</details>';
            }
            
            $results.html(html).show();
        },
        
        /**
         * Migrate from Hubbub
         */
        migrateFromHubbub: function(e) {
            e.preventDefault();
            
            if (!confirm(pinnerpress_migration_vars.migration_confirm)) {
                return;
            }
            
            var $button = $(this);
            var $scanButton = $('#pinnerpress-scan-hubbub');
            var $progress = $('#pinnerpress-migration-progress');
            var $results = $('#pinnerpress-migration-results');
            
            // Show progress
            $button.prop('disabled', true);
            $scanButton.prop('disabled', true);
            $progress.show();
            PinnerPressMigration.updateProgress(0, pinnerpress_migration_vars.migration_starting);
            
            // AJAX request
            $.ajax({
                url: pinnerpress_migration_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'pinnerpress_migrate_from_hubbub',
                    nonce: pinnerpress_migration_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        if (response.data.use_batch_processing) {
                            // Start batch processing
                            PinnerPressMigration.processBatches(response.data.migration_id, response.data.total_posts);
                        } else {
                            // Old single-operation migration
                            PinnerPressMigration.updateProgress(100, pinnerpress_migration_vars.migration_complete);
                            PinnerPressMigration.displayMigrationResults(response.data);
                        }
                    } else {
                        PinnerPressMigration.updateProgress(0, pinnerpress_migration_vars.migration_failed);
                        PinnerPressMigration.showError(pinnerpress_migration_vars.migration_error);
                    }
                },
                error: function() {
                    PinnerPressMigration.updateProgress(0, pinnerpress_migration_vars.migration_failed);
                    PinnerPressMigration.showError(pinnerpress_migration_vars.ajax_error);
                },
                complete: function() {
                    setTimeout(function() {
                        $progress.hide();
                        $button.prop('disabled', false);
                        $scanButton.prop('disabled', false);
                    }, 2000);
                }
            });
        },
        
        /**
         * Update progress bar
         */
        updateProgress: function(percentage, text) {
            var $progressFill = $('#pinnerpress-migration-progress .pinnerpress-progress-fill');
            $progressFill.css('width', percentage + '%');
            
            // Change color based on status
            if (percentage >= 100) {
                $progressFill.css('background-color', '#4CAF50'); // Green for success
            } else if (percentage === 0 && text && text.toLowerCase().includes('failed')) {
                $progressFill.css('background-color', '#f44336'); // Red for error
            } else {
                $progressFill.css('background-color', '#E60023'); // Pinterest red for progress
            }
            
            $('#pinnerpress-migration-progress .pinnerpress-progress-text').text(text);
        },
        
        /**
         * Display migration results
         */
        displayMigrationResults: function(data) {
            var $results = $('#pinnerpress-migration-results');
            var html = '<h4>' + pinnerpress_migration_vars.migration_results_title + '</h4>';
            
            // Settings migration results
            if (data.settings_migration) {
                if (data.settings_migration.success) {
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>' + pinnerpress_migration_vars.settings_migration_success + '</strong>';
                    data.settings_migration.messages.forEach(function(message) {
                        html += '<br>' + message;
                    });
                    html += '</div>';
                } else {
                    html += '<div class="pinnerpress-migration-error">';
                    html += '<strong>' + pinnerpress_migration_vars.settings_migration_failed + '</strong>';
                    data.settings_migration.messages.forEach(function(message) {
                        html += '<br>' + message;
                    });
                    html += '</div>';
                }
            }
            
            // Images migration results
            if (data.images_migration) {
                if (data.images_migration.success) {
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>' + pinnerpress_migration_vars.images_migration_success + '</strong>';
                    html += '<br>' + pinnerpress_migration_vars.migrated_posts + ': ' + data.images_migration.migrated_posts;
                    html += '<br>' + pinnerpress_migration_vars.migrated_images + ': ' + data.images_migration.migrated_images;
                    html += '</div>';
                } else {
                    html += '<div class="pinnerpress-migration-error">';
                    html += '<strong>' + pinnerpress_migration_vars.images_migration_failed + '</strong>';
                    if (data.images_migration.errors.length > 0) {
                        data.images_migration.errors.forEach(function(error) {
                            html += '<br>' + error;
                        });
                    }
                    html += '</div>';
                }
                
                // Show any messages
                if (data.images_migration.messages.length > 0) {
                    html += '<div class="pinnerpress-migration-info">';
                    data.images_migration.messages.forEach(function(message) {
                        html += message + '<br>';
                    });
                    html += '</div>';
                }
            }
            
            // Overall success messages
            if (data.messages.length > 0) {
                html += '<div class="pinnerpress-migration-success">';
                data.messages.forEach(function(message) {
                    html += message + '<br>';
                });
                html += '</div>';
            }
            
            // Important next steps (for non-batch migration)
            if (data.success) {
                html += '<div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin-top: 20px;">';
                html += '<h4 style="margin-top: 0; color: #856404;">⚠️ Important Next Steps</h4>';
                html += '<ol style="margin: 10px 0; color: #856404;">';
                html += '<li style="margin-bottom: 10px;">';
                html += '<strong>Disable Hubbub\'s Image Hover Pinterest Button:</strong><br>';
                html += 'To avoid conflicts, please disable the Hubbub Pinterest button feature.<br>';
                html += '<a href="/wp-admin/admin.php?page=dpsp-toolkit" target="_blank" class="button button-secondary" style="margin-top: 5px;">Open Hubbub Settings (new tab)</a>';
                html += '</li>';
                html += '<li style="margin-top: 15px;">';
                html += '<strong>Continue PinnerPress Setup:</strong><br>';
                html += 'Review and customize your migrated settings in PinnerPress.<br>';
                html += '<a href="/wp-admin/admin.php?page=pinnerpress-settings&tab=general" class="button button-primary" style="margin-top: 5px;">Continue to PinnerPress Settings</a>';
                html += '</li>';
                html += '</ol>';
                html += '</div>';
            }
            
            $results.html(html);
            
            // Hide migrate button after successful migration
            if (data.success) {
                $('#pinnerpress-migrate-hubbub').hide();
            }
        },
        
        /**
         * Process migration in batches
         */
        processBatches: function(migrationId, totalPosts) {
            var currentBatch = 0;
            var totalProcessed = 0;
            var totalMigratedImages = 0;
            var errors = [];
            
            PinnerPressMigration.updateProgress(5, 'Processing posts in batches... (0/' + totalPosts + ')');
            
            function processBatch() {
                $.ajax({
                    url: pinnerpress_migration_vars.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'pinnerpress_migrate_batch',
                        migration_id: migrationId,
                        nonce: pinnerpress_migration_vars.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            var data = response.data;
                            totalProcessed = data.progress.processed;
                            totalMigratedImages += data.batch_results.migrated_images;
                            
                            if (data.batch_results.errors.length > 0) {
                                errors = errors.concat(data.batch_results.errors);
                            }
                            
                            // Update progress
                            var progressText = 'Processing posts... (' + totalProcessed + '/' + totalPosts + ')';
                            PinnerPressMigration.updateProgress(data.progress.percentage, progressText);
                            
                            if (data.migration_complete) {
                                // Migration complete
                                PinnerPressMigration.updateProgress(100, pinnerpress_migration_vars.migration_complete);
                                PinnerPressMigration.displayBatchMigrationResults({
                                    total_posts: totalPosts,
                                    migrated_posts: totalProcessed,
                                    migrated_images: totalMigratedImages,
                                    errors: errors
                                });
                                
                                // Hide migrate button (no auto-reload so user can see instructions)
                                $('#pinnerpress-migrate-hubbub').hide();
                            } else if (data.next_batch !== null) {
                                // Continue with next batch
                                setTimeout(processBatch, 500); // Small delay between batches
                            }
                        } else {
                            PinnerPressMigration.updateProgress(0, 'Batch processing failed');
                            PinnerPressMigration.showError('Migration failed during batch processing');
                        }
                    },
                    error: function() {
                        PinnerPressMigration.updateProgress(0, 'Batch processing failed');
                        PinnerPressMigration.showError(pinnerpress_migration_vars.ajax_error);
                    }
                });
            }
            
            // Start processing
            processBatch();
        },
        
        /**
         * Display batch migration results
         */
        displayBatchMigrationResults: function(data) {
            var $results = $('#pinnerpress-migration-results');
            var html = '<h4>' + pinnerpress_migration_vars.migration_results_title + '</h4>';
            
            // Settings migration (already done)
            html += '<div class="pinnerpress-migration-success">';
            html += '<strong>Settings migrated successfully</strong>';
            html += '</div>';
            
            // Images migration results
            html += '<div class="pinnerpress-migration-success">';
            html += '<strong>Images Migration Complete</strong>';
            html += '<br>Posts processed: ' + data.migrated_posts + '/' + data.total_posts;
            html += '<br>Total images migrated: ' + data.migrated_images;
            html += '</div>';
            
            // Show errors if any
            if (data.errors.length > 0) {
                html += '<div class="pinnerpress-migration-error">';
                html += '<strong>Errors encountered:</strong>';
                data.errors.forEach(function(error) {
                    html += '<br>' + error;
                });
                html += '</div>';
            }
            
            html += '<div class="pinnerpress-migration-success">';
            html += '✅ Migration completed successfully!';
            html += '</div>';
            
            // Important next steps
            html += '<div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px; margin-top: 20px;">';
            html += '<h4 style="margin-top: 0; color: #856404;">⚠️ Important Next Steps</h4>';
            html += '<ol style="margin: 10px 0; color: #856404;">';
            html += '<li style="margin-bottom: 10px;">';
            html += '<strong>Disable Hubbub\'s Image Hover Pinterest Button:</strong><br>';
            html += 'To avoid conflicts, please disable the Hubbub Pinterest button feature.<br>';
            html += '<a href="/wp-admin/admin.php?page=dpsp-toolkit" target="_blank" class="button button-secondary" style="margin-top: 5px;">Open Hubbub Settings (new tab)</a>';
            html += '</li>';
            html += '<li style="margin-top: 15px;">';
            html += '<strong>Continue PinnerPress Setup:</strong><br>';
            html += 'Review and customize your migrated settings in PinnerPress.<br>';
            html += '<a href="/wp-admin/admin.php?page=pinnerpress-settings&tab=general" class="button button-primary" style="margin-top: 5px;">Continue to PinnerPress Settings</a>';
            html += '</li>';
            html += '</ol>';
            html += '</div>';
            
            $results.html(html);
        },
        
        /**
         * Show error message
         */
        showError: function(message) {
            var $results = $('#pinnerpress-migration-results');
            var html = '<div class="pinnerpress-migration-error">' + message + '</div>';
            $results.html(html).show();
        },
        
        /**
         * Scan for Tasty Pins data
         */
        scanTastyPinsData: function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var $results = $('#pinnerpress-tasty-pins-migration-results');
            var $migrateButton = $('#pinnerpress-migrate-tasty-pins');
            
            // Show loading state
            $button.prop('disabled', true).text('Scanning...');
            $results.hide();
            $migrateButton.hide();
            
            // AJAX request
            $.ajax({
                url: pinnerpress_migration_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'pinnerpress_scan_tasty_pins_data',
                    nonce: pinnerpress_migration_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        PinnerPressMigration.displayTastyPinsScanResults(response.data);
                        
                        // Show migrate button if data found
                        if (response.data.settings && Object.keys(response.data.settings).length > 0 || 
                            response.data.posts_with_images > 0) {
                            $migrateButton.show();
                        }
                    } else {
                        PinnerPressMigration.showTastyPinsError('Failed to scan for Tasty Pins data');
                    }
                },
                error: function() {
                    PinnerPressMigration.showTastyPinsError('Network error while scanning');
                },
                complete: function() {
                    $button.prop('disabled', false).text('Scan for Tasty Pins Data');
                }
            });
        },
        
        /**
         * Display Tasty Pins scan results
         */
        displayTastyPinsScanResults: function(data) {
            var $results = $('#pinnerpress-tasty-pins-migration-results');
            var html = '<h4>Tasty Pins Data Found:</h4>';
            
            // Show if Tasty Pins is active
            if (data.tasty_pins_active) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>✓ Tasty Pins detected</strong>';
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>Tasty Pins not currently active (but data may still exist)</strong>';
                html += '</div>';
            }
            
            // Show settings found
            if (data.settings && Object.keys(data.settings).length > 0) {
                var settingsCount = 0;
                
                if (data.settings.tasty_pins_settings) {
                    settingsCount++;
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>✓ Pin button settings found</strong>';
                    if (data.button_settings) {
                        if (data.button_settings.custom_text) {
                            html += '<br>&nbsp;&nbsp;• Button text: "' + data.button_settings.custom_text + '"';
                        }
                        if (data.button_settings.button_color) {
                            html += '<br>&nbsp;&nbsp;• Button color: ' + data.button_settings.button_color;
                        }
                        if (data.button_settings.position) {
                            html += '<br>&nbsp;&nbsp;• Position: ' + data.button_settings.position;
                        }
                    }
                    html += '</div>';
                }
                
                if (data.settings.tasty_pins_follow_box) {
                    settingsCount++;
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>✓ Follow box settings found</strong>';
                    html += '</div>';
                }
                
                if (data.settings.tasty_pins_banner) {
                    settingsCount++;
                    html += '<div class="pinnerpress-migration-success">';
                    html += '<strong>✓ Banner settings found</strong>';
                    html += '</div>';
                }
                
                if (settingsCount === 0) {
                    html += '<div class="pinnerpress-migration-info">';
                    html += '<strong>No Tasty Pins settings found</strong>';
                    html += '</div>';
                }
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>No Tasty Pins settings found</strong>';
                html += '</div>';
            }
            
            // Show hidden images info
            if (data.posts_with_images > 0) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>✓ Hidden Pinterest images found</strong>';
                html += '<br>&nbsp;&nbsp;• Posts with hidden images: ' + data.posts_with_images;
                html += '<br>&nbsp;&nbsp;• Total hidden images: ' + data.total_images;
                html += '</div>';
                
                // Show debug breakdown if available
                if (data.debug_hidden_images && data.debug_hidden_images.posts_breakdown) {
                    html += '<details style="margin-top: 10px;">';
                    html += '<summary>Debug: Images per Post</summary>';
                    html += '<div style="margin-top: 10px; font-family: monospace; font-size: 12px;">';
                    html += '<p><strong>Total meta entries found:</strong> ' + data.debug_hidden_images.total_meta_entries + '</p>';
                    html += '<p><strong>Breakdown by post:</strong></p>';
                    html += '<ul>';
                    
                    for (var postId in data.debug_hidden_images.posts_breakdown) {
                        var postData = data.debug_hidden_images.posts_breakdown[postId];
                        html += '<li><strong>Post ' + postId + ':</strong> ' + postData.count + ' images';
                        html += '<br><em>Raw value:</em> <code>' + postData.raw_value + '</code>';
                        html += '<ul>';
                        postData.images.forEach(function(imageId) {
                            html += '<li>Image ID: ' + imageId + '</li>';
                        });
                        html += '</ul></li>';
                    }
                    
                    html += '</ul>';
                    html += '</div>';
                    html += '</details>';
                }
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>No hidden Pinterest images found</strong>';
                html += '</div>';
            }
            
            $results.html(html).show();
        },
        
        /**
         * Migrate from Tasty Pins
         */
        migrateFromTastyPins: function(e) {
            e.preventDefault();
            
            if (!confirm('Are you sure you want to migrate from Tasty Pins? This will import all settings and hidden images.')) {
                return;
            }
            
            var $button = $(this);
            var $scanButton = $('#pinnerpress-scan-tasty-pins');
            var $progress = $('#pinnerpress-tasty-pins-migration-progress');
            var $results = $('#pinnerpress-tasty-pins-migration-results');
            
            // Show progress and hide results div
            $button.prop('disabled', true);
            $scanButton.prop('disabled', true);
            $progress.show();
            $results.hide(); // Hide scan results
            PinnerPressMigration.updateTastyPinsProgress(0, 'Starting migration...');
            
            // AJAX request
            $.ajax({
                url: pinnerpress_migration_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'pinnerpress_migrate_from_tasty_pins',
                    nonce: pinnerpress_migration_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Update progress to show settings migrated
                        PinnerPressMigration.updateTastyPinsProgress(10, 'Settings migrated. Processing hidden images...');
                        
                        if (response.data.use_batch_processing) {
                            // Start batch processing for hidden images
                            PinnerPressMigration.processTastyPinsBatches(
                                response.data.migration_id, 
                                response.data.total_posts,
                                response.data.settings_results
                            );
                        } else {
                            // No hidden images, just settings
                            PinnerPressMigration.updateTastyPinsProgress(100, 'Migration complete!');
                            setTimeout(function() {
                                PinnerPressMigration.displayTastyPinsMigrationResults(response.data);
                            }, 1500);
                        }
                    } else {
                        PinnerPressMigration.updateTastyPinsProgress(0, 'Migration failed');
                        PinnerPressMigration.showTastyPinsError('Migration failed. Please try again.');
                        $button.prop('disabled', false);
                        $scanButton.prop('disabled', false);
                    }
                },
                error: function() {
                    PinnerPressMigration.updateTastyPinsProgress(0, 'Migration failed');
                    PinnerPressMigration.showTastyPinsError('Network error during migration');
                    $button.prop('disabled', false);
                    $scanButton.prop('disabled', false);
                }
            });
        },
        
        /**
         * Process Tasty Pins migration in batches
         */
        processTastyPinsBatches: function(migrationId, totalPosts, settingsResults) {
            var totalProcessed = 0;
            var totalMigratedImages = 0;
            var errors = [];
            
            // Start at 10% since settings are already done
            var baseProgress = 10;
            var progressRange = 90; // 10% to 100%
            
            PinnerPressMigration.updateTastyPinsProgress(baseProgress, 'Processing posts with hidden images... (0/' + totalPosts + ')');
            
            function processBatch() {
                $.ajax({
                    url: pinnerpress_migration_vars.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'pinnerpress_migrate_tasty_pins_batch',
                        migration_id: migrationId,
                        nonce: pinnerpress_migration_vars.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            var data = response.data;
                            totalProcessed = data.progress.processed;
                            totalMigratedImages += data.batch_results.migrated_images;
                            
                            if (data.batch_results.errors.length > 0) {
                                errors = errors.concat(data.batch_results.errors);
                            }
                            
                            // Calculate progress (10% to 100%)
                            var progressPercent = baseProgress + ((totalProcessed / totalPosts) * progressRange);
                            var progressText = 'Processing posts with hidden images... (' + totalProcessed + '/' + totalPosts + ' posts, ' + totalMigratedImages + ' images)';
                            PinnerPressMigration.updateTastyPinsProgress(Math.round(progressPercent), progressText);
                            
                            if (data.migration_complete) {
                                // Migration complete
                                PinnerPressMigration.updateTastyPinsProgress(100, 'Migration complete! ' + totalMigratedImages + ' images from ' + totalProcessed + ' posts');
                                
                                // Wait a moment then show completion
                                setTimeout(function() {
                                    PinnerPressMigration.displayTastyPinsCompletionMessage({
                                        settings_results: settingsResults,
                                        total_posts: totalPosts,
                                        migrated_posts: totalProcessed,
                                        migrated_images: totalMigratedImages,
                                        errors: errors
                                    });
                                }, 1500);
                            } else if (data.next_batch !== null) {
                                // Continue with next batch
                                setTimeout(processBatch, 200); // Slightly faster
                            }
                        } else {
                            PinnerPressMigration.updateTastyPinsProgress(0, 'Batch processing failed');
                            PinnerPressMigration.showTastyPinsError('Migration failed during batch processing');
                            $('#pinnerpress-migrate-tasty-pins').prop('disabled', false);
                            $('#pinnerpress-scan-tasty-pins').prop('disabled', false);
                        }
                    },
                    error: function() {
                        PinnerPressMigration.updateTastyPinsProgress(0, 'Batch processing failed');
                        PinnerPressMigration.showTastyPinsError('Network error during batch processing');
                        $('#pinnerpress-migrate-tasty-pins').prop('disabled', false);
                        $('#pinnerpress-scan-tasty-pins').prop('disabled', false);
                    }
                });
            }
            
            // Start processing
            processBatch();
        },
        
        /**
         * Update Tasty Pins progress bar
         */
        updateTastyPinsProgress: function(percentage, text) {
            var $progressFill = $('#pinnerpress-tasty-pins-migration-progress .pinnerpress-progress-fill');
            $progressFill.css('width', percentage + '%');
            
            // Change color based on status
            if (percentage >= 100) {
                $progressFill.css('background-color', '#4CAF50'); // Green for success
            } else if (percentage === 0 && text && text.toLowerCase().includes('failed')) {
                $progressFill.css('background-color', '#f44336'); // Red for error
            } else {
                $progressFill.css('background-color', '#E60023'); // Pinterest red for progress
            }
            
            $('#pinnerpress-tasty-pins-migration-progress .pinnerpress-progress-text').text(text);
        },
        
        /**
         * Display Tasty Pins migration results (no hidden images)
         */
        displayTastyPinsMigrationResults: function(data) {
            // Build and show the complete migration results
            var html = PinnerPressMigration.buildTastyPinsCompleteMigrationHTML(data.settings_results, 0, 0);
            
            // Show in results div (replaces scan results)
            $('#pinnerpress-tasty-pins-migration-results').html(html).show();
            
            // Hide progress and migrate button
            $('#pinnerpress-tasty-pins-migration-progress').hide();
            $('#pinnerpress-migrate-tasty-pins').hide();
            $('#pinnerpress-scan-tasty-pins').prop('disabled', false);
        },
        
        /**
         * Display Tasty Pins completion message
         */
        displayTastyPinsCompletionMessage: function(data) {
            // Build and show the complete migration results
            var html = PinnerPressMigration.buildTastyPinsCompleteMigrationHTML(
                data.settings_results, 
                data.migrated_posts, 
                data.migrated_images
            );
            
            // Show in results div (replaces scan results)
            $('#pinnerpress-tasty-pins-migration-results').html(html).show();
            
            // Hide progress and migrate button  
            $('#pinnerpress-tasty-pins-migration-progress').hide();
            $('#pinnerpress-migrate-tasty-pins').hide();
            $('#pinnerpress-scan-tasty-pins').prop('disabled', false);
        },
        
        /**
         * Build complete Tasty Pins migration HTML
         */
        buildTastyPinsCompleteMigrationHTML: function(settingsResults, posts, images) {
            var html = '<div class="pinnerpress-migration-success" style="background: #d4edda; border: 1px solid #c3e6cb; padding: 15px; border-radius: 4px; margin-bottom: 20px;">';
            html += '<h4 style="margin-top: 0; color: #155724;">✅ Migration Complete!</h4>';
            html += '<p><strong>Settings Migrated:</strong></p>';
            html += '<ul style="margin: 10px 0;">';
            
            // Button settings
            if (settingsResults && settingsResults.button && settingsResults.button.success) {
                html += '<li>✓ Pin button settings';
                if (settingsResults.button.messages.length > 0) {
                    html += '<ul>';
                    settingsResults.button.messages.forEach(function(msg) {
                        html += '<li>' + msg + '</li>';
                    });
                    html += '</ul>';
                }
                html += '</li>';
            }
            
            // Follow box settings
            if (settingsResults && settingsResults.follow_box && settingsResults.follow_box.success) {
                html += '<li>✓ Follow box configuration</li>';
            }
            
            // Banner settings
            if (settingsResults && settingsResults.banner && settingsResults.banner.success) {
                html += '<li>✓ Banner settings</li>';
            }
            
            // Hidden images
            if (posts > 0) {
                html += '<li>✓ Hidden images: <strong>' + images + ' images</strong> across <strong>' + posts + ' posts</strong></li>';
            }
            
            html += '</ul>';
            html += '</div>';
            
            // Next Steps section
            html += '<div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px;">';
            html += '<h4 style="margin-top: 0; color: #856404;">Next Steps:</h4>';
            html += '<ol style="margin: 10px 0;">';
            html += '<li style="margin-bottom: 15px;">';
            html += '<a href="/wp-admin/admin.php?page=tasty" target="_blank" class="button button-secondary">';
            html += 'Deactivate Tasty Pins';
            html += '</a>';
            html += '<span style="margin-left: 10px; color: #666;">(Opens in new tab)</span>';
            html += '</li>';
            html += '<li>';
            html += '<a href="/wp-admin/admin.php?page=pinnerpress-settings" class="button button-primary">';
            html += 'Continue to PinnerPress Setup';
            html += '</a>';
            html += '</li>';
            html += '</ol>';
            html += '<p style="margin-top: 15px; padding: 10px; background: #fff; border-left: 4px solid #ffc107;">';
            html += '<strong>Important:</strong> Please deactivate Tasty Pins to avoid conflicts with PinnerPress.';
            html += '</p>';
            html += '</div>';
            
            return html;
        },
        
        /**
         * Show Tasty Pins error message
         */
        showTastyPinsError: function(message) {
            var $results = $('#pinnerpress-tasty-pins-migration-results');
            var html = '<div class="pinnerpress-migration-error">' + message + '</div>';
            $results.html(html).show();
        },
        
        /**
         * Scan for ESSB data
         */
        scanESSBData: function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var $results = $('#pinnerpress-essb-migration-results');
            var $migrateButton = $('#pinnerpress-migrate-essb');
            
            // Show loading state
            $button.prop('disabled', true).text('Scanning...');
            $results.hide();
            $migrateButton.hide();
            
            // AJAX request
            $.ajax({
                url: pinnerpress_migration_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'pinnerpress_scan_essb_data',
                    nonce: pinnerpress_migration_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        PinnerPressMigration.displayESSBScanResults(response.data);
                        
                        // Show migrate button if data found
                        if ((response.data.pinterest_settings && Object.keys(response.data.pinterest_settings).length > 0) || 
                            response.data.posts_with_images > 0) {
                            $migrateButton.show();
                        }
                    } else {
                        PinnerPressMigration.showESSBError('Failed to scan for ESSB data');
                    }
                },
                error: function() {
                    PinnerPressMigration.showESSBError('Network error while scanning');
                },
                complete: function() {
                    $button.prop('disabled', false).text('Scan for ESSB Data');
                }
            });
        },
        
        /**
         * Display ESSB scan results
         */
        displayESSBScanResults: function(data) {
            var $results = $('#pinnerpress-essb-migration-results');
            var html = '<h4>Easy Social Share Buttons Data Found:</h4>';
            
            // Show if ESSB is active
            if (data.essb_active) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>✓ ESSB detected</strong>';
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>ESSB not currently active (but data may still exist)</strong>';
                html += '</div>';
            }
            
            // Show if custom table exists
            if (data.table_exists) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>✓ ESSB custom table found (wp_essb_post_meta)</strong>';
                html += '</div>';
            }
            
            // Show Pinterest settings found
            if (data.pinterest_settings && Object.keys(data.pinterest_settings).length > 0) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>✓ Pinterest settings found:</strong>';
                
                if (data.migration_preview && data.migration_preview.length > 0) {
                    html += '<ul style="margin-top: 5px;">';
                    data.migration_preview.forEach(function(setting) {
                        html += '<li>' + setting.label + ': <strong>' + setting.value + '</strong></li>';
                    });
                    html += '</ul>';
                }
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>No ESSB Pinterest settings found</strong>';
                html += '</div>';
            }
            
            // Show hidden images info
            if (data.posts_with_images > 0) {
                html += '<div class="pinnerpress-migration-success">';
                html += '<strong>✓ Hidden Pinterest images found</strong>';
                html += '<br>&nbsp;&nbsp;• Posts with hidden images: ' + data.posts_with_images;
                html += '<br>&nbsp;&nbsp;• Total hidden images: ' + data.total_images;
                html += '</div>';
            } else {
                html += '<div class="pinnerpress-migration-info">';
                html += '<strong>No hidden Pinterest images found</strong>';
                html += '</div>';
            }
            
            // Show debug information if available
            if (data.debug) {
                html += '<details style="margin-top: 15px;">';
                html += '<summary>Debug Information</summary>';
                html += '<div style="margin-top: 10px; font-family: monospace; font-size: 12px; background: #f5f5f5; padding: 10px; border-radius: 4px;">';
                
                if (data.debug.options_found && data.debug.options_found.length > 0) {
                    html += '<p><strong>ESSB Options Found:</strong></p>';
                    html += '<ul>';
                    data.debug.options_found.forEach(function(option) {
                        html += '<li>' + option + '</li>';
                    });
                    html += '</ul>';
                }
                
                // Show structure of each option
                for (var key in data.debug) {
                    if (key.startsWith('option_') && key.endsWith('_keys')) {
                        var optionName = key.replace('option_', '').replace('_keys', '');
                        html += '<p><strong>Keys in ' + optionName + ':</strong></p>';
                        html += '<ul style="max-height: 200px; overflow-y: auto;">';
                        data.debug[key].forEach(function(k) {
                            html += '<li>' + k + '</li>';
                        });
                        html += '</ul>';
                    }
                }
                
                // Show Pinterest-specific keys found
                for (var key in data.debug) {
                    if (key.startsWith('pinterest_keys_in_')) {
                        var optionName = key.replace('pinterest_keys_in_', '');
                        html += '<p><strong>Pinterest Keys Found in ' + optionName + ':</strong></p>';
                        html += '<ul>';
                        for (var pkey in data.debug[key]) {
                            html += '<li><strong>' + pkey + ':</strong> ' + data.debug[key][pkey] + '</li>';
                        }
                        html += '</ul>';
                    }
                }
                
                html += '<p><strong>Summary:</strong></p>';
                html += '<ul>';
                html += '<li>Total ESSB options found: ' + data.debug.settings_count + '</li>';
                html += '<li>Pinterest settings extracted: ' + data.debug.pinterest_settings_count + '</li>';
                html += '</ul>';
                
                html += '</div>';
                html += '</details>';
            }
            
            $results.html(html).show();
        },
        
        /**
         * Migrate from ESSB
         */
        migrateFromESSB: function(e) {
            e.preventDefault();
            
            if (!confirm('Are you sure you want to migrate from Easy Social Share Buttons? This will import all Pinterest settings and hidden images.')) {
                return;
            }
            
            var $button = $(this);
            var $scanButton = $('#pinnerpress-scan-essb');
            var $progress = $('#pinnerpress-essb-migration-progress');
            var $results = $('#pinnerpress-essb-migration-results');
            
            // Show progress and hide results div
            $button.prop('disabled', true);
            $scanButton.prop('disabled', true);
            $progress.show();
            $results.hide();
            PinnerPressMigration.updateESSBProgress(0, 'Starting migration...');
            
            // AJAX request
            $.ajax({
                url: pinnerpress_migration_vars.ajax_url,
                type: 'POST',
                data: {
                    action: 'pinnerpress_migrate_from_essb',
                    nonce: pinnerpress_migration_vars.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Update progress to show settings migrated
                        PinnerPressMigration.updateESSBProgress(10, 'Settings migrated. Processing hidden images...');
                        
                        if (response.data.use_batch_processing && response.data.total_posts > 0) {
                            // Start batch processing for hidden images
                            PinnerPressMigration.processESSBBatches(
                                response.data.migration_id, 
                                response.data.total_posts,
                                response.data.settings_migration
                            );
                        } else {
                            // No hidden images, just settings
                            PinnerPressMigration.updateESSBProgress(100, 'Migration complete!');
                            setTimeout(function() {
                                PinnerPressMigration.displayESSBMigrationResults(response.data);
                            }, 1500);
                        }
                    } else {
                        PinnerPressMigration.updateESSBProgress(0, 'Migration failed');
                        PinnerPressMigration.showESSBError('Migration failed. Please try again.');
                        $button.prop('disabled', false);
                        $scanButton.prop('disabled', false);
                    }
                },
                error: function() {
                    PinnerPressMigration.updateESSBProgress(0, 'Migration failed');
                    PinnerPressMigration.showESSBError('Network error during migration');
                    $button.prop('disabled', false);
                    $scanButton.prop('disabled', false);
                }
            });
        },
        
        /**
         * Process ESSB migration in batches
         */
        processESSBBatches: function(migrationId, totalPosts, settingsResults) {
            var totalProcessed = 0;
            var totalMigratedImages = 0;
            var errors = [];
            
            // Start at 10% since settings are already done
            var baseProgress = 10;
            var progressRange = 90; // 10% to 100%
            
            PinnerPressMigration.updateESSBProgress(baseProgress, 'Processing posts with hidden images... (0/' + totalPosts + ')');
            
            function processBatch() {
                $.ajax({
                    url: pinnerpress_migration_vars.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'pinnerpress_migrate_essb_batch',
                        migration_id: migrationId,
                        nonce: pinnerpress_migration_vars.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            var data = response.data;
                            totalProcessed = data.progress.processed;
                            totalMigratedImages += data.batch_results.migrated_images;
                            
                            if (data.batch_results.errors.length > 0) {
                                errors = errors.concat(data.batch_results.errors);
                            }
                            
                            // Calculate progress (10% to 100%)
                            var progressPercent = baseProgress + ((totalProcessed / totalPosts) * progressRange);
                            var progressText = 'Processing posts with hidden images... (' + totalProcessed + '/' + totalPosts + ' posts, ' + totalMigratedImages + ' images)';
                            PinnerPressMigration.updateESSBProgress(Math.round(progressPercent), progressText);
                            
                            if (data.migration_complete) {
                                // Migration complete
                                PinnerPressMigration.updateESSBProgress(100, 'Migration complete! ' + totalMigratedImages + ' images from ' + totalProcessed + ' posts');
                                
                                // Wait a moment then show completion
                                setTimeout(function() {
                                    PinnerPressMigration.displayESSBCompletionMessage({
                                        settings_migration: settingsResults,
                                        total_posts: totalPosts,
                                        migrated_posts: totalProcessed,
                                        migrated_images: totalMigratedImages,
                                        errors: errors
                                    });
                                }, 1500);
                            } else if (data.next_batch !== null) {
                                // Continue with next batch
                                setTimeout(processBatch, 200);
                            }
                        } else {
                            PinnerPressMigration.updateESSBProgress(0, 'Batch processing failed');
                            PinnerPressMigration.showESSBError('Migration failed during batch processing');
                            $('#pinnerpress-migrate-essb').prop('disabled', false);
                            $('#pinnerpress-scan-essb').prop('disabled', false);
                        }
                    },
                    error: function() {
                        PinnerPressMigration.updateESSBProgress(0, 'Batch processing failed');
                        PinnerPressMigration.showESSBError('Network error during batch processing');
                        $('#pinnerpress-migrate-essb').prop('disabled', false);
                        $('#pinnerpress-scan-essb').prop('disabled', false);
                    }
                });
            }
            
            // Start processing
            processBatch();
        },
        
        /**
         * Update ESSB progress bar
         */
        updateESSBProgress: function(percentage, text) {
            var $progressFill = $('#pinnerpress-essb-migration-progress .pinnerpress-progress-fill');
            $progressFill.css('width', percentage + '%');
            
            // Change color based on status
            if (percentage >= 100) {
                $progressFill.css('background-color', '#4CAF50'); // Green for success
            } else if (percentage === 0 && text && text.toLowerCase().includes('failed')) {
                $progressFill.css('background-color', '#f44336'); // Red for error
            } else {
                $progressFill.css('background-color', '#E60023'); // Pinterest red for progress
            }
            
            $('#pinnerpress-essb-migration-progress .pinnerpress-progress-text').text(text);
        },
        
        /**
         * Display ESSB migration results (no hidden images)
         */
        displayESSBMigrationResults: function(data) {
            var html = PinnerPressMigration.buildESSBCompleteMigrationHTML(data.settings_migration, 0, 0);
            
            // Show in results div (replaces scan results)
            $('#pinnerpress-essb-migration-results').html(html).show();
            
            // Hide progress and migrate button
            $('#pinnerpress-essb-migration-progress').hide();
            $('#pinnerpress-migrate-essb').hide();
            $('#pinnerpress-scan-essb').prop('disabled', false);
        },
        
        /**
         * Display ESSB completion message
         */
        displayESSBCompletionMessage: function(data) {
            var html = PinnerPressMigration.buildESSBCompleteMigrationHTML(
                data.settings_migration, 
                data.migrated_posts, 
                data.migrated_images
            );
            
            // Show in results div (replaces scan results)
            $('#pinnerpress-essb-migration-results').html(html).show();
            
            // Hide progress and migrate button  
            $('#pinnerpress-essb-migration-progress').hide();
            $('#pinnerpress-migrate-essb').hide();
            $('#pinnerpress-scan-essb').prop('disabled', false);
        },
        
        /**
         * Build complete ESSB migration HTML
         */
        buildESSBCompleteMigrationHTML: function(settingsResults, posts, images) {
            var html = '<div class="pinnerpress-migration-success" style="background: #d4edda; border: 1px solid #c3e6cb; padding: 15px; border-radius: 4px; margin-bottom: 20px;">';
            html += '<h4 style="margin-top: 0; color: #155724;">✅ Migration Complete!</h4>';
            html += '<p><strong>Your Easy Social Share Buttons Pinterest settings have been successfully imported to PinnerPress.</strong></p>';
            
            html += '<p><strong>Migration Summary:</strong></p>';
            html += '<ul style="margin: 10px 0;">';
            
            // Settings migrated
            if (settingsResults && settingsResults.success) {
                settingsResults.messages.forEach(function(msg) {
                    html += '<li>✓ ' + msg + '</li>';
                });
            }
            
            // Hidden images
            if (posts > 0) {
                html += '<li>✓ Hidden images migrated: <strong>' + images + ' images</strong> for <strong>' + posts + ' posts</strong></li>';
            }
            
            html += '</ul>';
            html += '</div>';
            
            // Next Steps section
            html += '<div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; padding: 15px;">';
            html += '<h4 style="margin-top: 0; color: #856404;">Next Steps:</h4>';
            html += '<ol style="margin: 10px 0;">';
            html += '<li style="margin-bottom: 15px;">';
            html += '<strong>Disable Pinterest features in Easy Social Share Buttons:</strong><br>';
            html += '<a href="/wp-admin/admin.php?page=essb_options" target="_blank" class="button button-secondary">';
            html += 'Open ESSB Settings';
            html += '</a>';
            html += '<span style="margin-left: 10px; color: #666;">(Opens in new tab)</span>';
            html += '</li>';
            html += '<li>';
            html += '<strong>Complete your PinnerPress setup:</strong><br>';
            html += '<a href="/wp-admin/admin.php?page=pinnerpress-settings" class="button button-primary">';
            html += 'Open PinnerPress Settings';
            html += '</a>';
            html += '</li>';
            html += '<li style="margin-top: 15px;">';
            html += '<strong>Test your new Pinterest functionality</strong>';
            html += '</li>';
            html += '</ol>';
            html += '<p style="margin-top: 15px; padding: 10px; background: #fff; border-left: 4px solid #ffc107;">';
            html += '<strong>Important:</strong> Please disable Pinterest features in ESSB to avoid conflicts with PinnerPress.';
            html += '</p>';
            html += '</div>';
            
            return html;
        },
        
        /**
         * Show ESSB error message
         */
        showESSBError: function(message) {
            var $results = $('#pinnerpress-essb-migration-results');
            var html = '<div class="pinnerpress-migration-error">' + message + '</div>';
            $results.html(html).show();
        }
    };

    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        // Only initialize on migration tab
        if ($('#pinnerpress-scan-hubbub').length || $('#pinnerpress-scan-tasty-pins').length || $('#pinnerpress-scan-essb').length) {
            PinnerPressMigration.init();
        }
    });

})(jQuery);