/**
 * EPOFW Migration JavaScript
 *
 * Handles migration of existing addons from old flat structure to new
 * hierarchical section structure with custom database tables.
 *
 * @package Extra_Product_Options_For_WooCommerce
 * @since   4.4.0
 */

jQuery(document).ready(function($) {
    'use strict';

    // Check if migration variables are loaded
    if (typeof epofw_migration_vars === 'undefined') {
        return;
    }

    // Global migration state flag
    if (typeof window.epofwMigrationInProgress === 'undefined') {
        window.epofwMigrationInProgress = false;
    }

    // Migration button click handler
    $(document).on('click', '.epofw-migrate-to-sections-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
        
        // Prevent multiple executions
        if (window.epofwMigrationInProgress) {
            return false;
        }
        
        // Add confirmation dialog before migration
        if (!confirm('Are you sure you want to migrate all existing addons to the new section structure? This will update all your addons at once.')) {
            return false;
        }
        
        // Set global migration flag
        window.epofwMigrationInProgress = true;
        
        // Unbind all click events to prevent duplicates
        $('.epofw-migrate-to-sections-btn').off('click');
        
        var $button = $(this);
        $button.prop('disabled', true).text('Migrating...');
        
        showMigrationLoading();
        $('body').addClass('epofw-migration-in-progress');
        
        // Make AJAX request
        $.ajax({
            url: epofw_migration_vars.ajaxurl,
            type: 'POST',
            data: {
                action: 'epofw_migrate_to_sections',
                nonce: epofw_migration_vars.nonce
            },
            timeout: 60000,
            success: function(response) {
                $('body').removeClass('epofw-migration-in-progress');

                // Small delay for smooth transition
                setTimeout(function() {
                    hideMigrationLoading();

                    if (response.success) {
                        // wp_send_json_success wraps data, so access response.data.message and response.data.data
                        var message = response.data ? response.data.message : '';
                        var data = response.data ? response.data.data : null;

                        showMigrationSuccess(message, data);

                        // Hide all migration buttons and notice
                        $('.epofw-migrate-to-sections-btn').fadeOut();
                        $('#epofw-row-association-notice').fadeOut(500, function() {
                            $(this).remove();
                        });

                        // Reload page after successful migration
                        setTimeout(function() {
                            location.reload();
                        }, 3000);
                    } else {
                        // wp_send_json_error also wraps data
                        var errorMessage = response.data ? response.data.message : 'Migration failed';
                        showMigrationError(errorMessage);
                    }
                }, 500);
            },
            error: function(xhr, status, error) {
                $('body').removeClass('epofw-migration-in-progress');
                hideMigrationLoading();
                showMigrationError(epofw_migration_vars.strings.error + ': ' + error);
                window.epofwMigrationInProgress = false;
            }
        });
    });

    /**
     * Show migration loading indicator with overlay
     */
    function showMigrationLoading() {
        // Check if already showing
        if ($('.epofw-migration-modal').length > 0) {
            return;
        }
        
        // Remove any old ones just in case
        $('.epofw-migration-overlay, .epofw-migration-modal').remove();
        
        // Create overlay with modal inside (better positioning)
        var overlayHtml = '<div class="epofw-migration-overlay" style="' +
            'position: fixed !important;' +
            'top: 0 !important;' +
            'left: 0 !important;' +
            'right: 0 !important;' +
            'bottom: 0 !important;' +
            'width: 100% !important;' +
            'height: 100% !important;' +
            'background: rgba(0, 0, 0, 0.7) !important;' +
            'z-index: 99999 !important;' +
            'display: flex !important;' +
            'align-items: center !important;' +
            'justify-content: center !important;' +
            'backdrop-filter: blur(2px);' +
            'margin: 0 !important;' +
            'padding: 0 !important;' +
            '">';
        
        // Create modal (positioned by flexbox parent, not absolute positioning)
        var modalHtml = '<div class="epofw-migration-modal" style="' +
            'position: relative !important;' +
            'background: #fff !important;' +
            'padding: 40px !important;' +
            'border-radius: 8px !important;' +
            'box-shadow: 0 10px 40px rgba(0,0,0,0.3) !important;' +
            'min-width: 400px !important;' +
            'max-width: 500px !important;' +
            'text-align: center !important;' +
            'animation: fadeIn 0.3s ease !important;' +
            'margin: 20px !important;' +
            '">' +
            '<div class="epofw-migration-icon" style="margin-bottom: 20px;">' +
            '<div class="spinner is-active" style="float: none; margin: 0 auto; width: 40px; height: 40px;"></div>' +
            '</div>' +
            '<h2 style="margin: 0 0 10px; color: #2271b1;">Migrating All Addons</h2>' +
            '<p style="color: #666; margin: 0;">Please wait while we update all your addons at once...</p>' +
            '<p style="color: #999; font-size: 14px; margin-top: 10px;">This will only take a moment. Do not close this window.</p>' +
            '<div class="epofw-migration-progress" style="' +
            'margin-top: 20px;' +
            'height: 4px;' +
            'background: #f0f0f0;' +
            'border-radius: 2px;' +
            'overflow: hidden;' +
            '">' +
            '<div class="epofw-migration-progress-bar" style="' +
            'height: 100%;' +
            'background: linear-gradient(90deg, #2271b1 0%, #135e96 100%);' +
            'width: 0%;' +
            'animation: progressBar 2s infinite;' +
            '"></div>' +
            '</div>' +
            '</div>';
        
        // Add CSS animation
        var styleHtml = '<style>' +
            '@keyframes fadeIn {' +
            '  from { opacity: 0; }' +
            '  to { opacity: 1; }' +
            '}' +
            '@keyframes progressBar {' +
            '  0% { width: 0%; }' +
            '  50% { width: 70%; }' +
            '  100% { width: 100%; }' +
            '}' +
            '.epofw-migration-overlay { transition: opacity 0.3s ease !important; }' +
            '.epofw-migration-modal { transform: none !important; }' +
            '</style>';
        
        if (!$('head').find('style.epofw-migration-styles').length) {
            $('head').append(styleHtml);
        }
        
        // Nest modal inside overlay: overlay > modal > content
        var fullModal = overlayHtml + modalHtml + '</div>'; // Close overlay
        
        // Create element with opacity 0
        var $container = $(fullModal).css({
            'opacity': '0',
            'transition': 'opacity 0.3s ease'
        });
        
        $('body').append($container);
        $container[0].offsetHeight; // Force reflow
        $container.css('opacity', '1');
    }

    /**
     * Hide migration loading indicator
     */
    function hideMigrationLoading() {
        $('.epofw-migration-overlay, .epofw-migration-modal').fadeOut(300, function() {
            $(this).remove();
        });
    }

    /**
     * Show migration success message with modal
     */
    function showMigrationSuccess(message, data) {
        // Create success overlay (same as loading modal)
        var overlayHtml = '<div class="epofw-migration-overlay epofw-success-overlay" style="' +
            'position: fixed !important;' +
            'top: 0 !important;' +
            'left: 0 !important;' +
            'right: 0 !important;' +
            'bottom: 0 !important;' +
            'width: 100% !important;' +
            'height: 100% !important;' +
            'background: rgba(0, 0, 0, 0.7) !important;' +
            'z-index: 99999 !important;' +
            'display: flex !important;' +
            'align-items: center !important;' +
            'justify-content: center !important;' +
            'backdrop-filter: blur(2px);' +
            'margin: 0 !important;' +
            'padding: 0 !important;' +
            '">';
        
        // Create success modal (positioned by flexbox parent)
        var modalHtml = '<div class="epofw-migration-modal epofw-migration-success" style="' +
            'position: relative !important;' +
            'background: #fff !important;' +
            'padding: 40px !important;' +
            'border-radius: 8px !important;' +
            'box-shadow: 0 10px 40px rgba(0,0,0,0.3) !important;' +
            'min-width: 450px !important;' +
            'max-width: 550px !important;' +
            'text-align: center !important;' +
            'animation: fadeIn 0.3s ease !important;' +
            'margin: 20px !important;' +
            '">' +
            '<div class="epofw-migration-icon" style="margin-bottom: 20px;">' +
            '<span class="dashicons dashicons-yes-alt" style="' +
            'font-size: 60px;' +
            'width: 60px;' +
            'height: 60px;' +
            'color: #46b450;' +
            '"></span>' +
            '</div>' +
            '<h2 style="margin: 0 0 10px; color: #46b450;">Migration Successful!</h2>' +
            '<p style="color: #666; margin: 10px 0 20px;">' + message + '</p>';
        
        if (data && data.migrated_count > 0) {
            var totalCount = data.total_count || data.migrated_count;
            modalHtml += '<div style="' +
                'background: #f0f6fc;' +
                'padding: 20px;' +
                'border-radius: 5px;' +
                'margin-bottom: 20px;' +
                'border-left: 4px solid #2271b1;' +
                '">' +
                '<p style="margin: 0; color: #2271b1; font-weight: 600; font-size: 16px;">' +
                '<span style="font-size: 36px; display: block; margin-bottom: 10px; font-weight: bold;">' + data.migrated_count + '</span>' +
                (totalCount > 1 ? 
                    'Addons Migrated Successfully' + 
                    '<span style="display: block; margin-top: 8px; font-size: 14px; color: #666;">(' + data.migrated_count + ' out of ' + totalCount + ')</span>' 
                    : 
                    'Addon Migrated Successfully'
                ) +
                '</p>' +
                '</div>';
        }
        
        if (data && data.errors && data.errors.length > 0) {
            modalHtml += '<div style="' +
                'background: #fff8e5;' +
                'padding: 15px;' +
                'border-radius: 5px;' +
                'border-left: 4px solid #ffb900;' +
                'text-align: left;' +
                'margin-bottom: 20px;' +
                '">' +
                '<p style="margin: 0 0 10px; color: #996800; font-weight: 600;">Errors Encountered:</p>' +
                '<ul style="margin: 0; padding-left: 20px; color: #996800;">';
            
            data.errors.forEach(function(error) {
                modalHtml += '<li style="margin-bottom: 5px;">' + error + '</li>';
            });
            
            modalHtml += '</ul></div>';
        }
        
        modalHtml += '<p style="color: #999; font-size: 13px; margin: 20px 0 0;">Page will reload in 3 seconds...</p>' +
            '</div>';
        
        // Nest modal inside overlay
        var fullModal = overlayHtml + modalHtml + '</div>';
        
        var $container = $(fullModal).css({
            'opacity': '0',
            'transition': 'opacity 0.3s ease'
        });
        
        $('body').append($container);
        $container[0].offsetHeight; // Force reflow
        $container.css('opacity', '1');
    }

    /**
     * Show migration error message
     */
    function showMigrationError(message) {
        // Remove existing notices
        $('.epofw-migration-notice').remove();
        
        var noticeHtml = '<div class="epofw-migration-notice notice notice-error is-dismissible" style="margin: 20px 0;">' +
            '<p><strong>Migration Error:</strong></p>' +
            '<p>' + message + '</p>' +
            '</div>';
        
        $('.wp-header-end').after(noticeHtml);
        
        // Make notice dismissible
        $('.epofw-migration-notice').on('click', '.notice-dismiss', function() {
            $(this).parent().fadeOut(300, function() {
                $(this).remove();
            });
        });
    }
});
