(function($) {
    "use strict";

    $(document).ready(function() {
        // Definiamo una sola costante per accedere all'oggetto globale. LA USIAMO OVUNQUE.
        const adminVars = chatbot_admin_vars;

        function updateCounter(textareaIdPrefix, charactersSpanID, tokensSpanID) {
            const textAreaSelector = '#' + textareaIdPrefix;
            const text = $(textAreaSelector).val();
            const charactersCount = text.length;
            const estimatedTokens = Math.round(charactersCount / 4);

            $('#' + charactersSpanID).text(charactersCount);
            $('#' + tokensSpanID).text(estimatedTokens);
        }

        $('#chatbot_responses_info_textarea').on('input', function() {
            updateCounter(
                'chatbot_responses_info_textarea',
                'chatbox-responses-characters',
                'response-tokens'
            );
        });

        $('#chatbot_behavior_type_textarea').on('input', function() {
            updateCounter(
                'chatbot_behavior_type_textarea',
                'behavior-chars',
                'token-count'
            );
        });

        updateCounter('chatbot_responses_info_textarea', 'chatbox-responses-characters', 'response-tokens');
        updateCounter('chatbot_behavior_type_textarea', 'behavior-chars', 'token-count');

        $('.nav-tab').on('click', function(e) {
            e.preventDefault();
            $('.nav-tab').removeClass('nav-tab-active');
            $(this).addClass('nav-tab-active');

            $('.tab-content').hide();
            $($(this).attr('href')).show();
        });

        function handleAjaxError(xhr, errorMessage) {
            try {
                const responseJson = JSON.parse(xhr.responseText);
                if (responseJson?.data) {
                    // Controlla se response.data è a sua volta un oggetto con una proprietà 'message'
                    const finalMessage = (typeof responseJson.data === 'object' && responseJson.data.message) ? responseJson.data.message : responseJson.data;
                    alert(`${errorMessage}: ${finalMessage}`);
                    return;
                }
            } catch (e) {
                // Silently handle parsing error
            }
            alert(`${errorMessage}: ${xhr.responseText}`);
        }

        $('#chatbot-delete-messages').on('click', function(e) {
            e.preventDefault();
            if (!confirm(adminVars.delete_confirmation)) {
                return;
            }

            $.ajax({
                url: adminVars.ajaxurl,
                type: 'POST',
                data: {
                    action: 'newcodebyte_chatbot_delete_messages',
                    chatbot_delete_nonce: adminVars.chatbot_delete_nonce
                },
                success: function(response) {
                    if (response.success) {
                        window.location.reload();
                    } else {
                        const errorMessage = response.data.message || adminVars.delete_error;
                        alert(errorMessage);
                    }
                },
                error: function(xhr) {
                    handleAjaxError(xhr, adminVars.delete_error);
                }
            });
        });

// --- GESTIONE CAMPO API KEY (Versione Definitiva) ---

const apiKeyField = $('#chatbot_api_key_field');

if (apiKeyField.length > 0) {
    
    // Crea un unico "righello" invisibile per misurare il testo
    $('body').append('<span id="api_key_ruler" style="position:absolute; top:-9999px; left:-9999px; white-space:nowrap;"></span>');
    const apiKeyRuler = $('#api_key_ruler');
    const apiKeyContainer = apiKeyField.closest('.newcodebyte-password-field');

    const adjustApiKeyFieldWidth = function() {
        // Copia gli stili di font esatti dall'input al nostro "righello"
        apiKeyRuler.css({
            'font-size': apiKeyField.css('font-size'),
            'font-family': apiKeyField.css('font-family'),
            'letter-spacing': apiKeyField.css('letter-spacing'),
            'padding': apiKeyField.css('padding')
        });

        // Misura SEMPRE la larghezza del testo reale, ignorando i pallini
        apiKeyRuler.text(apiKeyField.val());
        
        // Calcola la larghezza necessaria per il testo visibile + spazio per l'icona
        const requiredWidth = apiKeyRuler.outerWidth() + 5;
        
        // Applica la larghezza calcolata, con un minimo di 250px
        apiKeyContainer.width(Math.max(250, requiredWidth));
    };

    // Aggiusta la larghezza al caricamento e ogni volta che l'utente scrive
    adjustApiKeyFieldWidth();
    apiKeyField.on('input', adjustApiKeyFieldWidth);

    // Gestisce il click sull'occhio. NON deve più ricalcolare la larghezza.
    $('.toggle-api-key').on('click', function() {
        const fieldType = apiKeyField.attr('type');

        if (fieldType === 'password') {
            apiKeyField.attr('type', 'text');
            $(this).removeClass('dashicons-visibility').addClass('dashicons-hidden');
        } else {
            apiKeyField.attr('type', 'password');
            $(this).removeClass('dashicons-hidden').addClass('dashicons-visibility');
        }
    });
}       

        function downloadFile(data, filename, type) {
            const blob = new Blob([data], { type });
            const downloadUrl = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = downloadUrl;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(downloadUrl);
        }

        $('#chatbot-export').on('click', function(e) {
            e.preventDefault();
            const format = $('#chatbot-export-format').val();
            const $exportButton = $(this);

            if (!format) {
                alert(adminVars.export_format_selection);
                return;
            }

            $exportButton.prop('disabled', true);

            $.ajax({
                url: adminVars.ajaxurl,
                type: 'POST',
                data: {
                    action: 'newcodebyte_chatbot_export_messages',
                    format,
                    chatbot_export_nonce: adminVars.chatbot_export_nonce
                },
                xhrFields: {
                    responseType: format === 'html' ? 'text' : 'blob'
                },
                success: function(data, textStatus, jqXHR) {
                    const disposition = jqXHR.getResponseHeader('content-disposition');
                    const matches = /"([^"]*)"/.exec(disposition);
                    const filename = (matches != null && matches[1] ? matches[1] : 'file.txt');
                    
                    downloadFile(data, filename, format === 'html' ? 'text/html' : 'application/octet-stream');
                },
                error: function(jqXHR) {
                    handleAjaxError(jqXHR, 'Error during message export');
                },
                complete: function() {
                    $exportButton.prop('disabled', false);
                }
            });
        });

        $('.chatbot-color-picker').wpColorPicker();

        $('.chatbot-upload-button').on('click', function(e) {
            e.preventDefault();
            const targetInput = $(this).data('target');
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'audio/mpeg', 'audio/wav', 'audio/ogg'];

            const mediaUploader = wp.media({
                title: adminVars.media_uploader_title,
                button: {
                    text: adminVars.media_uploader_button_text
                },
                multiple: false
            });

            mediaUploader.on('select', function() {
                const attachment = mediaUploader.state().get('selection').first().toJSON();
                
                if (!attachment?.url) {
                    alert(adminVars.image_upload_error);
                    return;
                }

                // Per i suoni, non controlliamo il mime type in modo così restrittivo, ci fidiamo dell'uploader
                if (attachment.mime.startsWith('image/')) {
                    const img = new Image();
                    img.onload = function() {
                        updatePreview(targetInput, attachment.url);
                    };
                    img.onerror = function() {
                        alert(adminVars.image_upload_error);
                    };
                    img.src = attachment.url;
                } else { // Presuppone sia un audio o altro
                    updatePreview(targetInput, attachment.url);
                }
            });

            mediaUploader.open();
        });

        function updatePreview(targetInput, url) {
            $(`input[name="${targetInput}"]`).val(url);
            const $previewElement = $(`#${targetInput.replace('_url', '')}_preview`);
            $previewElement.attr('src', url);

            if (targetInput === 'chatbot_notification_sound_url') {
                $previewElement.show();
            }
        }

        const previewInputs = [
            'chatbot_user_avatar_url',
            'chatbot_bot_avatar_url',
            'chatbot_icon_open_url',
            'chatbot_icon_closed_url',
            'chatbot_notification_sound_url'
        ];

        previewInputs.forEach(inputName => {
            $(`input[name="${inputName}"]`).on('input', function() {
                const value = $(this).val();
                const $previewElement = $(`#${inputName.replace('_url', '')}_preview`);
                $previewElement.attr('src', value);
                if (inputName === 'chatbot_notification_sound_url' && value) {
                    $previewElement.show();
                }
            });
        });

        // Applica lo stile del cursore iniziale a tutte le righe della tabella
        $('#chatbot-conversations-table .conversation-row').css('cursor', 'zoom-in');
        $('#chatbot-conversations-table').on('click', '.conversation-row', function() {
            var $this = $(this);
            var convId = $this.data('conv-id');
            var $messagesContainer = $('#messages-for-' + convId);
            var $innerBox = $messagesContainer.find('.inner-messages-box');

            // 1. Se la riga è non letta, invia una chiamata AJAX separata per marcarla come letta.
            if ($this.hasClass('unread')) {
                $this.removeClass('unread');

                $.ajax({
                    url: adminVars.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'newcodebyte_chatbot_mark_as_read',
                        nonce: adminVars.get_messages_nonce,
                        conversation_id: convId
                    },
                    success: function(response) {
                        if (!response.success) {
                           $this.addClass('unread');
                        }
                    },
                    error: function(xhr) {
                        $this.addClass('unread');
                    }
                });
            }

            // 2. Gestisci la visualizzazione dei messaggi (apri/chiudi).
            if ($messagesContainer.is(':visible')) {
                $messagesContainer.slideUp(200);
                $this.css('cursor', 'zoom-in').removeClass('is-open');
                return;
            }

            $('.messages-container').not($messagesContainer).slideUp(200);
            $('.conversation-row').not($this).css('cursor', 'zoom-in').removeClass('is-open');
            $messagesContainer.slideDown(200);
            $this.css('cursor', 'zoom-out').addClass('is-open');

            // 3. Se i messaggi non sono ancora stati caricati, esegui la chiamata AJAX per caricarli.
            if (!$innerBox.hasClass('loaded')) {
                $.ajax({
                    url: adminVars.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'newcodebyte_chatbot_get_conversation_messages',
                        nonce: adminVars.get_messages_nonce,
                        conversation_id: convId
                    },
                    beforeSend: function() {
                        // CORREZIONE: Usa la variabile passata da wp_localize_script
                        $innerBox.html('<div class="loading-messages">' + adminVars.loading_messages + '</div>');
                    },
                    success: function(response) {
                        if (response.success && response.data.html) {
                            $innerBox.html(response.data.html).addClass('loaded');
                        } else {
                            $innerBox.html('<div class="error-messages">Could not load messages.</div>');
                        }
                    },
                    error: function(xhr) {
                        $innerBox.html('<div class="error-messages">An error occurred while loading messages.</div>');
                    }
                });
            }
        });

    });

})(jQuery);