/**
 * Activation Wizard JavaScript.
 *
 * @package PrimeLink
 */

(function($) {
    'use strict';

    const Wizard = {
        currentStep: 1,
        totalSteps: 4,
        $wizard: null,
        $progressFill: null,

        init: function() {
            this.$wizard = $('#mt-primelink-activation-wizard');
            this.$progressFill = $('.mt-primelink-wizard-progress-fill');

            if (!this.$wizard.length) {
                return;
            }

            // Show wizard on page load (with small delay to ensure page is ready)
            const self = this;
            setTimeout(function() {
                self.show();
            }, 100);

            // Bind events
            this.bindEvents();

            // Auto-verify license if already set
            this.checkExistingLicense();
        },

        show: function() {
            this.$wizard.fadeIn(300);
            $('body').addClass('mt-primelink-wizard-active');
            this.updateProgress();
            // Scroll to top
            window.scrollTo(0, 0);
        },

        hide: function() {
            this.$wizard.fadeOut(300);
            $('body').removeClass('mt-primelink-wizard-active');
        },

        bindEvents: function() {
            const self = this;

            // Next button
            $('.mt-primelink-wizard-next').on('click', function() {
                self.nextStep();
            });

            // Previous button
            $('.mt-primelink-wizard-prev').on('click', function() {
                self.prevStep();
            });

            // Skip button (old)
            $('.mt-primelink-wizard-skip').on('click', function() {
                self.skipWizard();
            });

            // Skip for now button (new - doesn't force activation)
            $('.mt-primelink-wizard-skip-now').on('click', function() {
                self.skipForNow();
            });

            // Close button
            $('.mt-primelink-wizard-close').on('click', function() {
                self.skipForNow();
            });

            // Close on overlay click (outside modal)
            $(document).on('click', '.mt-primelink-wizard-overlay', function(e) {
                if ($(e.target).hasClass('mt-primelink-wizard-overlay')) {
                    self.skipForNow();
                }
            });

            // Finish button on complete step
            $(document).on('click', '#wizard-complete-finish', function() {
                self.completeWizard();
            });

            // License verification on Enter key (only if both fields are filled)
            $('#wizard-license-key, #wizard-client-name').on('keypress', function(e) {
                if (e.which === 13) {
                    const licenseKey = $('#wizard-license-key').val().trim();
                    const clientName = $('#wizard-client-name').val().trim();
                    if (licenseKey && clientName && clientName.length >= 2) {
                        e.preventDefault();
                        self.verifyLicense();
                    }
                }
            });

            // Hide status message when user starts typing (to clear previous errors)
            $('#wizard-license-key, #wizard-client-name').on('input', function() {
                const licenseKey = $('#wizard-license-key').val().trim();
                const clientName = $('#wizard-client-name').val().trim();
                
                // Only hide if fields are incomplete (user is still typing)
                if (!licenseKey || !clientName || clientName.length < 2) {
                    $('#wizard-license-status').fadeOut();
                }
            });
        },

        checkExistingLicense: function() {
            // Only check if license is already saved (don't auto-verify on page load)
            // User will verify manually when ready
            const licenseKey = $('#wizard-license-key').val().trim();
            if (licenseKey && licenseKey.length > 30) {
                // License key exists, but don't verify until user provides username
                // This just ensures the field is populated if license was previously saved
            }
        },

        nextStep: function() {
            const self = this;

            // Validate current step before proceeding
            if (!this.validateStep(this.currentStep)) {
                return;
            }

            // Save current step data
            this.saveStepData(this.currentStep).then(function() {
                if (self.currentStep < self.totalSteps) {
                    self.currentStep++;
                    self.updateStep();
                } else {
                    self.completeWizard();
                }
            }).catch(function(error) {
                self.showError(error.message || 'Failed to save step data.');
            });
        },

        prevStep: function() {
            if (this.currentStep > 1) {
                this.currentStep--;
                this.updateStep();
            }
        },

        updateStep: function() {
            // Hide all steps
            $('.mt-primelink-wizard-step-content').hide();

            // Show current step
            $(`.mt-primelink-wizard-step-content[data-step="${this.currentStep}"]`).fadeIn(300);

            // Update step indicators
            $('.mt-primelink-wizard-step').removeClass('active completed');
            $(`.mt-primelink-wizard-step[data-step="${this.currentStep}"]`).addClass('active');
            $('.mt-primelink-wizard-step').each(function() {
                const stepNum = parseInt($(this).data('step'), 10);
                if (stepNum < Wizard.currentStep) {
                    $(this).addClass('completed');
                }
            });

            // Update buttons
            $('.mt-primelink-wizard-prev').toggle(this.currentStep > 1);
            $('.mt-primelink-wizard-next').toggle(this.currentStep < this.totalSteps);
            $('.mt-primelink-wizard-skip').toggle(this.currentStep < this.totalSteps);

            // Update progress
            this.updateProgress();

            // Run step-specific actions
            this.runStepActions();
        },

        updateProgress: function() {
            const percentage = (this.currentStep / this.totalSteps) * 100;
            this.$progressFill.css('width', percentage + '%');
        },

        validateStep: function(step) {
            switch(step) {
                case 1:
                    return this.validateLicenseStep();
                case 2:
                    return this.validateSetupStep();
                default:
                    return true;
            }
        },

        validateLicenseStep: function() {
            const $licenseInput = $('#wizard-license-key');
            const $clientInput = $('#wizard-client-name');
            const licenseKey = $licenseInput.val() ? $licenseInput.val().trim() : '';
            const clientName = $clientInput.val() ? $clientInput.val().trim() : '';
            const $status = $('#wizard-license-status');
            const $message = $('#wizard-license-message');

            // Frontend validation: only ensure non-empty values.
            // Actual format / test codes / Envato checks are handled server-side
            // in EnvatoHelper::verify_purchase_code().
            if (!licenseKey || licenseKey.length === 0) {
                $message.removeClass('success').addClass('error')
                    .html('<span class="dashicons dashicons-warning"></span> Please enter a valid purchase code.');
                $status.fadeIn();
                return false;
            }
            if (!clientName || clientName.length < 2) {
                $message.removeClass('success').addClass('error')
                    .html('<span class="dashicons dashicons-warning"></span> Please enter your Envato username or name.');
                $status.fadeIn();
                return false;
            }
            
            // If both fields are filled, check if license is already verified
            const isVerified = $message.hasClass('success');
            if (!isVerified) {
                // Trigger verification - it will enable Next button when done
                this.verifyLicense();
                return false; // Prevent moving to next step until verification completes
            }
            
            return true;
        },

        validateSetupStep: function() {
            const email = $('#wizard-notify-email').val().trim();
            if (email && !this.isValidEmail(email)) {
                this.showError('Please enter a valid email address.');
                return false;
            }
            return true;
        },

        isValidEmail: function(email) {
            const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return re.test(email);
        },

        saveStepData: function(step) {
            const self = this;
            return new Promise(function(resolve, reject) {
                switch(step) {
                    case 1:
                        // License already saved during verification
                        resolve();
                        break;
                    case 2:
                        self.saveSetupData().then(resolve).catch(reject);
                        break;
                    case 3:
                        // Test system - no save needed
                        resolve();
                        break;
                    default:
                        resolve();
                }
            });
        },

        verifyLicense: function() {
            const self = this;
            const $licenseInput = $('#wizard-license-key');
            const $clientInput = $('#wizard-client-name');
            const licenseKey = $licenseInput.length && $licenseInput.val() ? $licenseInput.val().trim() : '';
            const clientName = $clientInput.length && $clientInput.val() ? $clientInput.val().trim() : '';
            const $status = $('#wizard-license-status');
            const $message = $('#wizard-license-message');
            const $nextBtn = $('.mt-primelink-wizard-next');

            // Allow any non-empty license key; server will validate format/test codes.
            if (!licenseKey || licenseKey.length === 0) {
                $message.removeClass('success').addClass('error')
                    .html('<span class="dashicons dashicons-warning"></span> Please enter a valid purchase code.');
                $status.fadeIn();
                return;
            }

            if (!clientName || clientName.length < 2) {
                $message.removeClass('success').addClass('error')
                    .html('<span class="dashicons dashicons-warning"></span> Please enter your Envato username or name.');
                $status.fadeIn();
                return;
            }

            $status.hide();
            $nextBtn.prop('disabled', true).text('Verifying...');

            // Ensure we have valid values before sending
            if (!licenseKey || licenseKey.length === 0) {
                $message.removeClass('success').addClass('error')
                    .html('<span class="dashicons dashicons-warning"></span> Please enter a valid purchase code.');
                $status.fadeIn();
                $nextBtn.prop('disabled', false).text('Next');
                return;
            }

            if (!clientName || clientName.length < 2) {
                $message.removeClass('success').addClass('error')
                    .html('<span class="dashicons dashicons-warning"></span> Please enter your Envato username or name.');
                $status.fadeIn();
                $nextBtn.prop('disabled', false).text('Next');
                return;
            }

            $.ajax({
                url: mtPrimeLinkWizard.restUrl + '/wizard/verify-license',
                method: 'POST',
                headers: {
                    'X-WP-Nonce': mtPrimeLinkWizard.restNonce
                },
                data: {
                    purchase_code: licenseKey,
                    client_name: clientName
                },
                success: function(response) {
                    if (response.success) {
                        $message.removeClass('error').addClass('success')
                            .html('<span class="dashicons dashicons-yes"></span> ' + (response.message || 'License verified successfully!'));
                        $status.fadeIn();
                        $nextBtn.prop('disabled', false).text('Next');
                    } else {
                        $message.removeClass('success').addClass('error')
                            .html('<span class="dashicons dashicons-warning"></span> ' + (response.error || 'License verification failed.'));
                        $status.fadeIn();
                        $nextBtn.prop('disabled', true).text('Next');
                    }
                },
                error: function(xhr) {
                    const error = xhr.responseJSON?.error || 'Failed to verify license. Please try again.';
                    $message.removeClass('success').addClass('error')
                        .html('<span class="dashicons dashicons-warning"></span> ' + error);
                    $status.fadeIn();
                    $nextBtn.prop('disabled', false).text('Next');
                }
            });
        },

        saveSetupData: function() {
            const self = this;
            return new Promise(function(resolve, reject) {
                $.ajax({
                    url: mtPrimeLinkWizard.restUrl + '/wizard/save-setup',
                    method: 'POST',
                    headers: {
                        'X-WP-Nonce': mtPrimeLinkWizard.restNonce
                    },
                    data: {
                        notify_email: $('#wizard-notify-email').val(),
                        iteration_size: $('#wizard-iteration-size').val(),
                        enable_logs: $('#wizard-enable-logs').is(':checked') ? 1 : 0
                    },
                    success: function(response) {
                        if (response.success) {
                            resolve();
                        } else {
                            reject(new Error(response.error || 'Failed to save settings.'));
                        }
                    },
                    error: function(xhr) {
                        reject(new Error(xhr.responseJSON?.error || 'Failed to save settings.'));
                    }
                });
            });
        },

        runStepActions: function() {
            switch(this.currentStep) {
                case 3:
                    this.testSystem();
                    break;
            }
        },

        testSystem: function() {
            const self = this;
            const $results = $('#wizard-test-results');
            $results.html('<div class="mt-primelink-wizard-test-item"><div class="mt-primelink-wizard-test-icon"><span class="dashicons dashicons-update spin"></span></div><div class="mt-primelink-wizard-test-content"><h4>Running system checks...</h4><p>Please wait while we verify your system.</p></div></div>');

            // Add timeout to prevent hanging
            const timeout = setTimeout(function() {
                $results.html('<div class="mt-primelink-wizard-test-item error"><div class="mt-primelink-wizard-test-icon"><span class="dashicons dashicons-warning"></span></div><div class="mt-primelink-wizard-test-content"><h4>Timeout</h4><p>System check is taking longer than expected. Please try again.</p></div></div>');
            }, 10000); // 10 second timeout

            $.ajax({
                url: mtPrimeLinkWizard.restUrl + '/wizard/test-system',
                method: 'POST',
                headers: {
                    'X-WP-Nonce': mtPrimeLinkWizard.restNonce
                },
                timeout: 8000, // 8 second AJAX timeout
                success: function(response) {
                    clearTimeout(timeout);
                    if (response && response.tests) {
                        let html = '';
                        response.tests.forEach(function(test) {
                            const icon = test.status === 'pass' ? 'yes' : (test.status === 'warning' ? 'warning' : 'dismiss');
                            const statusClass = test.status === 'pass' ? 'success' : (test.status === 'warning' ? 'warning' : 'error');
                            html += `
                                <div class="mt-primelink-wizard-test-item ${statusClass}">
                                    <div class="mt-primelink-wizard-test-icon">
                                        <span class="dashicons dashicons-${icon}"></span>
                                    </div>
                                    <div class="mt-primelink-wizard-test-content">
                                        <h4>${test.name}</h4>
                                        <p>${test.message}</p>
                                    </div>
                                </div>
                            `;
                        });
                        $results.html(html);
                        // Scroll to top of results
                        $results.scrollTop(0);
                    } else {
                        $results.html('<div class="mt-primelink-wizard-test-item error" style="grid-column: 1 / -1;"><div class="mt-primelink-wizard-test-icon"><span class="dashicons dashicons-dismiss"></span></div><div class="mt-primelink-wizard-test-content"><h4>Error</h4><p>Invalid response from server.</p></div></div>');
                    }
                },
                error: function(xhr, status, error) {
                    clearTimeout(timeout);
                    let errorMsg = 'Failed to run system tests.';
                    if (status === 'timeout') {
                        errorMsg = 'Request timed out. Please check your connection and try again.';
                    } else if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                    $results.html(`<div class="mt-primelink-wizard-test-item error" style="grid-column: 1 / -1;"><div class="mt-primelink-wizard-test-icon"><span class="dashicons dashicons-dismiss"></span></div><div class="mt-primelink-wizard-test-content"><h4>Error</h4><p>${errorMsg}</p></div></div>`);
                }
            });
        },

        completeWizard: function() {
            const self = this;
            $.ajax({
                url: mtPrimeLinkWizard.restUrl + '/wizard/complete',
                method: 'POST',
                headers: {
                    'X-WP-Nonce': mtPrimeLinkWizard.restNonce
                },
                success: function() {
                    // Mark as completed and hide
                    self.hide();
                },
                error: function() {
                    // Hide anyway
                    self.hide();
                }
            });
        },

        skipWizard: function() {
            if (confirm('Are you sure you want to skip the setup wizard? You can complete it later from Settings.')) {
                this.completeWizard();
            }
        },

        skipForNow: function() {
            const self = this;
            // Save skip flag via REST API
            $.ajax({
                url: mtPrimeLinkWizard.restUrl + '/wizard/skip',
                method: 'POST',
                headers: {
                    'X-WP-Nonce': mtPrimeLinkWizard.restNonce
                },
                success: function() {
                    // Hide wizard after skip is saved
                    self.hide();
                },
                error: function() {
                    // Hide anyway even if save fails
                    self.hide();
                }
            });
        },

        showError: function(message) {
            // You can implement a toast/notification system here
            alert(message);
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        Wizard.init();
    });

})(jQuery);

