/**
 * SEO Fury Migration Wizard
 *
 * Handles the 3-step migration process:
 * Step 1: Detect & select source plugin
 * Step 2: Migrate data in batches with progress bar
 * Step 3: Show results
 */
(function($) {
    'use strict';

    var MigrationWizard = {
        // State
        currentStep: 1,
        selectedPlugin: null,
        selectedPluginName: '',
        selectedPluginActive: false,
        totalPosts: 0,
        processedPosts: 0,
        migratedPosts: 0,
        skippedPosts: 0,
        errorPosts: 0,
        batchSize: 50,
        isMigrating: false,
        migrateSettings: true,

        // Elements
        $modal: null,
        $overlay: null,

        init: function() {
            this.bindEvents();

            // Auto-open if ?wizard=1 in URL
            if (this.getUrlParam('wizard') === '1') {
                this.open();
            }
        },

        bindEvents: function() {
            var self = this;

            $(document).on('click', '.seo-fury-open-wizard', function(e) {
                e.preventDefault();
                self.open();
            });

            $(document).on('click', '.sfmw-close, .sfmw-overlay', function() {
                if (!self.isMigrating) {
                    self.close();
                }
            });

            $(document).on('click', '.sfmw-plugin-card', function() {
                $('.sfmw-plugin-card').removeClass('sfmw-selected');
                $(this).addClass('sfmw-selected');
                self.selectedPlugin = $(this).data('plugin');
                self.selectedPluginName = $(this).data('name');
                self.selectedPluginActive = $(this).data('active') === true || $(this).data('active') === 'true' || $(this).data('active') === 1;
                self.totalPosts = parseInt($(this).data('count'), 10) || 0;
                $('.sfmw-btn-start').prop('disabled', false);
            });

            $(document).on('click', '.sfmw-btn-start', function() {
                if (self.selectedPlugin) {
                    self.startMigration();
                }
            });

            $(document).on('click', '.sfmw-btn-done', function() {
                self.close();
                // Remove wizard param from URL
                if (window.history.replaceState) {
                    var url = window.location.href.replace(/[?&]wizard=1/, '');
                    window.history.replaceState({}, '', url);
                }
            });

            $(document).on('click', '.sfmw-btn-settings', function() {
                self.close();
                window.location.href = seoFuryWizard.settingsUrl;
            });

            $(document).on('change', '.sfmw-settings-toggle', function() {
                self.migrateSettings = $(this).is(':checked');
            });

            $(document).on('click', '.sfmw-btn-deactivate', function() {
                self.deactivatePlugin();
            });
        },

        getUrlParam: function(name) {
            var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);
            return results ? decodeURIComponent(results[1]) : null;
        },

        open: function() {
            this.createModal();
            this.$overlay.fadeIn(200);
            this.$modal.fadeIn(200);
            this.goToStep(1);
            this.detectPlugins();
        },

        close: function() {
            var self = this;
            this.$modal.fadeOut(200, function() {
                self.$overlay.fadeOut(200);
            });
        },

        createModal: function() {
            if (this.$modal) {
                return;
            }

            var html = '' +
                '<div class="sfmw-overlay"></div>' +
                '<div class="sfmw-modal">' +
                    '<div class="sfmw-header">' +
                        '<h2 class="sfmw-title">🔄 ' + seoFuryWizard.i18n.title + '</h2>' +
                        '<button type="button" class="sfmw-close">&times;</button>' +
                    '</div>' +
                    '<div class="sfmw-steps">' +
                        '<div class="sfmw-step sfmw-step-active" data-step="1"><span class="sfmw-step-num">1</span> ' + seoFuryWizard.i18n.step1 + '</div>' +
                        '<div class="sfmw-step" data-step="2"><span class="sfmw-step-num">2</span> ' + seoFuryWizard.i18n.step2 + '</div>' +
                        '<div class="sfmw-step" data-step="3"><span class="sfmw-step-num">3</span> ' + seoFuryWizard.i18n.step3 + '</div>' +
                    '</div>' +
                    '<div class="sfmw-body">' +
                        '<div class="sfmw-content sfmw-content-1"></div>' +
                        '<div class="sfmw-content sfmw-content-2" style="display:none"></div>' +
                        '<div class="sfmw-content sfmw-content-3" style="display:none"></div>' +
                    '</div>' +
                '</div>';

            $('body').append(html);
            this.$modal = $('.sfmw-modal');
            this.$overlay = $('.sfmw-overlay');
        },

        goToStep: function(step) {
            this.currentStep = step;
            $('.sfmw-step').removeClass('sfmw-step-active sfmw-step-done');
            $('.sfmw-step').each(function() {
                var s = parseInt($(this).data('step'), 10);
                if (s < step) {
                    $(this).addClass('sfmw-step-done');
                } else if (s === step) {
                    $(this).addClass('sfmw-step-active');
                }
            });
            $('.sfmw-content').hide();
            $('.sfmw-content-' + step).show();
        },

        detectPlugins: function() {
            var self = this;
            var $content = $('.sfmw-content-1');

            $content.html('<div class="sfmw-loading"><span class="spinner is-active"></span> ' + seoFuryWizard.i18n.detecting + '</div>');

            $.post(ajaxurl, {
                action: 'seo_fury_wizard_detect',
                nonce: seoFuryWizard.nonce
            }, function(response) {
                if (response.success && response.data.plugins) {
                    self.renderPluginList(response.data.plugins);
                } else {
                    $content.html('<div class="sfmw-empty">' + seoFuryWizard.i18n.noPlugins + '</div>');
                }
            }).fail(function() {
                $content.html('<div class="sfmw-error">' + seoFuryWizard.i18n.detectError + '</div>');
            });
        },

        renderPluginList: function(plugins) {
            var $content = $('.sfmw-content-1');
            var keys = Object.keys(plugins);

            if (keys.length === 0) {
                $content.html(
                    '<div class="sfmw-empty">' +
                        '<span style="font-size: 48px; display: block; margin-bottom: 12px;">✅</span>' +
                        '<p>' + seoFuryWizard.i18n.noPlugins + '</p>' +
                    '</div>'
                );
                return;
            }

            var html = '<p class="sfmw-desc">' + seoFuryWizard.i18n.selectPlugin + '</p>';
            html += '<div class="sfmw-plugin-list">';

            for (var i = 0; i < keys.length; i++) {
                var slug = keys[i];
                var p = plugins[slug];
                var countText = p.post_count > 0
                    ? p.post_count + ' ' + seoFuryWizard.i18n.posts
                    : seoFuryWizard.i18n.settingsOnly;

                html += '<div class="sfmw-plugin-card" data-plugin="' + slug + '" data-name="' + this.escHtml(p.name) + '" data-count="' + p.post_count + '" data-active="' + (p.is_active ? 'true' : 'false') + '">' +
                    '<span class="sfmw-plugin-icon">' + p.icon + '</span>' +
                    '<div class="sfmw-plugin-info">' +
                        '<strong>' + this.escHtml(p.name) + '</strong>' +
                        '<span class="sfmw-plugin-count">' + countText + '</span>' +
                    '</div>' +
                    '<span class="sfmw-plugin-check">✓</span>' +
                '</div>';
            }

            html += '</div>';

            // Settings toggle
            html += '<label class="sfmw-settings-label">' +
                '<input type="checkbox" class="sfmw-settings-toggle" checked> ' +
                seoFuryWizard.i18n.alsoSettings +
            '</label>';

            // Warning
            html += '<div class="sfmw-notice">' +
                '<span>ℹ️</span> ' + seoFuryWizard.i18n.noOverwrite +
            '</div>';

            // Start button
            html += '<div class="sfmw-actions">' +
                '<button type="button" class="button button-primary sfmw-btn-start" disabled>' + seoFuryWizard.i18n.startImport + '</button>' +
            '</div>';

            $content.html(html);
        },

        startMigration: function() {
            this.isMigrating = true;
            this.processedPosts = 0;
            this.migratedPosts = 0;
            this.skippedPosts = 0;
            this.errorPosts = 0;

            this.goToStep(2);

            var html = '<div class="sfmw-progress-wrap">' +
                '<div class="sfmw-progress-header">' +
                    '<span class="sfmw-progress-plugin">' + this.escHtml(this.selectedPluginName) + '</span>' +
                    '<span class="sfmw-progress-percent">0%</span>' +
                '</div>' +
                '<div class="sfmw-progress-bar"><div class="sfmw-progress-fill"></div></div>' +
                '<div class="sfmw-progress-stats">' +
                    '<span class="sfmw-stat-processed">0 / ' + this.totalPosts + '</span>' +
                '</div>' +
                '<div class="sfmw-log"></div>' +
            '</div>';

            $('.sfmw-content-2').html(html);

            this.addLog('🚀 ' + seoFuryWizard.i18n.startingMigration + ' ' + this.selectedPluginName + '...');

            // Always run batch migration first (per-post SEO data),
            // then global settings. Even if totalPosts is 0, we run a batch
            // as a safety net — the server may find posts the count missed.
            this.runBatch(0);
        },

        runBatch: function(offset) {
            var self = this;

            $.post(ajaxurl, {
                action: 'seo_fury_wizard_migrate_batch',
                nonce: seoFuryWizard.nonce,
                plugin: this.selectedPlugin,
                offset: offset,
                batch: this.batchSize
            }, function(response) {
                if (!response.success) {
                    self.addLog('❌ ' + seoFuryWizard.i18n.batchError);
                    self.finishMigration();
                    return;
                }

                var data = response.data;
                self.processedPosts += data.migrated + data.skipped + data.errors;
                self.migratedPosts += data.migrated;
                self.skippedPosts += data.skipped;
                self.errorPosts += data.errors;

                self.updateProgress();

                if (data.migrated > 0) {
                    self.addLog('✅ ' + seoFuryWizard.i18n.batchDone.replace('%d', data.migrated));
                }
                if (data.skipped > 0) {
                    self.addLog('⏭️ ' + seoFuryWizard.i18n.batchSkipped.replace('%d', data.skipped));
                }

                if (data.done) {
                    if (self.migrateSettings) {
                        self.runSettingsMigration();
                    } else {
                        self.finishMigration();
                    }
                } else {
                    // Next batch
                    self.runBatch(offset + self.batchSize);
                }
            }).fail(function() {
                self.addLog('❌ ' + seoFuryWizard.i18n.networkError);
                self.finishMigration();
            });
        },

        runSettingsMigration: function() {
            var self = this;
            this.addLog('⚙️ ' + seoFuryWizard.i18n.migratingSettings);

            $.post(ajaxurl, {
                action: 'seo_fury_wizard_migrate_settings',
                nonce: seoFuryWizard.nonce,
                plugin: this.selectedPlugin
            }, function(response) {
                if (response.success && response.data.migrated && response.data.migrated.length > 0) {
                    self.addLog('✅ ' + seoFuryWizard.i18n.settingsMigrated + ': ' + response.data.migrated.join(', '));
                } else {
                    self.addLog('ℹ️ ' + seoFuryWizard.i18n.noSettingsToMigrate);
                }
                self.finishMigration();
            }).fail(function() {
                self.addLog('⚠️ ' + seoFuryWizard.i18n.settingsError);
                self.finishMigration();
            });
        },

        updateProgress: function() {
            var total = Math.max(this.totalPosts, 1);
            var percent = Math.min(Math.round((this.processedPosts / total) * 100), 100);

            $('.sfmw-progress-fill').css('width', percent + '%');
            $('.sfmw-progress-percent').text(percent + '%');
            $('.sfmw-stat-processed').text(this.processedPosts + ' / ' + this.totalPosts);
        },

        finishMigration: function() {
            this.isMigrating = false;

            // Set progress to 100%
            $('.sfmw-progress-fill').css('width', '100%');
            $('.sfmw-progress-percent').text('100%');

            this.addLog('');
            this.addLog('🎉 ' + seoFuryWizard.i18n.migrationComplete);

            // Dismiss the notice
            $.post(ajaxurl, {
                action: 'seo_fury_wizard_dismiss',
                nonce: seoFuryWizard.nonce
            });

            // Move to step 3 after a short delay
            var self = this;
            setTimeout(function() {
                self.goToStep(3);
                self.renderResults();
            }, 1500);
        },

        renderResults: function() {
            var html = '<div class="sfmw-results">' +
                '<div class="sfmw-results-icon">🎉</div>' +
                '<h3>' + seoFuryWizard.i18n.migrationComplete + '</h3>' +
                '<p class="sfmw-results-plugin">' + this.escHtml(this.selectedPluginName) + '</p>' +
                '<div class="sfmw-results-stats">';

            if (this.totalPosts > 0) {
                html += '<div class="sfmw-result-stat">' +
                    '<span class="sfmw-result-num sfmw-result-migrated">' + this.migratedPosts + '</span>' +
                    '<span class="sfmw-result-label">' + seoFuryWizard.i18n.migrated + '</span>' +
                '</div>';

                if (this.skippedPosts > 0) {
                    html += '<div class="sfmw-result-stat">' +
                        '<span class="sfmw-result-num sfmw-result-skipped">' + this.skippedPosts + '</span>' +
                        '<span class="sfmw-result-label">' + seoFuryWizard.i18n.skipped + '</span>' +
                    '</div>';
                }

                if (this.errorPosts > 0) {
                    html += '<div class="sfmw-result-stat">' +
                        '<span class="sfmw-result-num sfmw-result-errors">' + this.errorPosts + '</span>' +
                        '<span class="sfmw-result-label">' + seoFuryWizard.i18n.errors + '</span>' +
                    '</div>';
                }
            } else {
                html += '<p style="color: #64748B;">' + seoFuryWizard.i18n.settingsOnly + '</p>';
            }

            html += '</div>';

            // Show deactivate option if the source plugin is currently active
            if (this.selectedPluginActive) {
                html += '<div class="sfmw-deactivate-section">' +
                    '<div class="sfmw-deactivate-icon">⚠️</div>' +
                    '<p class="sfmw-deactivate-text">' +
                        (seoFuryWizard.i18n.deactivateHint || 'Running two SEO plugins at the same time can cause conflicts. We recommend deactivating the old plugin.').replace('%s', this.escHtml(this.selectedPluginName)) +
                    '</p>' +
                    '<button type="button" class="button sfmw-btn-deactivate">' +
                        (seoFuryWizard.i18n.deactivatePlugin || 'Deactivate %s').replace('%s', this.escHtml(this.selectedPluginName)) +
                    '</button>' +
                    '<div class="sfmw-deactivate-status"></div>' +
                '</div>';
            }

            html += '<div class="sfmw-actions">' +
                '<button type="button" class="button button-primary sfmw-btn-settings">' + seoFuryWizard.i18n.goToSettings + '</button>' +
                '<button type="button" class="button sfmw-btn-done">' + seoFuryWizard.i18n.close + '</button>' +
            '</div>';

            html += '</div>';

            $('.sfmw-content-3').html(html);
        },

        deactivatePlugin: function() {
            var self = this;
            var $btn = $('.sfmw-btn-deactivate');
            var $status = $('.sfmw-deactivate-status');

            $btn.prop('disabled', true).text(seoFuryWizard.i18n.deactivating || 'Deactivating...');
            $status.html('');

            $.post(ajaxurl, {
                action: 'seo_fury_wizard_deactivate_plugin',
                nonce: seoFuryWizard.nonce,
                plugin: this.selectedPlugin
            }, function(response) {
                if (response.success) {
                    self.selectedPluginActive = false;
                    $btn.replaceWith(
                        '<div class="sfmw-deactivate-success">✅ ' + response.data.message + '</div>'
                    );
                } else {
                    $status.html('<span style="color: #d63638;">❌ ' + (response.data.message || 'Error') + '</span>');
                    $btn.prop('disabled', false).text(
                        (seoFuryWizard.i18n.deactivatePlugin || 'Deactivate %s').replace('%s', self.escHtml(self.selectedPluginName))
                    );
                }
            }).fail(function() {
                $status.html('<span style="color: #d63638;">❌ ' + (seoFuryWizard.i18n.networkError || 'Network error') + '</span>');
                $btn.prop('disabled', false).text(
                    (seoFuryWizard.i18n.deactivatePlugin || 'Deactivate %s').replace('%s', self.escHtml(self.selectedPluginName))
                );
            });
        },

        addLog: function(message) {
            var $log = $('.sfmw-log');
            if (message) {
                $log.append('<div class="sfmw-log-entry">' + message + '</div>');
            }
            $log.scrollTop($log[0].scrollHeight);
        },

        escHtml: function(str) {
            var div = document.createElement('div');
            div.appendChild(document.createTextNode(str));
            return div.innerHTML;
        }
    };

    $(document).ready(function() {
        MigrationWizard.init();
    });

})(jQuery);
