/**
 * Setup Wizard JS
 * Step navigation, AJAX saves, form validation, and progress animation.
 */
(function ($) {
    'use strict';

    if (typeof strp_sub_wizard === 'undefined') { return; }

    var Wizard = {
        currentStep: 1,
        totalSteps: 5,
        saving: false,

        init: function () {
            this.currentStep = parseInt(strp_sub_wizard.current_step, 10) || 1;
            if (this.currentStep < 1) this.currentStep = 1;
            if (this.currentStep > this.totalSteps) this.currentStep = this.totalSteps;

            this.showStep(this.currentStep);
            this.bindEvents();

            // Add class to html for full-screen overlay
            $('html').addClass('strp-wizard-active');
        },

        bindEvents: function () {
            var self = this;

            // Navigation buttons
            $(document).on('click', '[data-wizard-next]', function (e) {
                e.preventDefault();
                self.nextStep();
            });

            $(document).on('click', '[data-wizard-prev]', function (e) {
                e.preventDefault();
                self.prevStep();
            });

            $(document).on('click', '[data-wizard-skip]', function (e) {
                e.preventDefault();
                self.skipStep();
            });

            $(document).on('click', '[data-wizard-save]', function (e) {
                e.preventDefault();
                self.saveStep(function () {
                    self.goToStep(self.currentStep + 1);
                });
            });

            $(document).on('click', '[data-wizard-finish]', function (e) {
                e.preventDefault();
                self.finishWizard();
            });

            // Copy webhook URL
            $(document).on('click', '.strp-wizard-webhook-url__copy', function (e) {
                e.preventDefault();
                var $code = $(this).siblings('code');
                var text = $code.text().trim();
                self.copyToClipboard(text, $(this));
            });

            // Verify webhook button
            $(document).on('click', '[data-wizard-verify-webhook]', function (e) {
                e.preventDefault();
                self.verifyWebhook($(this));
            });

            // Mode toggle
            $(document).on('click', '.strp-wizard-mode-toggle__btn', function (e) {
                e.preventDefault();
                var $btn = $(this);
                $btn.siblings().removeClass('strp-wizard-mode-toggle__btn--active');
                $btn.addClass('strp-wizard-mode-toggle__btn--active');
                var mode = $btn.data('mode');
                $('[name="test_mode"]').val(mode === 'test' ? 'yes' : 'no');
            });
        },

        showStep: function (step) {
            // Hide all steps
            $('.strp-wizard-step').removeClass('strp-wizard-step--active');

            // Show current step
            $('#strp-wizard-step-' + step).addClass('strp-wizard-step--active');

            // Update stepper
            this.updateStepper(step);

            // Scroll to top
            $('.strp-wizard-wrap').scrollTop(0);
        },

        updateStepper: function (step) {
            $('.strp-wizard-stepper__step').each(function () {
                var stepNum = parseInt($(this).data('step'), 10);
                $(this).removeClass('strp-wizard-stepper__step--active strp-wizard-stepper__step--completed');

                if (stepNum === step) {
                    $(this).addClass('strp-wizard-stepper__step--active');
                } else if (stepNum < step) {
                    $(this).addClass('strp-wizard-stepper__step--completed');
                    // Show checkmark for completed steps
                    $(this).find('.strp-wizard-stepper__circle').text('\u2713');
                } else {
                    $(this).find('.strp-wizard-stepper__circle').text(stepNum);
                }
            });

            // Update connector lines
            $('.strp-wizard-stepper__line').each(function (index) {
                if (index < step - 1) {
                    $(this).addClass('strp-wizard-stepper__line--completed');
                } else {
                    $(this).removeClass('strp-wizard-stepper__line--completed');
                }
            });
        },

        nextStep: function () {
            if (this.currentStep < this.totalSteps) {
                this.goToStep(this.currentStep + 1);
            }
        },

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

        skipStep: function () {
            this.nextStep();
        },

        goToStep: function (step) {
            if (step < 1 || step > this.totalSteps) return;
            this.currentStep = step;
            this.showStep(step);
            this.saveProgress(step);
        },

        saveProgress: function (step) {
            $.ajax({
                url: strp_sub_wizard.ajax_url,
                type: 'POST',
                data: {
                    action: 'strp_sub_wizard_save_step',
                    nonce: strp_sub_wizard.nonce,
                    wizard_action: 'save_progress',
                    step: step
                }
            }).fail(function () {
                // Silent failure — progress save is non-critical
            });
        },

        saveStep: function (callback) {
            if (this.saving) return;

            var self = this;
            var $step = $('#strp-wizard-step-' + this.currentStep);
            var $btn = $step.find('[data-wizard-save]');
            var data = this.getStepData(this.currentStep);

            if (!data) {
                if (typeof callback === 'function') callback();
                return;
            }

            // Validate
            if (!this.validateStep(this.currentStep)) {
                return;
            }

            this.saving = true;
            $btn.addClass('strp-wizard-btn--loading');
            var originalText = $btn.text();
            $btn.text(strp_sub_wizard.i18n_saving);

            data.action = 'strp_sub_wizard_save_step';
            data.nonce = strp_sub_wizard.nonce;
            data.step = this.currentStep;

            $.ajax({
                url: strp_sub_wizard.ajax_url,
                type: 'POST',
                data: data,
                success: function (response) {
                    self.saving = false;
                    $btn.removeClass('strp-wizard-btn--loading');
                    $btn.text(originalText);

                    if (response.success) {
                        if (typeof callback === 'function') callback();
                    } else {
                        var msg = response.data && response.data.message
                            ? response.data.message
                            : strp_sub_wizard.i18n_error;
                        self.showNotice($step, 'error', msg);
                    }
                },
                error: function () {
                    self.saving = false;
                    $btn.removeClass('strp-wizard-btn--loading');
                    $btn.text(originalText);
                    self.showNotice($step, 'error', strp_sub_wizard.i18n_error);
                }
            });
        },

        getStepData: function (step) {
            var data = { wizard_action: 'save_settings' };
            var $step = $('#strp-wizard-step-' + step);

            switch (step) {
                case 2: // Connect Stripe
                    data.test_mode = $step.find('[name="test_mode"]').val() || 'yes';
                    break;

                case 3: // Products
                    data.monthly_product_id = $step.find('[name="monthly_product_id"]').val() || '';
                    data.annual_product_id = $step.find('[name="annual_product_id"]').val() || '';
                    data.lifetime_product_id = $step.find('[name="lifetime_product_id"]').val() || '';
                    data.monthly_price_id = $step.find('[name="monthly_price_id"]').val() || '';
                    data.annual_price_id = $step.find('[name="annual_price_id"]').val() || '';
                    data.lifetime_price_id = $step.find('[name="lifetime_price_id"]').val() || '';
                    break;

                case 4: // Webhooks
                    data.test_webhook_secret = $step.find('[name="test_webhook_secret"]').val() || '';
                    data.live_webhook_secret = $step.find('[name="live_webhook_secret"]').val() || '';
                    break;

                case 5: // Email
                    data.welcome_email_subject = $step.find('[name="welcome_email_subject"]').val() || '';
                    data.welcome_email_intro = $step.find('[name="welcome_email_intro"]').val() || '';
                    data.trial_ending_email_subject = $step.find('[name="trial_ending_email_subject"]').val() || '';
                    data.trial_ending_email_intro = $step.find('[name="trial_ending_email_intro"]').val() || '';
                    break;

                default:
                    return null;
            }

            return data;
        },

        validateStep: function (step) {
            // Steps 1 and 2 don't need validation (OAuth is handled externally)
            // Steps 3-5 are all optional
            return true;
        },

        verifyWebhook: function ($btn) {
            var self = this;
            var $step = $('#strp-wizard-step-4');
            var testSecret = $step.find('[name="test_webhook_secret"]').val();
            var liveSecret = $step.find('[name="live_webhook_secret"]').val();

            if (!testSecret && !liveSecret) {
                self.showNotice($step, 'error', strp_sub_wizard.i18n_webhook_empty);
                return;
            }

            $btn.addClass('strp-wizard-btn--loading');

            $.ajax({
                url: strp_sub_wizard.ajax_url,
                type: 'POST',
                data: {
                    action: 'strp_sub_wizard_save_step',
                    nonce: strp_sub_wizard.nonce,
                    wizard_action: 'verify_webhook',
                    test_webhook_secret: testSecret,
                    live_webhook_secret: liveSecret
                },
                success: function (response) {
                    $btn.removeClass('strp-wizard-btn--loading');
                    if (response.success) {
                        self.showNotice($step, 'success', strp_sub_wizard.i18n_webhook_ok);
                    } else {
                        var msg = response.data && response.data.message
                            ? response.data.message
                            : strp_sub_wizard.i18n_webhook_fail;
                        self.showNotice($step, 'error', msg);
                    }
                },
                error: function () {
                    $btn.removeClass('strp-wizard-btn--loading');
                    self.showNotice($step, 'error', strp_sub_wizard.i18n_error);
                }
            });
        },

        finishWizard: function () {
            var self = this;
            var $step = $('#strp-wizard-step-' + this.currentStep);
            var $btn = $step.find('[data-wizard-finish]');
            var data = this.getStepData(this.currentStep);

            $btn.addClass('strp-wizard-btn--loading');

            // Save the last step data first
            var saveData = data || {};
            saveData.action = 'strp_sub_wizard_save_step';
            saveData.nonce = strp_sub_wizard.nonce;
            saveData.wizard_action = 'finish';
            saveData.step = this.currentStep;

            $.ajax({
                url: strp_sub_wizard.ajax_url,
                type: 'POST',
                data: saveData,
                success: function (response) {
                    if (response.success && response.data && response.data.redirect && response.data.redirect.indexOf(window.location.origin) === 0) {
                        window.location.href = response.data.redirect;
                    } else {
                        window.location.href = strp_sub_wizard.settings_url;
                    }
                },
                error: function () {
                    $btn.removeClass('strp-wizard-btn--loading');
                    self.showNotice($step, 'error', strp_sub_wizard.i18n_error);
                }
            });
        },

        showNotice: function ($container, type, message) {
            // Remove existing notices
            $container.find('.strp-wizard-notice').remove();

            var $notice = $('<div class="strp-wizard-notice" role="alert"></div>').addClass('strp-wizard-notice--' + type).text(message);
            $container.find('.strp-wizard-step__header').after($notice);

            // Auto-dismiss after 5s
            setTimeout(function () {
                $notice.fadeOut(300, function () {
                    $(this).remove();
                });
            }, 5000);
        },

        copyToClipboard: function (text, $btn) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(function () {
                    var original = $btn.text();
                    $btn.text(strp_sub_wizard.i18n_copied);
                    setTimeout(function () {
                        $btn.text(original);
                    }, 2000);
                }).catch(function () {
                    // Clipboard API denied — silent fallback
                });
            } else {
                var $temp = $('<textarea>').css({ position: 'fixed', left: '-9999px' });
                $('body').append($temp);
                $temp.val(text).select();
                try { document.execCommand('copy'); } catch (e) { /* ignored */ }
                $temp.remove();
                var original = $btn.text();
                $btn.text(strp_sub_wizard.i18n_copied);
                setTimeout(function () {
                    $btn.text(original);
                }, 2000);
            }
        }
    };

    $(document).ready(function () {
        if ($('.strp-wizard-wrap').length) {
            Wizard.init();
        }
    });

})(jQuery);
