/**
 * Wizard JavaScript
 *
 * @package SlideMind
 * @since 2.0.0
 */

(function($) {
    'use strict';

    // Namespace
    window.SM = window.SM || {};

    // Templates de prompts (chargés dynamiquement depuis la DB)
    SM.WizardTemplates = {};

    // Chargeur de templates
    SM.WizardTemplateLoader = {
        loaded: false,

        load: function(callback) {
            var self = this;

            var onDone = function(response) {
                if (response && response.success && response.data.templates) {
                    response.data.templates.forEach(function(t) {
                        SM.WizardTemplates[t.slug] = {
                            name: t.title,
                            prompt: t.system_prompt || '',
                            variables: t.variables || [],
                            icon: t.icon || '',
                            description: t.description || '',
                            widget_mode: t.widget_mode || '',
                            max_turns: t.max_turns || 0,
                            closing_message: t.closing_message || '',
                            opening_message: t.opening_message || '',
                            graceful_close: !!t.graceful_close,
                            output_variables: t.output_variables || [],
                            temperature: t.temperature,
                            max_tokens: t.max_tokens
                        };
                    });
                }

                // L'option personnalisé est toujours ajoutée en dernier
                SM.WizardTemplates['custom'] = {
                    name: slidemindWizardData.strings.templateCustomName,
                    prompt: '',
                    variables: [],
                    icon: '✏️',
                    description: slidemindWizardData.strings.templateCustomDesc,
                    widget_mode: ''
                };

                self.loaded = true;

                if (callback) callback();
            };

            SM.Utils.ajax('slidemind_get_templates', {}, onDone, onDone);
        },

        buildCardHtml: function(slug, t, checked) {
            var desc = (t.description || '').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
            return '<label class="sm-template-card">' +
                '<div class="sm-template-card-content" title="' + desc + '">' +
                '<span class="sm-template-icon">' + (t.icon || '') + '</span>' +
                '<strong>' + t.name + '</strong>' +
                '<p>' + (t.description || '') + '</p>' +
                '</div>' +
                '</label>';
        },

        renderTemplateCards: function(filterMode) {
            var $container = $('.sm-template-cards');
            $container.empty();

            var favorites = (slidemindAdmin && slidemindAdmin.favoriteTemplates) ? slidemindAdmin.favoriteTemplates : [];
            var keys = SM.Utils.filterTemplateKeysByMode(Object.keys(SM.WizardTemplates), SM.WizardTemplates, filterMode);
            var self = this;

            // Separate: favorites (cards), "custom" (always a card), others (dropdown)
            var favoriteKeys = [];
            var otherKeys = [];

            keys.forEach(function(slug) {
                if (slug === 'custom') return;
                if (favorites.indexOf(slug) !== -1) {
                    favoriteKeys.push(slug);
                } else {
                    otherKeys.push(slug);
                }
            });

            // Keep favorites in the order defined in settings
            favoriteKeys.sort(function(a, b) {
                return favorites.indexOf(a) - favorites.indexOf(b);
            });

            // If no favorites set, show all as cards (backward compatible)
            if (favorites.length === 0) {
                keys.forEach(function(slug) {
                    var t = SM.WizardTemplates[slug];
                    $container.append(self.buildCardHtml(slug, t, slug === 'custom'));
                });
                return;
            }

            // Always add "Custom" card first (selected by default)
            var customT = SM.WizardTemplates['custom'];
            $container.append(self.buildCardHtml('custom', customT, true));

            // Render favorite cards
            favoriteKeys.forEach(function(slug) {
                var t = SM.WizardTemplates[slug];
                $container.append(self.buildCardHtml(slug, t, false));
            });

            // Render "other templates" dropdown if any
            if (otherKeys.length > 0) {
                var dropdownHtml = '<div class="sm-template-more">' +
                    '<label class="sm-template-card sm-template-card-dropdown">' +
                    '<div class="sm-template-card-content">' +
                    '<span class="sm-template-icon">📂</span>' +
                    '<strong>' + slidemindWizardData.strings.otherTemplates + '</strong>' +
                    '<p>' + otherKeys.length + ' template' + (otherKeys.length > 1 ? 's' : '') + '</p>' +
                    '</div>' +
                    '</label>' +
                    '<select class="sm-form-select sm-template-dropdown-select" style="display: none;">' +
                    '<option value="">' + slidemindWizardData.strings.chooseTemplate + '</option>';

                otherKeys.forEach(function(slug) {
                    var t = SM.WizardTemplates[slug];
                    dropdownHtml += '<option value="' + slug + '">' + (t.icon ? t.icon + ' ' : '') + t.name + '</option>';
                });

                dropdownHtml += '</select></div>';
                $container.append(dropdownHtml);
            }
        }
    };

    // Variables système
    SM.SystemVariables = [
        'course_theme',
        'course_objectives',
        'course_content',
        'module_theme',
        'module_objectives',
        'module_content'
    ];

    // Wizard Controller
    SM.Wizard = {
        currentStep: 1,
        maxSteps: 4,
        data: {},
        inheritedContent: null,

        init: function() {
            if ($('#sm-wizard').length === 0) return;

            var self = this;

            // Applique l'outil auteur par défaut des réglages (widget n'est plus sélectionnable — fallback storyline)
            var defaultEditor = (typeof slidemindAdmin !== 'undefined' && slidemindAdmin.defaults && slidemindAdmin.defaults.editor) || 'storyline';
            if (defaultEditor === 'widget') defaultEditor = 'storyline';
            $('#wizard-editor-select').val(defaultEditor);

            // Bind events + init Select2 immediately (no AJAX dependency)
            self.bindEvents();
            self.initSelect2();

            // Load templates asynchronously, then render cards + preset data
            SM.WizardTemplateLoader.load(function() {
                var initialMode = $('input[name="wizard_widget_mode"]:checked').val() || 'qa';
                SM.WizardTemplateLoader.renderTemplateCards(initialMode);
                self.loadPresetData();
            });
        },

        bindEvents: function() {
            var self = this;

            // Navigation
            $('#wizard-next').on('click', function() {
                self.nextStep();
            });

            $('#wizard-prev').on('click', function() {
                self.prevStep();
            });

            // Submit
            $('#sm-wizard-form').on('submit', function(e) {
                e.preventDefault();
                self.submit();
            });

            // Course change -> load modules
            $('#wizard-course').on('change', function() {
                self.loadModules($(this).val());
                self.renderVariableTags();
                if (SM.Autocomplete && SM.Autocomplete.invalidateCache) {
                    SM.Autocomplete.invalidateCache();
                }
            });

            // Module change -> load inherited content
            $('#wizard-module').on('change', function() {
                self.loadInheritedContent($(this).val());
                self.renderVariableTags();
                if (SM.Autocomplete && SM.Autocomplete.invalidateCache) {
                    SM.Autocomplete.invalidateCache();
                }
            });

            // Dropdown select for "other templates"
            $(document).on('change', '.sm-template-dropdown-select', function() {
                var slug = $(this).val();
                if (!slug) return;
                self.applyTemplate(slug);
            });

            // Prompt change -> detect variables
            $('#wizard-prompt').on('input', function() {
                self.detectVariables();
            });

            // Temperature slider
            $('#wizard-temperature').on('input', function() {
                $('#wizard-temp-value').text($(this).val());
            });

            // Model change -> show pricing
            $('#wizard-model').on('change', function() {
                self.showModelPricing($(this).find(':selected'));
            });

            // Insert variable into prompt
            $('#wizard-insert-variable').on('click', function() {
                self.insertVariableInPrompt('#wizard-prompt');
            });

            // Test button
            $('#wizard-test-btn').on('click', function() {
                self.runTest();
            });

            // Changement d'outil auteur / mode widget dans le code d'intégration
            $('#wizard-editor-select').on('change', function() {
                $('#wizard-editor-var-names').toggle($(this).val() !== 'widget');
                self.showCodeGenerator();
            });

            // Changement de noms de variables d'outil auteur
            self._editorVarsManuallyEdited = false;
            $('#wizard-editor-input-var, #wizard-editor-output-var').on('input', function() {
                self._editorVarsManuallyEdited = true;
                self.showCodeGenerator();
            });

            // Auto-generate authoring tool var names on title/number blur
            $('#wizard-title, #wizard-slide-number').on('blur', function() {
                if (self._editorVarsManuallyEdited) return;
                var title = $('#wizard-title').val();
                var number = $('#wizard-slide-number').val();
                var names = SM.Utils.generateEditorVarNames(title, number);
                if (!names) return;
                $('#wizard-editor-input-var').val(names.input);
                $('#wizard-editor-output-var').val(names.output);
                self.showCodeGenerator();
            });

            // Reset variable to default
            $(document).on('click', '.sm-editor-var-reset', function() {
                var title = $('#wizard-title').val();
                var number = $('#wizard-slide-number').val();
                var names = SM.Utils.generateEditorVarNames(title, number);
                var target = $(this).data('target');
                var isInput = target.indexOf('input') !== -1;
                var val = names ? (isInput ? names.input : names.output) : (isInput ? 'userMessage' : 'aiResponse');
                $('#' + target).val(val);
                self.showCodeGenerator();
            });

            // Widget mode toggle (step 1)
            $(document).on('change', 'input[name="wizard_widget_mode"]', function() {
                var mode = $(this).val();
                // Visual toggle
                $('.sm-mode-option').removeClass('sm-mode-option--active');
                $(this).closest('.sm-mode-option').addClass('sm-mode-option--active');
                self.applyWidgetMode(mode);
            });

            // Graceful close toggle (step 3)
            $(document).on('change', '#wizard-graceful-close', function() {
                $('#wizard-graceful-close-prompt-wrap').toggle($(this).is(':checked'));
            });

            // Capture mode: add/remove capture variable rows
            $(document).on('click', '#wizard-add-capture-var', function() {
                self.addCaptureVarRow();
            });

            // Advanced options: add capture variable rows (Q&A/Chat modes)
            $(document).on('click', '#wizard-add-adv-capture-var', function() {
                self.addCaptureVarRow('#wizard-adv-capture-vars-list');
            });

            $(document).on('click', '.wizard-capture-var-remove', function() {
                $(this).closest('.wizard-capture-var-row').remove();
            });

            // Wizard output vars: add
            $(document).on('click', '#wizard-add-output-var', function() {
                self.addOutputVarRow();
            });

            // Wizard output vars: remove
            $(document).on('click', '.wizard-output-var-remove', function() {
                $(this).closest('.wizard-output-var-row').remove();
            });

            // Wizard output vars: type change
            $(document).on('change', '.wizard-output-var-type', function() {
                self.updateOutputVarType($(this).closest('.wizard-output-var-row'));
            });

            // Auto-save interaction toggle
            $(document).on('change', '#wizard-save-interaction', function() {
                var checked = $(this).is(':checked');
                $('#wizard-autosave-suboptions').toggle(checked);
                if (checked) {
                    // Auto-generate keys from title
                    var title = $('#wizard-title').val();
                    var number = $('#wizard-slide-number').val();
                    var keys = SM.Utils.generateMemoryKeyNames(title, number);
                    if (keys) {
                        if (!$('#wizard-save-input-key').val()) $('#wizard-save-input-key').val(keys.input);
                        if (!$('#wizard-save-response-key').val()) $('#wizard-save-response-key').val(keys.response);
                    }
                    // Default: both checked
                    if (!$('#wizard-save-user-input').is(':checked') && !$('#wizard-save-ai-response').is(':checked')) {
                        $('#wizard-save-user-input, #wizard-save-ai-response').prop('checked', true);
                    }
                }
            });

            // Auto-save: at least one sub-option must stay checked
            $(document).on('change', '#wizard-save-user-input, #wizard-save-ai-response', function() {
                if (!$('#wizard-save-user-input').is(':checked') && !$('#wizard-save-ai-response').is(':checked')) {
                    $(this).prop('checked', true);
                }
            });

            // Wizard chat turns: cost projection + unlimited warning
            $(document).on('input change', '#wizard-max-turns', function() {
                var val = parseInt($(this).val()) || 0;
                $('.sm-cost-unlimited-hint').toggle(val === 0);
                self.updateWizardCostProjection();
            });

            // Step click
            $('.sm-wizard-step').on('click', function() {
                var step = parseInt($(this).data('step'));
                if (step < self.currentStep) {
                    self.showStep(step);
                }
            });
        },

        loadPresetData: function() {
            if (typeof slidemindWizardData === 'undefined') return;

            // Si un module est pré-sélectionné
            if (slidemindWizardData.presetModuleId) {
                var module = slidemindWizardData.modules.find(function(m) {
                    return m.id === slidemindWizardData.presetModuleId;
                });

                if (module) {
                    $('#wizard-course').val(module.course_id).trigger('change.select2');
                }

                this.inheritedContent = slidemindWizardData.presetInherited;
            }
        },

        initSelect2: function() {
            $('.sm-model-select').select2({
                width: '100%',
                placeholder: slidemindAdmin.strings.selectModel
            });

            // Pre-select defaults from settings
            if (slidemindAdmin.defaults) {
                if (!$('#wizard-model').val() && slidemindAdmin.defaults.model) {
                    $('#wizard-model').val(slidemindAdmin.defaults.model).trigger('change');
                }
                if (slidemindAdmin.defaults.temperature !== undefined) {
                    var $temp = $('#wizard-temperature');
                    if (parseFloat($temp.val()) === 0.7) {
                        $temp.val(slidemindAdmin.defaults.temperature);
                        $('#wizard-temp-value').text(slidemindAdmin.defaults.temperature);
                    }
                }
                if (slidemindAdmin.defaults.maxTokens !== undefined) {
                    var $tokens = $('#wizard-max-tokens');
                    if (parseInt($tokens.val()) === 1024) {
                        $tokens.val(slidemindAdmin.defaults.maxTokens);
                    }
                }
            }
        },

        showStep: function(step) {
            this.currentStep = step;
            var mode = $('input[name="wizard_widget_mode"]:checked').val();
            var isCapture = mode === 'capture';

            // Update progress
            $('.sm-wizard-step').removeClass('active completed');
            $('.sm-wizard-step').each(function() {
                var s = parseInt($(this).data('step'));
                // Don't mark skipped steps as completed
                if (isCapture && s === 2) return;
                if (s < step) {
                    $(this).addClass('completed');
                } else if (s === step) {
                    $(this).addClass('active');
                }
            });

            // Show panel
            $('.sm-wizard-panel').removeClass('active');
            $('.sm-wizard-panel[data-step="' + step + '"]').addClass('active');

            // Update navigation
            if (step === 1) {
                $('#wizard-prev').hide();
            } else {
                $('#wizard-prev').show();
            }

            if (step === this.maxSteps) {
                $('#wizard-next').hide();
                $('#wizard-submit').show();
                this.updateSummary();
                if (isCapture) {
                    this.buildCaptureSummary();
                } else {
                    this.buildTestVariables();
                    $('#wizard-prompt-preview').text($('#wizard-prompt').val() || slidemindWizardData.strings.noPromptDefined);
                }
            } else {
                $('#wizard-next').show();
                $('#wizard-submit').hide();
            }

            // Render clickable variable tags when reaching prompt step (3) in AI mode
            if (step === 3 && !isCapture) {
                this.renderVariableTags();
            }
        },

        nextStep: function() {
            if (!this.validateStep(this.currentStep)) {
                return;
            }

            var mode = $('input[name="wizard_widget_mode"]:checked').val();
            var next = this.currentStep + 1;
            // In capture mode, skip step 2 (AI model) only
            if (mode === 'capture' && next === 2) {
                next = 3;
            }
            if (next <= this.maxSteps) {
                this.showStep(next);
            }
        },

        prevStep: function() {
            var mode = $('input[name="wizard_widget_mode"]:checked').val();
            var prev = this.currentStep - 1;
            // In capture mode, skip step 2 (AI model) only
            if (mode === 'capture' && prev === 2) {
                prev = 1;
            }
            if (prev >= 1) {
                this.showStep(prev);
            }
        },

        validateStep: function(step) {
            switch (step) {
                case 1:
                    // Course et module sont optionnels (slide indépendante possible)
                    if (!$('#wizard-title').val()) {
                        SM.Utils.showToast(slidemindAdmin.strings.titleRequired, 'error');
                        return false;
                    }
                    break;

                case 2:
                    if ($('input[name="wizard_widget_mode"]:checked').val() !== 'capture' && !$('#wizard-model').val()) {
                        SM.Utils.showToast(slidemindAdmin.strings.selectModel, 'error');
                        return false;
                    }
                    break;

                case 3:
                    // Prompt optionnel mais recommandé
                    break;

                case 4:
                    // Title already validated in step 1
                    break;
            }
            return true;
        },

        loadModules: function(courseId) {
            var $select = $('#wizard-module');
            $select.html('<option value="">' + slidemindAdmin.strings.loading + '</option>');
            $('#wizard-inherited-preview').hide();

            if (!courseId) {
                $select.html('<option value="">' + slidemindWizardData.strings.noModuleIndependent + '</option>');
                return;
            }

            // Filtrer les modules
            var modules = slidemindWizardData.modules.filter(function(m) {
                return m.course_id == courseId;
            });

            if (modules.length === 0) {
                $select.html('<option value="">' + slidemindWizardData.strings.noModuleForCourse + '</option>');
                return;
            }

            var html = '<option value="">' + slidemindWizardData.strings.selectAModule + '</option>';
            modules.forEach(function(m) {
                html += '<option value="' + m.id + '">' + m.title + '</option>';
            });

            $select.html(html);

            // Pré-sélectionner si preset
            if (slidemindWizardData.presetModuleId) {
                $select.val(slidemindWizardData.presetModuleId);
                this.loadInheritedContent(slidemindWizardData.presetModuleId);
            }
        },

        loadInheritedContent: function(moduleId) {
            var self = this;

            if (!moduleId) {
                $('#wizard-inherited-preview').hide();
                return;
            }

            SM.Utils.ajax('slidemind_get_inherited_content', { module_id: moduleId }, function(response) {
                if (response.success) {
                    self.inheritedContent = response.data.inherited;
                    self.displayInheritedContent(response.data.inherited);
                }
            });
        },

        displayInheritedContent: function(inherited) {
            var html = '';

            if (inherited.course) {
                html += '<div class="sm-inherited-field"><strong>' + slidemindAdmin.strings.labelCourse + '</strong> ' + inherited.course.title + '</div>';
                html += '<div class="sm-inherited-field"><strong>' + slidemindAdmin.strings.labelTheme + '</strong> ' + (inherited.course.theme || '—') + '</div>';
            }

            if (inherited.module) {
                html += '<div class="sm-inherited-field"><strong>' + slidemindAdmin.strings.labelModule + '</strong> ' + inherited.module.title + '</div>';
                html += '<div class="sm-inherited-field"><strong>' + slidemindAdmin.strings.labelSubject + '</strong> ' + (inherited.module.subject || '—') + '</div>';
            }

            $('#wizard-inherited-content').html(html);
            $('#wizard-inherited-preview').show();
        },

        getCustomVariablesFromPrompt: function() {
            var prompt = $('#wizard-prompt').val() || '';
            var regex = /\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;
            var matches = [];
            var match;
            while ((match = regex.exec(prompt)) !== null) {
                if (matches.indexOf(match[1]) === -1) {
                    matches.push(match[1]);
                }
            }
            return matches.filter(function(v) {
                return SM.SystemVariables.indexOf(v) === -1;
            });
        },

        renderVariableTags: function() {
            var $container = $('#wizard-variable-tags');
            if (!$container.length) {
                $container = $('<div id="wizard-variable-tags" class="sm-variable-tags"></div>');
                $('#wizard-prompt').before($container);
            }
            $container.empty();

            var customVars = this.getCustomVariablesFromPrompt();
            var hasCourse = !!$('#wizard-course').val();
            var hasModule = !!$('#wizard-module').val();
            var systemVars = SM.SystemVariables.filter(function(v) {
                if (v.indexOf('course_') === 0 && !hasCourse) return false;
                if (v.indexOf('module_') === 0 && !hasModule) return false;
                return true;
            });

            if (customVars.length === 0 && systemVars.length === 0) {
                $container.hide();
                return;
            }

            var html = '<span class="sm-variable-tags-label">' + slidemindAdmin.strings.labelVariables + '</span>';
            systemVars.forEach(function(v) {
                html += '<code class="sm-clickable-var sm-tag-system">{{' + v + '}}</code>';
            });
            customVars.forEach(function(v) {
                html += '<code class="sm-clickable-var sm-tag-custom">{{' + v + '}}</code>';
            });
            $container.html(html).show();
        },

        applyWidgetMode: function(mode) {
            var isCapture = mode === 'capture';
            // Toggle conditional sections in step 3
            $('#wizard-chat-options').toggle(mode === 'chat');
            $('#wizard-output-vars-section').toggle(mode === 'qa');
            // Toggle AI prompt vs capture vars sections
            $('#wizard-ai-prompt-section').toggle(!isCapture);
            $('#wizard-capture-vars-section').toggle(isCapture);
            // Update step 3 card header
            $('#wizard-step3-title').text(isCapture ? slidemindAdmin.strings.memVarTitle : slidemindWizardData.strings.configurePromptTitle);
            // In capture mode, step 4 hides the AI quick test card, shows capture summary
            $('#wizard-test-card').toggle(!isCapture);
            $('#wizard-capture-summary').toggle(isCapture);
            // Toggle auto-save section (not in capture mode)
            $('#wizard-autosave-section').toggle(!isCapture);
            // Toggle advanced capture section (Q&A/Chat only, capture has its own section)
            $('#wizard-adv-capture-section').toggle(!isCapture);
            // Update stepper: skip step 2 in capture mode
            $('.sm-wizard-step[data-step="2"]').toggleClass('skipped', isCapture);
            // Update step 3 label in stepper
            $('.sm-wizard-step[data-step="3"] .sm-wizard-step-label').text(
                isCapture ? slidemindWizardData.strings.captureStepLabel : slidemindWizardData.strings.promptStepLabel
            );
            this.updateWizardCostProjection();

            // Re-filter template cards by mode
            if (SM.WizardTemplateLoader.loaded) {
                SM.WizardTemplateLoader.renderTemplateCards(mode);
            }
        },

        addOutputVarRow: function() {
            var ws = slidemindWizardData.strings;
            var html = '<div class="wizard-output-var-row">' +
                '<div class="wizard-output-var-row-top">' +
                '<input type="text" class="sm-form-input wizard-output-var-name" placeholder="variable_name" pattern="^[a-z][a-z0-9_]*$" style="width: 160px; flex-shrink: 0;">' +
                '<select class="sm-form-select wizard-output-var-type" style="width: 120px; flex-shrink: 0;">' +
                '<option value="texte">' + (ws.typeText || 'Text') + '</option>' +
                '<option value="nombre">' + (ws.typeNumber || 'Number') + '</option>' +
                '<option value="booleen">' + (ws.typeBoolean || 'Boolean') + '</option>' +
                '<option value="enum">' + (ws.typeEnum || 'Enum') + '</option>' +
                '</select>' +
                '<input type="text" class="sm-form-input wizard-output-var-values" placeholder="val1, val2, val3" style="display: none; flex: 1;">' +
                '<button type="button" class="sm-btn sm-btn-sm sm-btn-danger wizard-output-var-remove" style="padding: 4px; width: 32px; flex-shrink: 0;">' +
                '<span class="dashicons dashicons-no-alt" style="font-size: 16px; width: 16px; height: 16px;"></span>' +
                '</button>' +
                '</div>' +
                '<input type="text" class="sm-form-input wizard-output-var-desc" placeholder="' + (slidemindAdmin.strings.placeholderDescOptional || '') + '">' +
                '</div>';
            $('#wizard-output-vars-list').append(html);
        },

        updateOutputVarType: function($row) {
            var type = $row.find('.wizard-output-var-type').val();
            var s = slidemindAdmin.strings;
            $row.find('.wizard-output-var-values').toggle(type === 'enum');
            var placeholder = s.placeholderDescOptional || '';
            if (type === 'nombre') placeholder = s.placeholderDescNumber || placeholder;
            else if (type === 'booleen') placeholder = s.placeholderDescBoolean || placeholder;
            $row.find('.wizard-output-var-desc').attr('placeholder', placeholder);
        },

        collectOutputVariables: function() {
            var vars = [];
            $('#wizard-output-vars-list .wizard-output-var-row').each(function() {
                var name = $(this).find('.wizard-output-var-name').val().trim();
                var type = $(this).find('.wizard-output-var-type').val();
                if (name) {
                    var entry = { name: name, type: type, description: $(this).find('.wizard-output-var-desc').val().trim() || '' };
                    if (type === 'enum') {
                        entry.values = $(this).find('.wizard-output-var-values').val().trim();
                    }
                    vars.push(entry);
                }
            });
            return vars;
        },

        collectAutoSaveData: function() {
            if (!$('#wizard-save-interaction').is(':checked')) return null;
            return {
                save_user_input:  $('#wizard-save-user-input').is(':checked') ? '1' : '0',
                save_ai_response: $('#wizard-save-ai-response').is(':checked') ? '1' : '0',
                save_input_key:   $('#wizard-save-input-key').val() || '',
                save_response_key: $('#wizard-save-response-key').val() || '',
                save_interaction_scope: $('#wizard-save-interaction-scope').val() || 'global'
            };
        },

        addCaptureVarRow: function(targetList) {
            var listId = targetList || '#wizard-capture-vars-list';
            var s = slidemindAdmin.strings;
            var canScope = !!(slidemindAdmin.proFeatures && slidemindAdmin.proFeatures.scope_course_module);
            var scopeOptions = '<option value="global">' + s.memVarScopeGlobal + '</option>';
            if (canScope) {
                scopeOptions += '<option value="course">' + s.memVarScopeCourse + '</option>' +
                                '<option value="module">' + s.memVarScopeModule + '</option>';
            }
            var html = '<div class="wizard-capture-var-row">' +
                '<input type="text" class="sm-form-input wizard-capture-var-name" placeholder="' + s.memVarNamePlaceholder + '" pattern="^[a-z][a-z0-9_]*$" style="width: 140px; flex-shrink: 0;">' +
                '<select class="sm-form-select wizard-capture-var-scope" style="width: 120px; flex-shrink: 0;">' +
                scopeOptions +
                '</select>' +
                '<input type="text" class="sm-form-input wizard-capture-var-source" placeholder="' + s.memVarSourcePlaceholder + '" style="flex: 1;">' +
                '<button type="button" class="sm-btn sm-btn-sm sm-btn-danger wizard-capture-var-remove" style="padding: 4px; width: 32px; flex-shrink: 0;">' +
                '<span class="dashicons dashicons-no-alt" style="font-size: 16px; width: 16px; height: 16px;"></span>' +
                '</button>' +
                '</div>';
            $(listId).append(html);
        },

        collectCaptureVariables: function() {
            var vars = [];
            $('#wizard-capture-vars-list .wizard-capture-var-row, #wizard-adv-capture-vars-list .wizard-capture-var-row').each(function() {
                var name = $(this).find('.wizard-capture-var-name').val().trim();
                var scope = $(this).find('.wizard-capture-var-scope').val();
                var source = $(this).find('.wizard-capture-var-source').val().trim();
                if (name && source) {
                    vars.push({ name: name, scope: scope, source: source });
                }
            });
            return vars;
        },

        buildCaptureSummary: function() {
            var vars = this.collectCaptureVariables();
            var $container = $('#wizard-capture-summary-content');

            if (vars.length === 0) {
                $container.html('<p class="sm-form-help">' + slidemindWizardData.strings.captureNoVars + '</p>');
                return;
            }

            var s = slidemindWizardData.strings;
            var html = '<table class="widefat striped" style="font-size: 13px;">' +
                '<thead><tr>' +
                '<th>' + s.columnName + '</th>' +
                '<th>' + s.columnScope + '</th>' +
                '<th>' + s.columnSource + '</th>' +
                '</tr></thead><tbody>';

            vars.forEach(function(v) {
                var scopeLabel = v.scope === 'global' ? slidemindAdmin.strings.memVarScopeGlobal :
                                 v.scope === 'course' ? slidemindAdmin.strings.memVarScopeCourse :
                                 slidemindAdmin.strings.memVarScopeModule;
                var safeName = $('<span>').text(v.name).html();
                var safeSource = $('<span>').text(v.source).html();
                html += '<tr>' +
                    '<td><code>' + safeName + '</code></td>' +
                    '<td>' + scopeLabel + '</td>' +
                    '<td><code>' + safeSource + '</code></td>' +
                    '</tr>';
            });

            html += '</tbody></table>';
            $container.html(html);
        },

        updateWizardCostProjection: function() {
            var $container = $('#wizard-chat-cost-projection');
            if (!$container.length) return;

            var mode = $('input[name="wizard_widget_mode"]:checked').val();
            if (mode !== 'chat') {
                $container.empty().hide();
                return;
            }

            var $selected = $('#wizard-model option:selected');
            var pricing = $selected.data('pricing') || null;
            var turns = parseInt($('#wizard-max-turns').val()) || 0;

            if (typeof SM !== 'undefined' && SM.Utils && SM.Utils.renderChatCostProjection) {
                SM.Utils.renderChatCostProjection($container, pricing, turns);
            }
        },

        applyTemplate: function(type) {
            var t = SM.WizardTemplates[type];
            if (!t) return;

            // Prompt
            $('#wizard-prompt').val(t.prompt || '');
            this.detectVariables();

            // Temperature + max tokens from template
            if (t.temperature !== undefined) {
                $('#wizard-temperature').val(t.temperature);
                $('#wizard-temp-value').text(t.temperature);
            }
            if (t.max_tokens) {
                $('#wizard-max-tokens').val(t.max_tokens);
            }

            // Chat fields (only if current mode is chat — wizard doesn't change mode from template)
            var currentMode = $('input[name="wizard_widget_mode"]:checked').val() || 'qa';
            if (currentMode === 'chat') {
                if (t.max_turns) $('#wizard-max-turns').val(t.max_turns);
                if (t.closing_message) $('#wizard-closing-message').val(t.closing_message);
                if (t.opening_message) $('#wizard-opening-message').val(t.opening_message);
                if (t.graceful_close) $('#wizard-graceful-close').prop('checked', true).trigger('change');
            }

            // Output variables: load from template or clear
            if (t.output_variables && t.output_variables.length) {
                var self = this;
                $('#wizard-output-vars-list').empty();
                t.output_variables.forEach(function(v) {
                    self.addOutputVarRow();
                    var $row = $('#wizard-output-vars-list .wizard-output-var-row:last');
                    $row.find('.wizard-output-var-name').val(v.name || '');
                    $row.find('.wizard-output-var-type').val(v.type || 'texte');
                    self.updateOutputVarType($row);
                    $row.find('.wizard-output-var-desc').val(v.description || '');
                    if (v.type === 'enum' && v.values) {
                        $row.find('.wizard-output-var-values').val(v.values);
                    }
                });
            } else {
                $('#wizard-output-vars-list').empty();
            }
        },

        detectVariables: function() {
            this.renderVariableTags();
        },

        insertVariableInPrompt: function(selector) {
            var name = prompt(slidemindAdmin.strings.variableNamePrompt);
            if (!name) return;

            name = name.replace(/[^a-zA-Z0-9_]/g, '_').toLowerCase();
            var tag = '{{' + name + '}}';
            var $textarea = $(selector);
            var textarea = $textarea[0];
            var start = textarea.selectionStart;
            var end = textarea.selectionEnd;
            var text = $textarea.val();

            $textarea.val(text.substring(0, start) + tag + text.substring(end));
            textarea.selectionStart = textarea.selectionEnd = start + tag.length;
            $textarea.focus();
            this.detectVariables();
        },

        showModelPricing: function($option) {
            var pricing = $option.data('pricing');
            var $container = $('#wizard-model-pricing');

            if (!pricing) {
                $container.hide();
                this.updateWizardCostProjection();
                return;
            }

            var text = SM.Utils.formatModelPricing(pricing);
            if (text) {
                $('#wizard-pricing-text').text(text);
                $container.show();
            } else {
                $container.hide();
            }

            this.updateWizardCostProjection();
        },

        updateSummary: function() {
            var titleText = $('#wizard-title').val();
            var courseText = $('#wizard-course option:selected').text();
            var moduleText = $('#wizard-module option:selected').text();
            var modelText = $('#wizard-model option:selected').text();

            var customVars = this.getCustomVariablesFromPrompt();
            var widgetMode = $('input[name="wizard_widget_mode"]:checked').val() || 'qa';
            var modeLabel;
            if (widgetMode === 'chat') {
                modeLabel = slidemindWizardData.strings.modeChat || 'Chat';
            } else if (widgetMode === 'capture') {
                modeLabel = slidemindWizardData.strings.modeCapture || 'Capture';
            } else {
                modeLabel = slidemindWizardData.strings.modeQA || 'Q&A';
            }
            var isCapture = widgetMode === 'capture';

            $('#summary-title').text(titleText || '—');
            $('#summary-course').text($('#wizard-course').val() ? courseText : '—');
            $('#summary-module').text($('#wizard-module').val() ? moduleText : '—');
            $('#summary-model').closest('.sm-summary-row').toggle(!isCapture);
            $('#summary-model').text(modelText || '—');
            $('#summary-mode').text(modeLabel);

            if (isCapture) {
                var captureVars = this.collectCaptureVariables();
                var varNames = captureVars.map(function(v) { return v.name; });
                $('#summary-variables').text(varNames.length > 0 ? varNames.join(', ') : slidemindWizardData.strings.noVariables);
            } else {
                $('#summary-variables').text(customVars.length > 0 ? customVars.join(', ') : slidemindWizardData.strings.noVariables);
            }

            // Memory summary row
            var $memRow = $('#summary-memory').closest('.sm-summary-row');
            var autoSave = !isCapture ? this.collectAutoSaveData() : null;
            var memParts = [];
            if (autoSave) {
                var saveParts = [];
                if (autoSave.save_user_input === '1') saveParts.push(autoSave.save_input_key || '?');
                if (autoSave.save_ai_response === '1') saveParts.push(autoSave.save_response_key || '?');
                if (saveParts.length) {
                    var scope = $('#wizard-save-interaction-scope option:selected').text();
                    memParts.push(saveParts.join(', ') + ' (' + scope + ')');
                }
            }
            if (!isCapture) {
                var advCapture = this.collectCaptureVariables();
                if (advCapture.length > 0) {
                    var capNames = advCapture.map(function(v) { return v.name; });
                    memParts.push(slidemindAdmin.strings.memVarTitle + ': ' + capNames.join(', '));
                }
            }
            if (memParts.length) {
                $('#summary-memory').text(memParts.join(' · '));
                $memRow.show();
            } else {
                $memRow.hide();
            }

            // Notes summary row
            var notes = $('#wizard-notes').val();
            var $notesRow = $('#summary-notes').closest('.sm-summary-row');
            if (notes) {
                $('#summary-notes').text(notes.length > 60 ? notes.substring(0, 60) + '...' : notes);
                $notesRow.show();
            } else {
                $notesRow.hide();
            }
        },

        buildTestVariables: function() {
            var $container = $('#wizard-test-variables');
            $container.empty();
            this.getCustomVariablesFromPrompt().forEach(function(name) {
                var html = '<div class="sm-form-group">' +
                    '<label class="sm-form-label">' + name + '</label>' +
                    '<input type="text" class="sm-form-input sm-test-var" data-var="' + name + '">' +
                    '</div>';
                $container.append(html);
            });
        },

        runTest: function() {
            var self = this;
            var $btn = $('#wizard-test-btn');
            var $result = $('#wizard-test-result');

            // Collect data
            var moduleId = $('#wizard-module').val();
            var modelId = $('#wizard-model').val();
            var prompt = $('#wizard-prompt').val();
            var message = $('#wizard-test-message').val();
            var temperature = parseFloat($('#wizard-temperature').val());
            var maxTokens = parseInt($('#wizard-max-tokens').val());

            if (!message) {
                SM.Utils.showToast(slidemindAdmin.strings.enterTestMessage, 'error');
                return;
            }

            // Collect test variables
            var variables = {};
            $('.sm-test-var').each(function() {
                variables[$(this).data('var')] = $(this).val();
            });

            $btn.prop('disabled', true).text(slidemindAdmin.strings.testing);
            $result.hide();

            // Build request
            var requestData = {
                model: modelId,
                system_prompt: prompt,
                response_example: $('#wizard-response-example').val() || '',
                temperature: temperature,
                max_tokens: maxTokens,
                messages: [{ role: 'user', content: message }],
                variables: variables,
                provider: $('#wizard-provider').val() || '',
                widget_mode: $('input[name="wizard_widget_mode"]:checked').val() || 'qa'
            };

            // If we have inherited content, add it
            if (self.inheritedContent) {
                if (self.inheritedContent.course) {
                    variables.course_theme = self.inheritedContent.course.theme || '';
                    variables.course_objectives = self.inheritedContent.course.objectives || '';
                    variables.course_content = self.inheritedContent.course.content || '';
                    variables.course_response_example = self.inheritedContent.course.response_example || '';
                }
                if (self.inheritedContent.module) {
                    variables.module_theme = self.inheritedContent.module.theme || '';
                    variables.module_objectives = self.inheritedContent.module.objectives || '';
                    variables.module_content = self.inheritedContent.module.content || '';
                    variables.module_response_example = self.inheritedContent.module.response_example || '';
                }
                requestData.variables = variables;
            }

            // Call sandbox endpoint
            $.ajax({
                url: slidemindAdmin.restUrl + 'sandbox/test',
                method: 'POST',
                headers: {
                    'X-WP-Nonce': slidemindAdmin.restNonce
                },
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(response) {
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-visibility"></span> ' + slidemindAdmin.strings.testButton);

                    if (response.success) {
                        $('#wizard-test-response').text(response.message.content || response.message);
                        $('#debug-tokens').text((response.usage?.total_tokens || '—'));
                        $('#debug-time').text((response.meta?.response_time || '—') + 'ms');
                        $('#debug-cost').text('$' + (response.usage?.estimated_cost || 0).toFixed(6));
                        $result.show();
                    } else {
                        SM.Utils.showToast(response.message || slidemindAdmin.strings.testError, 'error');
                    }
                },
                error: function(xhr) {
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-visibility"></span> ' + slidemindAdmin.strings.testButton);
                    var msg = xhr.responseJSON?.message || slidemindAdmin.strings.testError;
                    SM.Utils.showToast(msg, 'error');
                }
            });
        },

        showCodeGenerator: function(configUid) {
            // Stocke l'ID pour la regénération au changement d'outil auteur
            this._codeConfigUid = configUid || this._codeConfigUid;
            if (!this._codeConfigUid) return;

            // Auto-fill authoring tool var names if not manually edited and still empty/default
            if (!this._editorVarsManuallyEdited) {
                var curInput = $('#wizard-editor-input-var').val();
                var curOutput = $('#wizard-editor-output-var').val();
                if (!curInput || curInput === 'userMessage' || !curOutput || curOutput === 'aiResponse') {
                    var title = $('#wizard-title').val();
                    var number = $('#wizard-slide-number').val();
                    var names = SM.Utils.generateEditorVarNames(title, number);
                    if (names) {
                        $('#wizard-editor-input-var').val(names.input);
                        $('#wizard-editor-output-var').val(names.output);
                    }
                }
            }

            var restUrl    = slidemindWizardData.restUrl || '';
            var siteUrl    = slidemindWizardData.siteUrl || restUrl.replace(/wp-json\/slidemind\/v2\/?$/, '');
            var prompt     = $('#wizard-prompt').val() || '';
            var useMemory  = /\{\{memory\./.test(prompt);
            var editorKey  = $('#wizard-editor-select').val() || 'storyline';
            var isWidget   = editorKey === 'widget';

            var inputVar = $('#wizard-editor-input-var').val() || 'userMessage';
            var outputVar = $('#wizard-editor-output-var').val() || 'aiResponse';
            SM.CodeGenerator.inputVar = inputVar;
            SM.CodeGenerator.outputVar = outputVar;

            var widgetMode = $('input[name="wizard_widget_mode"]:checked').val() || 'qa';
            var code = SM.CodeGenerator.buildForList({
                authoringTool: editorKey,
                configUid:  this._codeConfigUid,
                restUrl:    restUrl,
                siteUrl:    siteUrl,
                widgetMode: widgetMode,
                inputVar:   inputVar,
                outputVar:  outputVar
            });

            // Mise à jour des instructions
            var editor = SM.CodeGenerator.editors[editorKey];
            $('#wizard-editor-instructions').html(editor ? editor.instructions : '');
            $('#wizard-memory-hint').toggle(useMemory && !isWidget);

            // Beta authoring tool warning
            var isBeta = SM.CodeGenerator.betaEditors.indexOf(editorKey) !== -1;
            var $betaWarn = $('#wizard-beta-warning');
            $betaWarn.toggle(isBeta);
            if (isBeta) $betaWarn.find('span:last').html(slidemindAdmin.strings.codeBetaWarning);

            $('#wizard-integration-code').text(code);
            $('#wizard-customize-widget-btn').toggle(isWidget);

            // Handler du bouton copier
            $('#wizard-copy-integration-code').off('click').on('click', function() {
                SM.Utils.copyToClipboard(code, function(success) {
                    if (success) {
                        var $btn = $('#wizard-copy-integration-code');
                        $btn.html('<span class="dashicons dashicons-yes"></span> ' + slidemindAdmin.strings.copied);
                        setTimeout(function() {
                            $btn.html('<span class="dashicons dashicons-clipboard"></span> ' + slidemindAdmin.strings.copyCode);
                        }, 2000);
                    }
                });
            });
        },

        submit: function() {
            var self = this;

            // Re-validate title (was validated in step 1)
            if (!$('#wizard-title').val()) {
                SM.Utils.showToast(slidemindAdmin.strings.titleRequired, 'error');
                return;
            }

            var $btn = $('#wizard-submit');
            $btn.prop('disabled', true).text(slidemindAdmin.strings.creating);

            // Collect all data
            var widgetMode = $('input[name="wizard_widget_mode"]:checked').val() || 'qa';
            var slideData = {
                title: $('#wizard-title').val(),
                slide_number: $('#wizard-slide-number').val() || '',
                parent_module_id: $('#wizard-module').val(),
                model_id: $('#wizard-model').val(),
                system_prompt: $('#wizard-prompt').val(),
                response_example: $('#wizard-response-example').val() || '',
                temperature: parseFloat($('#wizard-temperature').val()),
                max_tokens: parseInt($('#wizard-max-tokens').val()),
                status: $('#wizard-status').val(),
                provider: $('#wizard-provider').val() || '',
                widget_mode: widgetMode,
                variables: []
            };

            slideData.editor_input_var = $('#wizard-editor-input-var').val() || 'userMessage';
            slideData.editor_output_var = $('#wizard-editor-output-var').val() || 'aiResponse';

            // Capture mode: no AI fields, add memory variables
            if (widgetMode === 'capture') {
                slideData.model_id = '';
                slideData.system_prompt = '';
                slideData.response_example = '';
                slideData.memory_variables = JSON.stringify(this.collectCaptureVariables());
                slideData.variables = [];
            }

            // Chat mode fields
            if (widgetMode === 'chat') {
                slideData.max_turns = parseInt($('#wizard-max-turns').val()) || 0;
                slideData.closing_message = $('#wizard-closing-message').val() || '';
                slideData.opening_message = $('#wizard-opening-message').val() || '';
                slideData.graceful_close = $('#wizard-graceful-close').is(':checked') ? '1' : '0';
                slideData.graceful_close_prompt = $('#wizard-graceful-close-prompt').val() || '';
            }

            // Q&A mode: output variables
            if (widgetMode === 'qa') {
                var outputVars = this.collectOutputVariables();
                if (outputVars.length > 0) {
                    slideData.output_variables = JSON.stringify(outputVars);
                }
            }

            // Auto-save interaction (Q&A/Chat only)
            if (widgetMode !== 'capture') {
                var autoSave = this.collectAutoSaveData();
                if (autoSave) $.extend(slideData, autoSave);

                // Capture variables from advanced options
                var advCaptureVars = this.collectCaptureVariables();
                if (advCaptureVars.length > 0) {
                    slideData.memory_variables = JSON.stringify(advCaptureVars);
                }
            }

            // Widget appearance
            slideData.widget_color = $('input[name="widget_color"]').val() || '';
            slideData.widget_ai_color = $('input[name="widget_ai_color"]').val() || '';
            slideData.widget_theme = $('input[name="widget_theme"]').val() || '';
            slideData.widget_show_header = $('input[name="widget_show_header"]').val() || '';
            slideData.widget_title = $('input[name="widget_title"]').val() || '';
            slideData.widget_ai_text_color = $('input[name="widget_ai_text_color"]').val() || '';
            slideData.widget_border_radius = $('input[name="widget_border_radius"]').val() || '';

            // Notes
            slideData.notes = $('#wizard-notes').val() || '';

            // Collect custom variables from prompt
            slideData.variables = this.getCustomVariablesFromPrompt().map(function(v) {
                return { name: v, test_value: '' };
            });

            SM.Utils.ajax('slidemind_save_slide', { slide: slideData }, function(response) {
                $btn.prop('disabled', false).html('<span class="dashicons dashicons-saved"></span> ' + slidemindWizardData.strings.createSlide);

                if (response.success) {
                    var slideId = response.data.slide_id;
                    var configUid = response.data.config_uid;
                    var title = slideData.title || slidemindWizardData.strings.slideDefault;

                    // Masque le wizard, affiche la page de succès
                    $('#sm-wizard').hide();
                    var $success = $('#wizard-success');
                    $('#wizard-success-title').text(SM.Utils.sprintf(slidemindWizardData.strings.slideReady, title));
                    $('#wizard-success-edit').attr('href', 'admin.php?page=slidemind-slide-edit&slide_id=' + slideId);
                    $('#wizard-success-sandbox').attr('href', 'admin.php?page=slidemind-sandbox&slide_id=' + slideId);
                    $('#wizard-success-sandbox').toggle(widgetMode !== 'capture');
                    $success.show();

                    // Génère le code d'intégration
                    self.showCodeGenerator(configUid);

                    // Scroll en haut
                    $('html, body').animate({ scrollTop: $success.offset().top - 40 }, 300);
                } else {
                    SM.Utils.showToast(response.data.message || slidemindAdmin.strings.creationError, 'error');
                }
            });
        }
    };

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

})(jQuery);
