/**
 * Setup Wizard Controller - First-time configuration wizard.
 *
 * This script manages the multi-step setup wizard that guides users through
 * initial plugin configuration, including API key setup and preferences.
 *
 * ## Wizard Steps
 *
 * | Step        | Description                           |
 * |-------------|---------------------------------------|
 * | welcome     | Introduction and overview             |
 * | api-keys    | Configure AI provider API keys        |
 * | preferences | Set language, website type, options   |
 * | complete    | Finish wizard and redirect            |
 *
 * ## Features
 *
 * - Multi-step navigation with validation
 * - Real-time API key validation
 * - Password visibility toggle
 * - Skip confirmation modal
 * - Auto-save between steps
 * - Responsive design
 *
 * ## AJAX Actions
 *
 * | Action                          | Purpose                    |
 * |---------------------------------|----------------------------|
 * | infyp_wizard_save_step        | Save step data             |
 * | infyp_wizard_validate_api_key | Validate API key           |
 * | infyp_wizard_complete         | Complete wizard            |
 * | infyp_wizard_skip             | Skip wizard                |
 *
 * ## Localized Data
 *
 * Uses `infyp_wizard` global object with:
 * - `ajax_url` - WordPress AJAX endpoint
 * - `nonce` - Security nonce
 * - `strings` - Translated UI strings
 *
 * @file Setup wizard controller and UI handler.
 * @author AI Image SEO
 * @since 1.0.0
 * @requires jQuery
 */

