;(function($) {
    'use strict';

    /**
     * Initialize AI Chatbot Widget
     */
    function initAIChatbot($scope) {
        const $container = $scope.find('.unlockafe-ai-chatbot-container');
        
        if ($container.length === 0) {
            return;
        }

        const chatbotId = $container.attr('id');
        const $messages = $container.find('.unlockafe-ai-chatbot-messages');
        const $input = $container.find('.unlockafe-ai-chatbot-input');
        const $sendButton = $container.find('.unlockafe-ai-chatbot-send-button');
        const $typing = $container.find('.unlockafe-ai-chatbot-typing');
        const $wrapper = $scope.find('.unlockafe-ai-chatbot-wrapper');
        const widgetId = $wrapper.data('chatbot-id') || '';

        let conversationHistory = [];
        let isProcessing = false;

        // Get AJAX URL and nonce
        let ajaxUrl = '';
        let nonce = '';

        // Try to get from localized script
        if (widgetId && typeof window['unlockafe_ai_chatbot_' + widgetId] !== 'undefined') {
            const localized = window['unlockafe_ai_chatbot_' + widgetId];
            ajaxUrl = localized.ajax_url || '';
            nonce = localized.nonce || '';
        }

        // Fallback to text generator settings
        if (!ajaxUrl && typeof unlockafe_text_generator !== 'undefined') {
            ajaxUrl = unlockafe_text_generator.ajax_url || '';
            nonce = unlockafe_text_generator.nonce || '';
        }

        // Fallback to global nonce
        if (!nonce && typeof unlockafe_text_generator_nonce !== 'undefined') {
            nonce = unlockafe_text_generator_nonce;
        }

        // Final fallback: construct AJAX URL
        if (!ajaxUrl) {
            const currentUrl = window.location.origin;
            ajaxUrl = currentUrl + '/wp-admin/admin-ajax.php';
        }

        // Send message function
        function sendMessage() {
            const message = $input.val().trim();
            
            if (!message || isProcessing) {
                return;
            }

            // Add user message to chat
            addMessage(message, 'user');
            $input.val('');
            
            // Add to conversation history
            conversationHistory.push({
                role: 'user',
                content: message
            });

            // Show typing indicator
            showTyping();
            isProcessing = true;
            $sendButton.prop('disabled', true);

            // Send to AI
            getAIResponse(message, conversationHistory);
        }

        // Add message to chat
        function addMessage(text, type) {
            const $message = $('<div>')
                .addClass('unlockafe-ai-chatbot-message')
                .addClass(type);

            const $content = $('<div>')
                .addClass('unlockafe-ai-chatbot-message-content')
                .html(formatMessage(text));

            $message.append($content);
            $messages.append($message);
            
            // Scroll to bottom
            scrollToBottom();
        }

        // Format message (convert markdown-like to HTML and render HTML tags)
        function formatMessage(text) {
            // Check if text contains HTML tags
            const htmlTagRegex = /<[^>]+>/g;
            const hasHtmlTags = htmlTagRegex.test(text);
            
            if (hasHtmlTags) {
                // If HTML tags are present, render them (but sanitize for security)
                // Allow common safe HTML tags
                const allowedTags = ['p', 'br', 'strong', 'b', 'em', 'i', 'u', 'code', 'pre', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'span', 'div'];
                const tempDiv = $('<div>').html(text);
                tempDiv.find('*').each(function() {
                    if ($.inArray(this.tagName.toLowerCase(), allowedTags) === -1) {
                        $(this).replaceWith($(this).html());
                    }
                });
                text = tempDiv.html();
            } else {
                // No HTML tags, escape and convert markdown
                text = $('<div>').text(text).html();
                
                // Convert line breaks
                text = text.replace(/\n/g, '<br>');
                
                // Convert **bold**
                text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
                
                // Convert *italic*
                text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
                
                // Convert code blocks
                text = text.replace(/`([^`]+)`/g, '<code>$1</code>');
            }
            
            return text;
        }

        // Show typing indicator
        function showTyping() {
            $typing.show();
            scrollToBottom();
        }

        // Hide typing indicator
        function hideTyping() {
            $typing.hide();
        }

        // Scroll to bottom
        function scrollToBottom() {
            setTimeout(function() {
                $messages.scrollTop($messages[0].scrollHeight);
            }, 100);
        }

        // Get AI response
        function getAIResponse(userMessage, history) {
            // Build conversation context
            let conversationText = '';
            if (history.length > 1) {
                // Include recent conversation history (last 5 messages)
                const recentHistory = history.slice(-5);
                conversationText = recentHistory.map(msg => {
                    return msg.role === 'user' 
                        ? 'User: ' + msg.content 
                        : 'Assistant: ' + msg.content;
                }).join('\n\n');
                conversationText += '\n\nUser: ' + userMessage;
            } else {
                conversationText = userMessage;
            }

            // Make AJAX request
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'unlockafe_generate_text',
                    prompt: conversationText,
                    nonce: nonce,
                    debug: false
                },
                timeout: 60000, // 60 seconds
                success: function(response) {
                    hideTyping();
                    isProcessing = false;
                    $sendButton.prop('disabled', false);

                    if (response.success) {
                        const aiResponse = typeof response.data === 'string' 
                            ? response.data 
                            : (response.data.content || '');
                        
                        if (aiResponse) {
                            addMessage(aiResponse, 'ai');
                            
                            // Add to conversation history
                            conversationHistory.push({
                                role: 'assistant',
                                content: aiResponse
                            });
                        } else {
                            addMessage('I apologize, but I didn\'t receive a valid response. Please try again.', 'ai');
                        }
                    } else {
                        const errorMsg = response.data || 'An error occurred. Please try again.';
                        addMessage('Error: ' + errorMsg, 'ai');
                    }
                },
                error: function(xhr, status, error) {
                    hideTyping();
                    isProcessing = false;
                    $sendButton.prop('disabled', false);

                    let errorMsg = 'Sorry, I encountered an error. Please try again.';
                    
                    if (status === 'timeout') {
                        errorMsg = 'Request timed out. Please try again.';
                    } else if (xhr.responseJSON && xhr.responseJSON.data) {
                        errorMsg = xhr.responseJSON.data;
                    }

                    addMessage('Error: ' + errorMsg, 'ai');
                }
            });
        }

        // Event handlers
        $sendButton.on('click', sendMessage);
        
        $input.on('keypress', function(e) {
            if (e.which === 13 && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // Auto-focus input
        $input.focus();
    }

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-ai-chatbot.default', function($scope) {
            initAIChatbot($scope);
        });
    });

    // Also initialize on document ready (for non-Elementor pages)
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-ai-chatbot').each(function() {
            var $scope = $(this);
            initAIChatbot($scope);
        });
    });

    // Re-initialize on Elementor preview refresh
    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope) {
            if ($scope.find('.unlockafe-ai-chatbot-container').length) {
                setTimeout(function() {
                    initAIChatbot($scope);
                }, 100);
            }
        });
    }

})(jQuery);
