/**
 * Comparison Module - SlideMind Pro
 *
 * Comparaison multi-modeles dans une modale plein ecran.
 * Envoie le meme prompt a N modeles en parallele via /sandbox/test.
 *
 * @package SlideMind
 * @since 2.1.0
 */

(function($) {
    'use strict';

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

    SM.Comparison = {

        MAX_MODELS: 3,
        modelSlots: [],
        results: [],
        isRunning: false,

        /**
         * Initialise le module
         */
        init: function() {
            this.bindEvents();
        },

        /**
         * Bind les evenements
         */
        bindEvents: function() {
            var self = this;

            // Bouton header "Comparer les modeles"
            $(document).on('click', '#sm-comparison-btn', function() {
                self.openFromSandbox();
            });

            // Lien dans le debug panel
            $(document).on('click', '.sm-comparison-debug-link', function(e) {
                e.preventDefault();
                self.openFromSandbox();
            });

            // Fermer la modale
            $(document).on('click', '#sm-comparison-modal .sm-modal-close', function(e) {
                e.preventDefault();
                self.close();
            });

            // Click sur overlay
            $(document).on('click', '#sm-comparison-modal', function(e) {
                if ($(e.target).is('#sm-comparison-modal')) {
                    self.close();
                }
            });

            // Escape
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape' && $('#sm-comparison-modal').hasClass('active')) {
                    self.close();
                }
            });

            // Ajouter un slot modele
            $(document).on('click', '#sm-comparison-add-model', function() {
                self.addModelSlot();
            });

            // Supprimer un slot modele
            $(document).on('click', '.sm-comparison-slot-remove', function() {
                self.removeModelSlot($(this).closest('.sm-comparison-panel'));
            });

            // Lancer la comparaison
            $(document).on('click', '#sm-comparison-run', function() {
                self.runComparison();
            });

            // Exporter JSON
            $(document).on('click', '#sm-comparison-export', function() {
                self.exportComparison();
            });
        },

        /**
         * Ouvre la modale depuis le sandbox
         */
        openFromSandbox: function() {
            if (typeof SM.Sandbox === 'undefined' || typeof SM.Sandbox.getComparisonConfig !== 'function') {
                return;
            }

            var config = SM.Sandbox.getComparisonConfig();
            this.open(config);
        },

        /**
         * Ouvre la modale de comparaison
         */
        open: function(config) {
            this.config = config || {};
            this.results = [];
            this.modelSlots = [];
            this.isRunning = false;

            // Build modal if needed
            this.ensureModal();

            // Reset UI
            this.resetUI();

            // Pre-fill from config
            this.prefill(config);

            // Show modal
            $('#sm-comparison-modal').addClass('active');
            $('body').css('overflow', 'hidden');
        },

        /**
         * Ferme la modale
         */
        close: function() {
            if (this.isRunning) {
                if (!confirm(slidemindAdmin.strings.comparisonAbortConfirm)) {
                    return;
                }
            }
            $('#sm-comparison-modal').removeClass('active');
            $('body').css('overflow', '');
            this.isRunning = false;
        },

        /**
         * Construit la modale si elle n'existe pas
         */
        ensureModal: function() {
            if ($('#sm-comparison-modal').length) return;

            var s = slidemindAdmin.strings;
            var html = '<div id="sm-comparison-modal" class="sm-modal-overlay" data-custom-close="true">' +
                '<div class="sm-modal sm-comparison-modal">' +
                '<div class="sm-modal-header">' +
                '<div class="sm-comparison-header-left">' +
                '<h3 class="sm-modal-title">' + s.comparisonTitle + '</h3>' +
                '<span class="sm-badge sm-badge-pro">Pro</span>' +
                '</div>' +
                '<button type="button" class="sm-modal-close">&times;</button>' +
                '</div>' +
                '<div class="sm-modal-body">' +

                // Config bar
                '<div class="sm-comparison-config-bar">' +
                '<div class="sm-comparison-config-info" id="sm-comparison-config-info"></div>' +
                '<div class="sm-comparison-message-wrap">' +
                '<label class="sm-form-label">' + s.comparisonMessage + '</label>' +
                '<div style="display:flex;gap:8px;">' +
                '<input type="text" id="sm-comparison-message" class="sm-form-input" style="flex:1;" placeholder="' + s.comparisonMessagePlaceholder + '">' +
                '</div>' +
                '</div>' +
                '</div>' +

                // Panels container
                '<div class="sm-comparison-panels" id="sm-comparison-panels"></div>' +

                // Summary table
                '<div class="sm-comparison-summary" id="sm-comparison-summary" style="display:none;"></div>' +

                // Footer
                '<div class="sm-comparison-footer">' +
                '<button type="button" id="sm-comparison-run" class="sm-btn sm-btn-primary">' +
                '<span class="dashicons dashicons-controls-play"></span> ' + s.comparisonRun +
                '</button>' +
                '<button type="button" id="sm-comparison-export" class="sm-btn sm-btn-secondary" style="display:none;">' +
                '<span class="dashicons dashicons-download"></span> ' + s.comparisonExport +
                '</button>' +
                '</div>' +

                '</div>' +
                '</div>' +
                '</div>';

            $('body').append(html);
        },

        /**
         * Reset l'UI de la modale
         */
        resetUI: function() {
            $('#sm-comparison-panels').empty();
            $('#sm-comparison-summary').hide().empty();
            $('#sm-comparison-export').hide();
            $('#sm-comparison-run').prop('disabled', false)
                .html('<span class="dashicons dashicons-controls-play"></span> ' + slidemindAdmin.strings.comparisonRun);
            this.modelSlots = [];
        },

        /**
         * Pre-remplit depuis la config du sandbox
         */
        prefill: function(config) {
            if (!config) return;

            var s = slidemindAdmin.strings;

            // Config info bar
            var infoHtml = '';
            if (config.prompt) {
                var promptShort = config.prompt.length > 100 ? config.prompt.substring(0, 100) + '...' : config.prompt;
                infoHtml += '<div class="sm-comparison-config-detail">' +
                    '<strong>' + s.comparisonPromptLabel + '</strong> ' +
                    '<span class="sm-comparison-prompt-preview">' + this.escapeHtml(promptShort) + '</span>' +
                    '</div>';
            }
            if (config.temperature !== undefined) {
                infoHtml += '<span class="sm-prompt-badge"><span class="dashicons dashicons-controls-volumeon"></span> Temp: ' + config.temperature + '</span> ';
            }
            if (config.max_tokens) {
                infoHtml += '<span class="sm-prompt-badge"><span class="dashicons dashicons-editor-textcolor"></span> ' + config.max_tokens + ' tokens</span>';
            }
            $('#sm-comparison-config-info').html(infoHtml);

            // Pre-fill message
            if (config.lastMessage) {
                $('#sm-comparison-message').val(config.lastMessage);
            }

            // Add Model A (pre-selected from sandbox)
            this.addModelSlot(config.model, true);

            // Add empty Model B slot
            this.addModelSlot();
        },

        /**
         * Ajoute un slot de modele
         */
        addModelSlot: function(preselectedModel, isPrimary) {
            if (this.modelSlots.length >= this.MAX_MODELS) return;

            var index = this.modelSlots.length;
            var s = slidemindAdmin.strings;
            var letter = String.fromCharCode(65 + index); // A, B, C

            var models = (typeof slidemindComparison !== 'undefined' && slidemindComparison.models) ? slidemindComparison.models : {};
            var selectHtml = '<select class="sm-form-select sm-comparison-model-select" data-index="' + index + '">';
            selectHtml += '<option value="">' + s.comparisonSelectModel + '</option>';

            for (var group in models) {
                if (models.hasOwnProperty(group)) {
                    selectHtml += '<optgroup label="' + this.escapeHtml(group) + '">';
                    for (var j = 0; j < models[group].length; j++) {
                        var m = models[group][j];
                        var sel = (preselectedModel && m.id === preselectedModel) ? ' selected' : '';
                        selectHtml += '<option value="' + this.escapeAttr(m.id) + '"' + sel + '>' + this.escapeHtml(m.name) + '</option>';
                    }
                    selectHtml += '</optgroup>';
                }
            }
            selectHtml += '</select>';

            var removeBtn = !isPrimary ? '<button type="button" class="sm-btn sm-btn-sm sm-btn-secondary sm-comparison-slot-remove" title="' + s.buttonDelete + '"><span class="dashicons dashicons-no-alt"></span></button>' : '';

            var panelHtml = '<div class="sm-comparison-panel" data-index="' + index + '">' +
                '<div class="sm-comparison-panel-header">' +
                '<span class="sm-comparison-panel-label">' + s.comparisonModel + ' ' + letter + '</span>' +
                selectHtml +
                removeBtn +
                '</div>' +
                '<div class="sm-comparison-panel-body" id="sm-comparison-body-' + index + '">' +
                '<div class="sm-comparison-panel-placeholder">' + s.comparisonWaiting + '</div>' +
                '</div>' +
                '<div class="sm-comparison-panel-metrics" id="sm-comparison-metrics-' + index + '"></div>' +
                '</div>';

            // Insert before the add button (if exists) or append
            var $addPanel = $('#sm-comparison-add-panel');
            if ($addPanel.length) {
                $addPanel.before(panelHtml);
            } else {
                $('#sm-comparison-panels').append(panelHtml);
            }

            this.modelSlots.push({ index: index, model: preselectedModel || null });

            // Add the "+ Ajouter" panel if we haven't reached max
            this.updateAddButton();
        },

        /**
         * Supprime un slot de modele
         */
        removeModelSlot: function($panel) {
            var index = parseInt($panel.data('index'), 10);

            // Remove from DOM
            $panel.remove();

            // Remove from slots
            this.modelSlots = this.modelSlots.filter(function(slot) {
                return slot.index !== index;
            });

            // Re-label panels
            this.relabelPanels();
            this.updateAddButton();
        },

        /**
         * Re-labellise les panneaux A, B, C
         */
        relabelPanels: function() {
            var s = slidemindAdmin.strings;
            $('#sm-comparison-panels .sm-comparison-panel').each(function(i) {
                var letter = String.fromCharCode(65 + i);
                $(this).find('.sm-comparison-panel-label').text(s.comparisonModel + ' ' + letter);
            });
        },

        /**
         * Met a jour le bouton d'ajout
         */
        updateAddButton: function() {
            var s = slidemindAdmin.strings;
            $('#sm-comparison-add-panel').remove();

            if (this.modelSlots.length < this.MAX_MODELS) {
                var addHtml = '<div class="sm-comparison-panel sm-comparison-add-panel" id="sm-comparison-add-panel">' +
                    '<button type="button" id="sm-comparison-add-model" class="sm-comparison-add-btn">' +
                    '<span class="dashicons dashicons-plus-alt2"></span>' +
                    '<span>' + s.comparisonAddModel + '</span>' +
                    '</button>' +
                    '</div>';
                $('#sm-comparison-panels').append(addHtml);
            }
        },

        /**
         * Lance la comparaison
         */
        runComparison: function() {
            var self = this;
            var s = slidemindAdmin.strings;

            var message = $('#sm-comparison-message').val().trim();
            if (!message) {
                SM.Utils.showToast(s.comparisonEnterMessage, 'error');
                return;
            }

            // Collect selected models
            var models = [];
            $('#sm-comparison-panels .sm-comparison-model-select').each(function() {
                var val = $(this).val();
                if (val) {
                    models.push({
                        model: val,
                        index: parseInt($(this).data('index'), 10)
                    });
                }
            });

            if (models.length < 2) {
                SM.Utils.showToast(s.comparisonMinModels, 'error');
                return;
            }

            this.isRunning = true;
            this.results = [];

            // Update UI
            $('#sm-comparison-run').prop('disabled', true)
                .html('<span class="dashicons dashicons-update sm-spin"></span> ' + s.comparisonRunning);
            $('#sm-comparison-summary').hide().empty();
            $('#sm-comparison-export').hide();

            // Clear panel bodies
            models.forEach(function(m) {
                $('#sm-comparison-body-' + m.index).html(
                    '<div class="sm-comparison-panel-loading">' +
                    '<div class="sm-sandbox-typing"><span></span><span></span><span></span></div>' +
                    '</div>'
                );
                $('#sm-comparison-metrics-' + m.index).empty();
            });

            // Build base request data
            var config = this.config || {};
            var baseData = {
                system_prompt: config.prompt || '',
                temperature: config.temperature !== undefined ? config.temperature : 0.7,
                max_tokens: config.max_tokens || 1024,
                messages: [{ role: 'user', content: message }],
                variables: config.variables || {},
                output_variables: config.output_variables || [],
                response_example: config.response_example || ''
            };

            // Fire N parallel requests
            var completed = 0;
            var total = models.length;

            models.forEach(function(m) {
                var requestData = $.extend(true, {}, baseData, { model: m.model });
                var startTime = Date.now();

                $.ajax({
                    url: slidemindAdmin.restUrl + 'sandbox/test',
                    method: 'POST',
                    contentType: 'application/json',
                    headers: { 'X-WP-Nonce': slidemindAdmin.restNonce },
                    data: JSON.stringify(requestData),
                    success: function(response) {
                        var elapsed = Date.now() - startTime;
                        self.onModelResponse(m.index, m.model, response, elapsed);
                    },
                    error: function(xhr) {
                        var elapsed = Date.now() - startTime;
                        var errorMsg = s.connectionError;
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMsg = xhr.responseJSON.message;
                        }
                        self.onModelError(m.index, m.model, errorMsg, elapsed);
                    },
                    complete: function() {
                        completed++;
                        if (completed === total) {
                            self.onAllComplete();
                        }
                    }
                });
            });
        },

        /**
         * Callback: reponse d'un modele
         */
        onModelResponse: function(index, modelId, response, elapsed) {
            var s = slidemindAdmin.strings;

            if (response.success) {
                var content = response.message ? response.message.content : '';
                var usage = response.usage || {};
                var meta = response.meta || {};

                this.results.push({
                    index: index,
                    model: modelId,
                    success: true,
                    content: content,
                    tokens: {
                        input: usage.prompt_tokens || 0,
                        output: usage.completion_tokens || 0,
                        total: usage.total_tokens || 0
                    },
                    cost: usage.estimated_cost || 0,
                    time: meta.response_time || elapsed
                });

                // Render response
                $('#sm-comparison-body-' + index).html(
                    '<div class="sm-comparison-response">' + this.escapeHtml(content) + '</div>'
                );

                // Render metrics
                var modelShort = modelId.indexOf('/') !== -1 ? modelId.split('/').pop() : modelId;
                var metricsHtml = '<div class="sm-comparison-metric"><span>' + s.comparisonTokens + '</span><strong>' + (usage.total_tokens || 0) + '</strong></div>' +
                    '<div class="sm-comparison-metric"><span>' + s.debugEstimatedCost + '</span><strong>$' + this.formatCost(usage.estimated_cost || 0) + '</strong></div>' +
                    '<div class="sm-comparison-metric"><span>' + s.debugResponseTime + '</span><strong>' + (meta.response_time || elapsed) + ' ms</strong></div>';
                $('#sm-comparison-metrics-' + index).html(metricsHtml);

            } else {
                this.results.push({
                    index: index,
                    model: modelId,
                    success: false,
                    error: response.error || s.unknownError,
                    time: elapsed
                });

                $('#sm-comparison-body-' + index).html(
                    '<div class="sm-comparison-error">' +
                    '<span class="dashicons dashicons-warning"></span> ' +
                    this.escapeHtml(response.error || s.unknownError) +
                    '</div>'
                );
                $('#sm-comparison-metrics-' + index).empty();
            }
        },

        /**
         * Callback: erreur d'un modele
         */
        onModelError: function(index, modelId, errorMsg, elapsed) {
            this.results.push({
                index: index,
                model: modelId,
                success: false,
                error: errorMsg,
                time: elapsed
            });

            $('#sm-comparison-body-' + index).html(
                '<div class="sm-comparison-error">' +
                '<span class="dashicons dashicons-warning"></span> ' +
                this.escapeHtml(errorMsg) +
                '</div>'
            );
            $('#sm-comparison-metrics-' + index).empty();
        },

        /**
         * Callback: toutes les requetes terminees
         */
        onAllComplete: function() {
            var s = slidemindAdmin.strings;
            this.isRunning = false;

            // Restore button
            $('#sm-comparison-run').prop('disabled', false)
                .html('<span class="dashicons dashicons-controls-play"></span> ' + s.comparisonRun);

            // Render summary + badges
            this.renderMetricsSummary();
            this.highlightWinners();

            // Show export button
            if (this.results.some(function(r) { return r.success; })) {
                $('#sm-comparison-export').show();
            }
        },

        /**
         * Affiche le tableau comparatif
         */
        renderMetricsSummary: function() {
            var s = slidemindAdmin.strings;
            var successResults = this.results.filter(function(r) { return r.success; });

            if (successResults.length < 2) {
                $('#sm-comparison-summary').hide();
                return;
            }

            var html = '<h4>' + s.comparisonSummary + '</h4>';
            html += '<table class="sm-comparison-summary-table">';

            // Header
            html += '<thead><tr><th></th>';
            for (var i = 0; i < successResults.length; i++) {
                var modelShort = successResults[i].model.indexOf('/') !== -1
                    ? successResults[i].model.split('/').pop()
                    : successResults[i].model;
                html += '<th>' + this.escapeHtml(modelShort) + '</th>';
            }
            html += '</tr></thead><tbody>';

            // Tokens
            html += '<tr><td>' + s.comparisonTokens + '</td>';
            for (var i = 0; i < successResults.length; i++) {
                html += '<td>' + successResults[i].tokens.total + '</td>';
            }
            html += '</tr>';

            // Cost
            html += '<tr><td>' + s.debugEstimatedCost + '</td>';
            for (var i = 0; i < successResults.length; i++) {
                html += '<td>$' + this.formatCost(successResults[i].cost) + '</td>';
            }
            html += '</tr>';

            // Time
            html += '<tr><td>' + s.debugResponseTime + '</td>';
            for (var i = 0; i < successResults.length; i++) {
                html += '<td>' + successResults[i].time + ' ms</td>';
            }
            html += '</tr>';

            html += '</tbody></table>';

            $('#sm-comparison-summary').html(html).show();
        },

        /**
         * Ajoute les badges "Plus rapide" / "Moins cher"
         */
        highlightWinners: function() {
            var s = slidemindAdmin.strings;
            var successResults = this.results.filter(function(r) { return r.success; });

            if (successResults.length < 2) return;

            // Find fastest
            var fastest = successResults.reduce(function(a, b) {
                return a.time < b.time ? a : b;
            });

            // Find cheapest
            var cheapest = successResults.reduce(function(a, b) {
                return a.cost < b.cost ? a : b;
            });

            // Add badges
            if (fastest) {
                var $fastMetrics = $('#sm-comparison-metrics-' + fastest.index);
                $fastMetrics.find('.sm-comparison-metric').last()
                    .append(' <span class="sm-comparison-winner">' + s.comparisonFastest + '</span>');
            }

            if (cheapest && cheapest.index !== fastest.index) {
                var $cheapMetrics = $('#sm-comparison-metrics-' + cheapest.index);
                $cheapMetrics.find('.sm-comparison-metric').eq(1)
                    .append(' <span class="sm-comparison-winner">' + s.comparisonCheapest + '</span>');
            } else if (cheapest && cheapest.index === fastest.index) {
                // Same model is both fastest and cheapest
                var $metrics = $('#sm-comparison-metrics-' + cheapest.index);
                $metrics.find('.sm-comparison-metric').eq(1)
                    .append(' <span class="sm-comparison-winner">' + s.comparisonCheapest + '</span>');
            }
        },

        /**
         * Exporte la comparaison en JSON
         */
        exportComparison: function() {
            var config = this.config || {};
            var exportData = {
                exported_at: new Date().toISOString(),
                config: {
                    system_prompt: config.prompt || '',
                    temperature: config.temperature,
                    max_tokens: config.max_tokens,
                    variables: config.variables || {}
                },
                message: $('#sm-comparison-message').val(),
                results: this.results.map(function(r) {
                    return {
                        model: r.model,
                        success: r.success,
                        content: r.content || null,
                        error: r.error || null,
                        tokens: r.tokens || null,
                        cost: r.cost || null,
                        time_ms: r.time || null
                    };
                })
            };

            var json = JSON.stringify(exportData, null, 2);
            var filename = 'slidemind-comparison-' + new Date().toISOString().slice(0, 10) + '.json';

            var blob = new Blob([json], { type: 'application/json' });
            var url = URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        },

        /**
         * Formate le cout
         */
        formatCost: function(cost) {
            return parseFloat(cost).toFixed(6);
        },

        /**
         * Escape HTML
         */
        escapeHtml: function(text) {
            if (!text) return '';
            return $('<div>').text(text).html().replace(/\n/g, '<br>');
        },

        /**
         * Escape attribute
         */
        escapeAttr: function(text) {
            if (!text) return '';
            return String(text).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        if ($('#sm-sandbox-messages').length && slidemindAdmin.proFeatures && slidemindAdmin.proFeatures.comparison) {
            SM.Comparison.init();
        }
    });

})(jQuery);