(function($) {
    'use strict';

    /**
     * Wizard Controller object.
     *
     * Manages all wizard functionality including navigation,
     * validation, and data persistence.
     *
     * @namespace WizardController
     */
    const WizardController = {
        /**
         * Validation timeout for debouncing API key checks.
         * @type {number|null}
         */
        validationTimeout: null,

        /**
         * Track which API keys have been validated.
         * @type {Object.<string, boolean>}
         */
        validatedKeys: {},

        /**
         * Initialize the wizard
         */
        init: function() {
            this.bindEvents();
            this.initApiKeyStatus();
        },

        /**
         * Bind all event handlers
         */
        bindEvents: function() {
            // Navigation
            $(document).on('click', '.infyp-wizard-next', this.handleNext.bind(this));
            $(document).on('click', '#infyp-wizard-complete', this.handleComplete.bind(this));
            $(document).on('click', '#infyp-wizard-skip', this.handleSkip.bind(this));

            // API Key inputs
            $(document).on('input', '.infyp-api-input', this.handleApiKeyInput.bind(this));
            $(document).on('blur', '.infyp-api-input', this.validateApiKey.bind(this));

            // Toggle visibility
            $(document).on('click', '.infyp-toggle-visibility', this.toggleVisibility.bind(this));

            // Disclosure panel toggle
            $(document).on('click', '.infyp-disclosure-trigger', this.toggleDisclosure.bind(this));

            // Form submission prevention
            $(document).on('submit', 'form', function(e) {
                e.preventDefault();
            });
        },

        /**
         * Initialize API key status from existing data
         */
        initApiKeyStatus: function() {
            $('.infyp-api-card.has-key').each(function() {
                const provider = $(this).data('provider');
                WizardController.validatedKeys[provider] = true;
            });
        },

        /**
         * Handle next button click
         */
        handleNext: function(e) {
            e.preventDefault();

            const $btn = $(e.currentTarget);
            const nextStep = $btn.data('next-step');
            const currentStep = this.getCurrentStep();

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

            // Save step data
            $btn.addClass('loading').prop('disabled', true);

            this.saveStepData(currentStep).then(function(response) {
                if (response.success) {
                    // Navigate to next step
                    window.location.href = infyp_wizard.ajax_url.replace('admin-ajax.php', 'admin.php') + '?page=ai-image-seo-optimizer-wizard&step=' + nextStep;
                } else {
                    WizardController.showError(response.data.message);
                    $btn.removeClass('loading').prop('disabled', false);
                }
            }).catch(function(error) {
                WizardController.showError(infyp_wizard.strings.error);
                $btn.removeClass('loading').prop('disabled', false);
            });
        },

        /**
         * Handle complete button click
         */
        handleComplete: function(e) {
            e.preventDefault();

            const $btn = $(e.currentTarget);
            const currentStep = this.getCurrentStep();

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

            $btn.addClass('loading').prop('disabled', true);

            // Save preferences first
            this.saveStepData(currentStep).then(function() {
                // Then complete the wizard
                return $.ajax({
                    url: infyp_wizard.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'infyp_wizard_complete',
                        nonce: infyp_wizard.nonce
                    }
                });
            }).then(function(response) {
                if (response.success) {
                    window.location.href = response.data.redirect_url;
                } else {
                    WizardController.showError(response.data.message);
                    $btn.removeClass('loading').prop('disabled', false);
                }
            }).catch(function(error) {
                WizardController.showError(infyp_wizard.strings.error);
                $btn.removeClass('loading').prop('disabled', false);
            });
        },

        /**
         * Handle skip button click
         */
        handleSkip: function(e) {
            e.preventDefault();
            this.showSkipModal();
        },

        /**
         * Show skip confirmation modal
         */
        showSkipModal: function() {
            // Create modal if it doesn't exist
            if (!$('#infyp-skip-modal').length) {
                const modalHtml = `
                    <div class="infyp-modal-overlay" id="infyp-skip-modal">
                        <div class="infyp-modal">
                            <div class="infyp-modal-icon">
                                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <circle cx="12" cy="12" r="10"/>
                                    <line x1="12" y1="8" x2="12" y2="12"/>
                                    <line x1="12" y1="16" x2="12.01" y2="16"/>
                                </svg>
                            </div>
                            <h3 class="infyp-modal-title">${infyp_wizard.strings.skip_title || 'Skip Setup?'}</h3>
                            <p class="infyp-modal-message">${infyp_wizard.strings.skip_confirm}</p>
                            <div class="infyp-modal-actions">
                                <button type="button" class="infyp-btn infyp-btn-secondary" id="infyp-skip-cancel">
                                    ${infyp_wizard.strings.cancel || 'Cancel'}
                                </button>
                                <button type="button" class="infyp-btn infyp-btn-danger" id="infyp-skip-confirm">
                                    ${infyp_wizard.strings.skip_button || 'Skip Setup'}
                                </button>
                            </div>
                        </div>
                    </div>
                `;
                $('body').append(modalHtml);

                // Bind modal events
                $(document).on('click', '#infyp-skip-cancel', this.hideSkipModal.bind(this));
                $(document).on('click', '#infyp-skip-confirm', this.confirmSkip.bind(this));
                $(document).on('click', '#infyp-skip-modal', function(e) {
                    if ($(e.target).is('#infyp-skip-modal')) {
                        WizardController.hideSkipModal();
                    }
                });
                $(document).on('keydown', function(e) {
                    if (e.key === 'Escape' && $('#infyp-skip-modal').hasClass('active')) {
                        WizardController.hideSkipModal();
                    }
                });
            }

            // Show modal
            $('#infyp-skip-modal').addClass('active');
            $('body').addClass('infyp-modal-open');
        },

        /**
         * Hide skip confirmation modal
         */
        hideSkipModal: function() {
            $('#infyp-skip-modal').removeClass('active');
            $('body').removeClass('infyp-modal-open');
        },

        /**
         * Confirm skip action
         */
        confirmSkip: function() {
            const $btn = $('#infyp-skip-confirm');
            $btn.addClass('loading').prop('disabled', true);

            $.ajax({
                url: infyp_wizard.ajax_url,
                type: 'POST',
                data: {
                    action: 'infyp_wizard_skip',
                    nonce: infyp_wizard.nonce
                }
            }).then(function(response) {
                if (response.success) {
                    window.location.href = response.data.redirect_url;
                } else {
                    WizardController.showError(response.data.message);
                    WizardController.hideSkipModal();
                    $btn.removeClass('loading').prop('disabled', false);
                }
            }).catch(function(error) {
                WizardController.showError(infyp_wizard.strings.error);
                WizardController.hideSkipModal();
                $btn.removeClass('loading').prop('disabled', false);
            });
        },

        /**
         * Get current step from URL or page
         */
        getCurrentStep: function() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('step') || 'welcome';
        },

        /**
         * Validate current step
         */
        validateStep: function(step) {
            switch (step) {
                case 'api-keys':
                    return this.validateApiKeysStep();
                default:
                    return true;
            }
        },

        /**
         * Validate API keys step
         */
        validateApiKeysStep: function() {
            // Check if at least one API key is provided
            let hasKey = false;
            const providers = ['openai', 'google', 'anthropic'];

            providers.forEach(function(provider) {
                const $input = $('#infyp-api-' + provider);
                const value = $input.val().trim();
                const $card = $input.closest('.infyp-api-card');

                if (value || $card.hasClass('has-key')) {
                    hasKey = true;
                }
            });

            if (!hasKey) {
                this.showError(infyp_wizard.strings.api_key_required, '#infyp-api-notice');
                return false;
            }

            return true;
        },

        /**
         * Save step data via AJAX
         */
        saveStepData: function(step) {
            const data = this.collectStepData(step);

            return $.ajax({
                url: infyp_wizard.ajax_url,
                type: 'POST',
                data: {
                    action: 'infyp_wizard_save_step',
                    nonce: infyp_wizard.nonce,
                    step: step,
                    data: data
                }
            });
        },

        /**
         * Collect data from current step
         */
        collectStepData: function(step) {
            const data = {};

            switch (step) {
                case 'api-keys':
                    ['openai', 'google', 'anthropic'].forEach(function(provider) {
                        const value = $('#infyp-api-' + provider).val().trim();
                        if (value) {
                            data[provider] = value;
                        }
                    });
                    break;

                case 'preferences':
                    data.website_type = $('#infyp-website-type').val();
                    data.language = $('#infyp-language').val();
                    data.image_count = $('input[name="image_count"]:checked').val();
                    // Newsletter opt-in uses logged-in user's data
                    data.newsletter_consent = $('input[name="newsletter_consent"]').is(':checked') ? 1 : 0;
                    data.user_email = $('input[name="user_email"]').val();
                    data.user_name = $('input[name="user_name"]').val();
                    data.user_id = $('input[name="user_id"]').val();
                    // Telemetry preferences (only relevant when newsletter is checked)
                    if (data.newsletter_consent) {
                        data.telemetry_environment = $('input[name="telemetry_environment"]').is(':checked') ? 1 : 0;
                        data.telemetry_theme = $('input[name="telemetry_theme"]').is(':checked') ? 1 : 0;
                        data.telemetry_content = $('input[name="telemetry_content"]').is(':checked') ? 1 : 0;
                        data.telemetry_plugins = $('input[name="telemetry_plugins"]').is(':checked') ? 1 : 0;
                    }
                    break;
            }

            return data;
        },

        /**
         * Handle API key input
         */
        handleApiKeyInput: function(e) {
            const $input = $(e.target);
            const provider = $input.data('provider');

            // Clear validation timeout
            clearTimeout(this.validationTimeout);

            // Remove previous validation status
            this.updateApiKeyStatus(provider, '');
            delete this.validatedKeys[provider];
        },

        /**
         * Validate API key on blur
         */
        validateApiKey: function(e) {
            const $input = $(e.target);
            const provider = $input.data('provider');
            const apiKey = $input.val().trim();

            if (!apiKey) {
                this.updateApiKeyStatus(provider, '');
                return;
            }

            // Show validating status
            this.updateApiKeyStatus(provider, 'validating');

            $.ajax({
                url: infyp_wizard.ajax_url,
                type: 'POST',
                data: {
                    action: 'infyp_wizard_validate_api_key',
                    nonce: infyp_wizard.nonce,
                    provider: provider,
                    api_key: apiKey
                }
            }).then(function(response) {
                if (response.success) {
                    WizardController.updateApiKeyStatus(provider, 'connected');
                    WizardController.validatedKeys[provider] = true;
                } else {
                    WizardController.updateApiKeyStatus(provider, 'invalid');
                    delete WizardController.validatedKeys[provider];
                }
            }).catch(function() {
                WizardController.updateApiKeyStatus(provider, 'invalid');
                delete WizardController.validatedKeys[provider];
            });
        },

        /**
         * Update API key status badge
         */
        updateApiKeyStatus: function(provider, status) {
            const $statusContainer = $('#infyp-status-' + provider);
            const $card = $statusContainer.closest('.infyp-api-card');

            $card.removeClass('has-key');

            if (!status) {
                $statusContainer.html('');
                return;
            }

            let html = '';
            switch (status) {
                case 'validating':
                    html = '<span class="infyp-status-badge validating">' + infyp_wizard.strings.validating + '</span>';
                    break;
                case 'connected':
                    html = '<span class="infyp-status-badge connected">' +
                           '<svg width="16" height="16" viewBox="0 0 16 16" fill="none">' +
                           '<path d="M13.5 4.5L6 12L2.5 8.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
                           '</svg>' +
                           infyp_wizard.strings.valid +
                           '</span>';
                    $card.addClass('has-key');
                    break;
                case 'invalid':
                    html = '<span class="infyp-status-badge invalid">' + infyp_wizard.strings.invalid + '</span>';
                    break;
            }

            $statusContainer.html(html);
        },

        /**
         * Toggle data disclosure panel
         */
        toggleDisclosure: function(e) {
            e.preventDefault();

            const $trigger = $(e.currentTarget);
            const $content = $trigger.siblings('.infyp-disclosure-content');
            const isExpanded = $trigger.attr('aria-expanded') === 'true';

            $trigger.attr('aria-expanded', !isExpanded);
            $content.attr('aria-hidden', isExpanded);
        },

        /**
         * Toggle password visibility
         */
        toggleVisibility: function(e) {
            e.preventDefault();

            const $btn = $(e.currentTarget);
            const $input = $btn.siblings('.infyp-api-input');
            const isPassword = $input.attr('type') === 'password';

            $input.attr('type', isPassword ? 'text' : 'password');
            $btn.find('.eye-open').toggle(!isPassword);
            $btn.find('.eye-closed').toggle(isPassword);
        },

        /**
         * Show error message
         */
        showError: function(message, selector) {
            const $notice = selector ? $(selector) : $('#infyp-api-notice');

            if ($notice.length) {
                $notice.addClass('error').find('span').text(message);

                // Scroll to notice
                $('html, body').animate({
                    scrollTop: $notice.offset().top - 100
                }, 300);

                // Remove error class after 5 seconds
                setTimeout(function() {
                    $notice.removeClass('error');
                }, 5000);
            } else {
                alert(message);
            }
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        WizardController.init();
    });

})(jQuery);
