document.addEventListener('DOMContentLoaded', function() {
    (function($) {

        // --- Selettori DOM e Variabili Globali ---
        var chatbox = $('#chatbox');
        var chatboxButton = $('#chatbox-button');
        var chatboxButtonImg = chatboxButton.find('img');
        var chatboxContent = $('#chatbox-content');
        var chatboxInput = $('#chatbox-input');
        var proactiveBubble = $('#chatbot-proactive-bubble');

        var conversationHistory = [];
        var currentConversationId = null;
        var userInfo = null;
        var isChatboxOpen = false;
        var isAnimating = false;

        // --- CHIAVI UNIVOCHE PER SESSIONSTORAGE ---
        const historyKey = chatbot_params.site_id + '_chatbotHistory';
        const convIdKey = chatbot_params.site_id + '_chatbotConvId';

        // --- Funzioni di Gestione della Cronologia (sessionStorage) ---
        function saveHistoryToSessionStorage() {
            try {
                sessionStorage.setItem(historyKey, JSON.stringify(conversationHistory));
            } catch (e) {
                console.warn('Chatbot: Could not save history to sessionStorage.');
            }
        }

        function loadHistoryFromSessionStorage() {
            try {
                const storedHistory = sessionStorage.getItem(historyKey);
                if (storedHistory) {
                    conversationHistory = JSON.parse(storedHistory);
                    rebuildChatFromHistory();
                }
            } catch (e) {
                console.warn('Chatbot: Could not load history from sessionStorage.');
                conversationHistory = [];
            }
        }

        function rebuildChatFromHistory() {
            chatboxContent.empty();
            conversationHistory.forEach(function(message) {
                if (message.role === 'user') {
                    appendUserMessage(message.content);
                } else if (message.role === 'assistant') {
                    appendBotMessage(message.content);
                }
            });
        }

        function getConversationId() {
            if (currentConversationId) return currentConversationId;
            try {
                currentConversationId = sessionStorage.getItem(convIdKey);
            } catch (e) {
                console.warn('Chatbot: Could not read conversation ID from sessionStorage.');
            }
            return currentConversationId;
        }

        // --- Funzioni di Interazione con la Chat ---
        function sendMessage() {
            var message = chatboxInput.val().trim();
            if (message === '') return;

            appendUserMessage(message);
            chatboxInput.val('');
            
            conversationHistory.push({ role: 'user', content: message });
            saveHistoryToSessionStorage();

            showLoadingIndicator();
            sendMessageToServer(message);
        }

        function sendMessageToServer(message) {
            var conversationId = getConversationId();
            var ajaxData = {
                action: 'newcodebyte_chatbot_send_message',
                message: message,
                conversation_id: conversationId,
                history: JSON.stringify(conversationHistory),
                newcodebyte_chatbot_message_nonce: chatbot_ajax.newcodebyte_chatbot_message_nonce
            };

            if (userInfo) {
                ajaxData.name = userInfo.name;
                ajaxData.email = userInfo.email;
                ajaxData.is_first_message = '1';
                userInfo = null;
            }

            $.ajax({
                url: chatbot_ajax.ajaxurl,
                type: 'POST',
                data: ajaxData,
                success: handleServerResponse,
                error: handleServerError
            });
        }

        function handleServerResponse(response) {
            $('.chat-message.loading').remove();

            if (response.success) {
                var botMessageRaw = response.data.message;
                
                conversationHistory.push({ role: 'assistant', content: botMessageRaw });
                saveHistoryToSessionStorage();

                appendBotMessage(botMessageRaw);

                if (response.data.conversation_id && !currentConversationId) {
                    currentConversationId = response.data.conversation_id;
                    try {
                        sessionStorage.setItem(convIdKey, currentConversationId);
                    } catch (e) {}
                }
            } else {
                appendBotMessage(response.data.message || chatbot_i18n.there_was_an_error);
            }
        }

        function sendWelcomeMessage() {
            var welcomeMsg = chatbot_i18n.welcome_message || 'Hello!';
            if (conversationHistory.length === 0) {
                conversationHistory.push({ role: 'assistant', content: welcomeMsg });
                saveHistoryToSessionStorage();
                appendBotMessage(welcomeMsg);
            }
        }

        // --- Funzioni di Visualizzazione (Rendering) ---
            function appendChatMessage(type, avatar, messageContent) {
            var avatarImg = $('<img>').attr('src', avatar).attr('alt', type);
            var messageBubble = $('<div>').addClass('chat-bubble');

            if (type === 'user') {
                messageBubble.text(messageContent);
            } else {
                if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
                    // Inserisci l'HTML generato da marked.js direttamente nel div
                    messageBubble.html(DOMPurify.sanitize(marked.parse(messageContent)));
                } else {
                    messageBubble.text(messageContent);
                }
            }
            
            var newMessage = $('<div>').addClass('chat-message ' + type).append(avatarImg).append(messageBubble);
            chatboxContent.append(newMessage);
            chatboxContent.stop().animate({ scrollTop: chatboxContent[0].scrollHeight }, 200);
        }
        function appendUserMessage(message) { appendChatMessage('user', chatbot_params.chatbot_user_avatar_url, message); }
        function appendBotMessage(message) { appendChatMessage('bot', chatbot_params.chatbot_bot_avatar_url, message); }
        
        function showLoadingIndicator() {
            var loadingImg = $('<img>').attr('src', chatbot_params.loading_gif_url).attr('alt', 'Loading...');
            var loadingMessage = $('<div>').addClass('chat-message loading').append(loadingImg);
            chatboxContent.append(loadingMessage);
            chatboxContent.scrollTop(chatboxContent[0].scrollHeight);
        }

        function handleServerError(xhr) {
            $('.chat-message.loading').remove();
            var errorMessage = chatbot_i18n.there_was_an_error;
            if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                errorMessage = xhr.responseJSON.data.message;
            }
            appendBotMessage(errorMessage);
        }
        
        function toggleChatbox() {
            if (isAnimating) return;
            isAnimating = true;

            if (proactiveBubble.hasClass('visible')) {
                 proactiveBubble.removeClass('visible').addClass('hidden');
                 try { sessionStorage.setItem('newcodebyte_proactive_bubble_closed', 'true'); } catch(e) {}
            }

            var isMobile = window.innerWidth <= 768;
            var newPosition = isChatboxOpen ? (isMobile ? '-100vh' : '-800px') : (isMobile ? '60px' : '85px');
            var newIcon = isChatboxOpen ? chatbot_params.chatbot_icon_closed_url : chatbot_params.chatbot_icon_open_url;
            
            chatbox.animate({ bottom: newPosition }, 300, function() {
                isAnimating = false;
                isChatboxOpen = !isChatboxOpen; 
            });
            
            chatboxButtonImg.attr('src', newIcon);
        
            if (!isChatboxOpen) {
                playNotificationSound();
                if (conversationHistory.length === 0) {
                    sendWelcomeMessage();
                }
            }
        }

        function playNotificationSound() {
            var audioPath = chatbot_params.notification_sound_url;
            if (audioPath) {
                try {
                    var audio = new Audio(audioPath);
                    audio.play().catch(function(error) {});
                } catch (e) {}
            }
        }

        // --- Logica di Avvio e Binding degli Eventi ---
        
        loadHistoryFromSessionStorage();
        getConversationId();

        if ($('.chatbot-shortcode-wrapper').length === 0) {
            chatboxButton.on('click', toggleChatbox);
            $('#chatbox-close').on('click', toggleChatbox);
        }

        $('#chatbox-send').on('click', sendMessage);
        chatboxInput.on('keypress', function(e) { if (e.which === 13 && !e.shiftKey) { e.preventDefault(); sendMessage(); } });

        $(document).on('chatbot:ready', function() {
            if (conversationHistory.length === 0) {
                sendWelcomeMessage();
            }
        });
        
        if ($('.chatbot-shortcode-wrapper').length === 0 && chatbot_params.enable_proactive === '1' && proactiveBubble.length > 0) {
            // (Logica per il messaggio proattivo)
        }

    })(jQuery);
});