// Enhanced forum-bot.js with Ollama Integration (replacing Python servers)
(function() {
    // Make ForumBot available globally
    window.ForumBot = {
        // Configuration
        serverConfig: {
            // Ollama configuration
            ollama: {
                baseUrl: 'http://secupgrade.com:11434', // Keep for fallback direct connection
                model: 'deepseek-v3.1:671b-cloud',
                endpoint: '/api/generate', // or '/api/chat' for native
                status: 'unknown',
                maxTokens: 128000,
                temperature: 0.7,
                useProxy: true // Always use PHP proxy for all requests
            },
            timeout: 30000,
            // Fallback responses when Ollama is offline
            fallbackMode: {
                enabled: true,
                responses: {
                    code: [
                        "I'm sorry, the AI assistant is currently offline. Please make sure Ollama is running with the deepseek-v3.1:671b-cloud model.",
                        "It looks like I can't connect to Ollama right now. Please check that it's running and try again.",
                        "Code assistant requires Ollama to be running. Please start Ollama and pull the deepseek-v3.1:671b-cloud model."
                    ],
                    chat: [
                        "I'm currently offline and can't process your message. Please ensure Ollama is running.",
                        "Sorry, I'm unable to connect to the AI backend. Please check Ollama status.",
                        "Chat service requires Ollama. Please start it with: ollama serve"
                    ],
                    auto: [
                        "I apologize, but the AI assistant is currently offline. Please start Ollama and try again.",
                        "Unable to connect to Ollama. Make sure it's running with: ollama serve",
                        "Service temporarily unavailable. Please check Ollama installation and model availability."
                    ]
                }
            }
        },
        
        // Chat history storage for each bot instance
        chatHistories: new Map(),
        
        // Initialize all bot instances on the page
        init: function() {
            console.log('Auto-initializing Forum Bot with Ollama');
            
            // Find all bot containers
            const botContainers = document.querySelectorAll('.forum-bot-container');
            console.log('Found', botContainers.length, 'bot containers');
            
            // Check Ollama status first
            this.checkOllamaStatus()
                .then(() => {
                    console.log('Ollama status checked');
                    // Initialize each bot after checking status
                    botContainers.forEach((container) => {
                        this.initializeBot(container);
                    });
                    console.log('All bots initialized');
                })
                .catch((error) => {
                    console.warn('Ollama status check failed:', error);
                    console.log('Initializing bots in offline mode');
                    
                    // Initialize bots anyway, status will show as offline
                    botContainers.forEach((container) => {
                        this.initializeBot(container);
                    });
                });
            
            console.log('Forum Bot initialization complete');
            
            // Set up periodic status checks
            setInterval(() => this.checkOllamaStatus(), 60000); // Check every minute
        },
        
        // Check if Ollama is running and model is available
        checkOllamaStatus: function() {
            return new Promise((resolve, reject) => {
                this.testOllamaConnection()
                    .then((isOnline) => {
                        this.serverConfig.ollama.status = isOnline ? 'online' : 'offline';
                        
                        // Update all bot status indicators
                        document.querySelectorAll('.forum-bot-container').forEach((container) => {
                            this.updateBotStatusIndicator(container);
                        });
                        
                        if (isOnline) {
                            resolve(true);
                        } else {
                            reject(new Error('Ollama is offline'));
                        }
                    })
                    .catch((error) => {
                        console.error('Ollama connection test failed:', error);
                        this.serverConfig.ollama.status = 'offline';
                        
                        // Update all bot status indicators
                        document.querySelectorAll('.forum-bot-container').forEach((container) => {
                            this.updateBotStatusIndicator(container);
                        });
                        
                        reject(error);
                    });
            });
        },
        
        // Test Ollama connection
        testOllamaConnection: async function() {
            try {
                console.log('Testing Ollama connection...');

                // First, try direct connection to Ollama
                try {
                    // First, test if Ollama is running by checking /api/tags
                    const tagsResponse = await fetch(this.serverConfig.ollama.baseUrl + '/api/tags', {
                        method: 'GET',
                        signal: AbortSignal.timeout(5000)
                    });

                    if (!tagsResponse.ok) {
                        throw new Error(`Ollama server not responding (${tagsResponse.status})`);
                    }

                    const tagsData = await tagsResponse.json();
                    console.log('Available models:', tagsData.models?.map(m => m.name) || []);

                    // Check if our model exists
                    const modelExists = tagsData.models?.some(model =>
                        model.name.includes(this.serverConfig.ollama.model) ||
                        model.name.includes(this.serverConfig.ollama.model.replace(':3.8b', ''))
                    );

                    if (!modelExists) {
                        const availableModels = tagsData.models?.map(m => m.name).join(', ') || 'none';
                        console.warn(`Model "${this.serverConfig.ollama.model}" not found. Available: ${availableModels}`);
                        throw new Error(`Model "${this.serverConfig.ollama.model}" not available. Run: ollama pull ${this.serverConfig.ollama.model}`);
                    }

                    // Test the actual chat endpoint with a simple request
                    const endpoint = this.serverConfig.ollama.endpoint;
                    const fullUrl = this.serverConfig.ollama.baseUrl + endpoint;

                    const testPayload = endpoint === '/api/generate' ? {
                        model: this.serverConfig.ollama.model,
                        messages: [{ role: 'user', content: 'Hi' }],
                        max_tokens: 1,
                        stream: false
                    } : {
                        model: this.serverConfig.ollama.model,
                        messages: [{ role: 'user', content: 'Hi' }],
                        stream: false
                    };

                    const testResponse = await fetch(fullUrl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(testPayload),
                        signal: AbortSignal.timeout(10000)
                    });

                    if (!testResponse.ok) {
                        if (testResponse.status === 403) {
                            throw new Error('CORS error. Falling back to PHP proxy...');
                        }
                        throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`);
                    }

                    console.log('Ollama connection test successful');
                    return true;
                } catch (directError) {
                    console.warn('Direct Ollama connection test failed, falling back to PHP proxy:', directError.message);

                    // Fallback to PHP proxy for connection test
                    try {
                        // Test the PHP proxy by making a simple call
                        const testPayload = {
                            messages: [{ role: 'user', content: 'test' }],
                            userMessage: 'test',
                            model: this.serverConfig.ollama.model
                        };

                        const phpResponse = await fetch('bot-handler.php?action=call_ollama', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(testPayload),
                            signal: AbortSignal.timeout(10000)
                        });

                        if (!phpResponse.ok) {
                            throw new Error(`PHP proxy test failed: HTTP ${phpResponse.status}`);
                        }

                        const phpData = await phpResponse.json();

                        if (!phpData.success && !phpData.botResponse) {
                            throw new Error(phpData.error || 'PHP proxy test failed');
                        }

                        console.log('Ollama connection test successful via PHP proxy');
                        return true;
                    } catch (proxyError) {
                        console.error('Both direct and proxy connection tests failed:', proxyError);
                        return false;
                    }
                }
            } catch (error) {
                console.error('Ollama connection test failed:', error);
                return false;
            }
        },
        
        // Initialize a single bot container
        initializeBot: function(container) {
            try {
                const botId = container.dataset.id;
                const botName = container.dataset.name;
                const botType = container.dataset.type || 'auto';
                
                // Skip if already initialized
                if (container.dataset.initialized === 'true') {
                    return;
                }
                
                // Mark as initialized
                container.dataset.initialized = 'true';
                
                // Initialize chat history for this bot
                if (!this.chatHistories.has(botId)) {
                    this.chatHistories.set(botId, []);
                }
                
                // Get elements
                const messagesContainer = document.getElementById(`${botId}-messages`);
                const inputField = document.getElementById(`${botId}-input`);
                const sendButton = container.querySelector('.bot-send-btn');
                const statusElement = document.getElementById(`${botId}-connection`);
                
                if (!messagesContainer || !inputField || !sendButton) {
                    console.error(`Missing required elements for bot ${botId}`);
                    return;
                }
                
                // Set initial status
                if (statusElement) {
                    statusElement.innerHTML = '<i class="fas fa-sync fa-spin"></i> Checking Ollama...';
                }
                
                // Update status indicator
                this.updateBotStatusIndicator(container);
                
                // Add event listener for send button
                sendButton.addEventListener('click', () => {
                    if (inputField.value.trim()) {
                        this.sendMessage(botId, inputField.value);
                        inputField.value = '';
                    }
                });
                
                // Add event listener for enter key
                inputField.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        if (inputField.value.trim()) {
                            this.sendMessage(botId, inputField.value);
                            inputField.value = '';
                        }
                    }
                });
                
                // Add event listeners for bot type toggle
                container.querySelectorAll('input[name^="bot-type-"]').forEach((radio) => {
                    radio.addEventListener('change', (e) => {
                        if (e.target.checked) {
                            container.dataset.type = e.target.value;
                            this.updateBotStatusIndicator(container);
                            
                            // Add a system message about bot type change
                            let modeText = e.target.value === 'auto' ? 'automatic' : e.target.value;
                            this.addSystemMessage(messagesContainer, `Switched to ${modeText} mode`);
                            
                            // Clear conversation history when switching modes
                            this.chatHistories.set(botId, []);
                            this.addSystemMessage(messagesContainer, 'Conversation history cleared');
                        }
                    });
                });
                
                console.log(`Bot "${botName}" (${botId}) initialized with Ollama backend`);
                
                // Add initial message based on Ollama status
                const isOllamaOffline = this.serverConfig.ollama.status === 'offline';
                
                if (isOllamaOffline) {
                    this.addSystemMessage(messagesContainer, 'Ollama AI assistant is offline');
                    this.addMessage(messagesContainer, "Hello! I'm currently offline because Ollama isn't running. Please make sure Ollama is running with the deepseek-v3.1:671b-cloud model.", 'bot');
                } else {
                    this.addSystemMessage(messagesContainer, `Connected to Ollama AI (${this.serverConfig.ollama.model})`);
                    this.addMessage(messagesContainer, `Hello! I'm an AI assistant powered by ${this.serverConfig.ollama.model}. How can I help you today?`, 'bot');
                }
            } catch (error) {
                console.error('Error initializing bot:', error);
            }
        },
        
        // Update bot status indicator
        updateBotStatusIndicator: function(container) {
            try {
                const botId = container.dataset.id;
                const connectionElement = document.getElementById(`${botId}-connection`);
                
                if (!connectionElement) return;
                
                let statusIcon = connectionElement.previousElementSibling;
                if (!statusIcon) return;
                
                // Remove previous status classes
                statusIcon.classList.remove('status-online', 'status-offline', 'status-unknown');
                
                // Determine status based on Ollama status
                let status = 'unknown';
                let statusText = 'Unknown';
                
                if (this.serverConfig.ollama.status === 'offline') {
                    status = 'offline';
                    statusText = 'Ollama Offline';
                } else if (this.serverConfig.ollama.status === 'online') {
                    status = 'online';
                    statusText = `AI Ready (${this.serverConfig.ollama.model})`;
                } else {
                    status = 'unknown';
                    statusText = 'Checking Ollama...';
                }
                
                // Update status text and icon color
                connectionElement.textContent = statusText;
                statusIcon.classList.add(`status-${status}`);
                
                // Log status
                console.log(`Bot ${botId} status updated to ${status} (${statusText})`);
            } catch (error) {
                console.error('Error updating bot status:', error);
            }
        },
        
        // Send a message to the bot
        sendMessage: function(botId, message) {
            try {
                if (!message.trim()) return;
                
                const container = document.querySelector(`.forum-bot-container[data-id="${botId}"]`);
                if (!container) return;
                
                const messagesContainer = document.getElementById(`${botId}-messages`);
                
                // Add user message to chat
                this.addMessage(messagesContainer, message, 'user');
                
                // Check if Ollama is available
                if (this.serverConfig.ollama.status === 'offline') {
                    // Use fallback mode
                    if (this.serverConfig.fallbackMode.enabled) {
                        const botType = container.dataset.type || 'auto';
                        const responseType = botType === 'code' ? 'code' : 
                                             botType === 'chat' ? 'chat' : 'auto';
                        
                        const responses = this.serverConfig.fallbackMode.responses[responseType];
                        const randomResponse = responses[Math.floor(Math.random() * responses.length)];
                        
                        // Show "thinking" briefly
                        const thinkingId = this.addThinkingIndicator(messagesContainer);
                        
                        setTimeout(() => {
                            this.removeThinkingIndicator(thinkingId);
                            this.addMessage(messagesContainer, randomResponse, 'bot');
                        }, 1000);
                        
                        return;
                    } else {
                        this.addSystemMessage(messagesContainer, 'Ollama is currently offline. Please start Ollama and try again.');
                        return;
                    }
                }
                
                // Show thinking indicator
                const thinkingId = this.addThinkingIndicator(messagesContainer);
                
                // Send message to Ollama
                this.sendToOllama(botId, message)
                    .then((response) => {
                        // Remove thinking indicator
                        this.removeThinkingIndicator(thinkingId);
                        
                        // Add bot response to chat
                        if (response) {
                            this.addMessage(messagesContainer, response, 'bot');
                        } else {
                            throw new Error('Empty response from Ollama');
                        }
                    })
                    .catch((error) => {
                        console.error('Error sending message to Ollama:', error);
                        
                        // Remove thinking indicator
                        this.removeThinkingIndicator(thinkingId);
                        
                        // Add error message
                        const errorMsg = error.message.includes('CORS') 
                            ? "Connection error: Please set OLLAMA_ORIGINS=* environment variable and restart Ollama."
                            : `Sorry, I encountered an error: ${error.message}`;
                        
                        this.addMessage(messagesContainer, errorMsg, 'bot');
                        
                        // Update server status
                        this.serverConfig.ollama.status = 'offline';
                        this.updateBotStatusIndicator(container);
                    });
            } catch (error) {
                console.error('Error in sendMessage:', error);
            }
        },
        
        // Send message to Ollama
        sendToOllama: async function(botId, message) {
            try {
                // Get chat history for this bot
                const chatHistory = this.chatHistories.get(botId) || [];

                // Add user message to history
                chatHistory.push({ role: 'user', content: message });

                // Check if we should use PHP proxy directly
                if (this.serverConfig.ollama.useProxy) {
                    // Use PHP proxy directly
                    const phpPayload = {
                        messages: chatHistory,
                        userMessage: message,
                        model: this.serverConfig.ollama.model
                    };

                    const phpResponse = await fetch('bot-handler.php?action=call_ollama', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(phpPayload),
                        signal: AbortSignal.timeout(this.serverConfig.timeout)
                    });

                    if (!phpResponse.ok) {
                        throw new Error(`PHP proxy error: HTTP ${phpResponse.status}`);
                    }

                    const phpData = await phpResponse.json();

                    if (!phpData.success) {
                        throw new Error(phpData.error || 'PHP proxy returned error');
                    }

                    const botResponseContent = phpData.botResponse || "Sorry, I couldn't get a response.";

                    // Add bot message to chat history
                    chatHistory.push({ role: 'assistant', content: botResponseContent });

                    // Update chat history (keep last 20 messages to prevent memory issues)
                    if (chatHistory.length > 20) {
                        chatHistory.splice(0, chatHistory.length - 20);
                    }
                    this.chatHistories.set(botId, chatHistory);

                    return botResponseContent;
                } else {
                    // First, try direct connection to Ollama
                    try {
                        // Prepare the request
                        const endpoint = this.serverConfig.ollama.endpoint;
                        const fullUrl = this.serverConfig.ollama.baseUrl + endpoint;

                        const payload = endpoint === '/v1/chat/completions' ? {
                            model: this.serverConfig.ollama.model,
                            messages: chatHistory,
                            max_tokens: this.serverConfig.ollama.maxTokens,
                            temperature: this.serverConfig.ollama.temperature,
                            stream: false
                        } : {
                            model: this.serverConfig.ollama.model,
                            messages: chatHistory,
                            stream: false
                        };

                        console.log('Sending request to Ollama:', { url: fullUrl, model: this.serverConfig.ollama.model });

                        const response = await fetch(fullUrl, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(payload),
                            signal: AbortSignal.timeout(this.serverConfig.timeout)
                        });

                        if (!response.ok) {
                            if (response.status === 403) {
                                throw new Error('CORS error (403). Falling back to PHP proxy...');
                            }
                            let errorDetails = `HTTP error! status: ${response.status}`;
                            try {
                                const errorJson = await response.json();
                                if (errorJson && errorJson.error) {
                                    errorDetails += `: ${errorJson.error}`;
                                }
                            } catch (e) {
                                // Response was not JSON, use default error message
                            }
                            throw new Error(errorDetails);
                        }

                        const data = await response.json();
                        console.log('Ollama response received');

                        // Handle different response formats
                        let botResponseContent;
                        if (endpoint === '/v1/chat/completions') {
                            // OpenAI format
                            botResponseContent = data.choices?.[0]?.message?.content || "Sorry, I couldn't get a response.";
                        } else {
                            // Native Ollama format
                            botResponseContent = data.message?.content || "Sorry, I couldn't get a response.";
                        }

                        // Add bot message to chat history
                        chatHistory.push({ role: 'assistant', content: botResponseContent });

                        // Update chat history (keep last 20 messages to prevent memory issues)
                        if (chatHistory.length > 20) {
                            chatHistory.splice(0, chatHistory.length - 20);
                        }
                        this.chatHistories.set(botId, chatHistory);

                        return botResponseContent;
                    } catch (directError) {
                        console.warn('Direct Ollama connection failed, falling back to PHP proxy:', directError.message);

                        // Fallback to PHP proxy
                        const phpPayload = {
                            messages: chatHistory,
                            userMessage: message,
                            model: this.serverConfig.ollama.model
                        };

                        const phpResponse = await fetch('bot-handler.php?action=call_ollama', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(phpPayload),
                            signal: AbortSignal.timeout(this.serverConfig.timeout)
                        });

                        if (!phpResponse.ok) {
                            throw new Error(`PHP proxy error: HTTP ${phpResponse.status}`);
                        }

                        const phpData = await phpResponse.json();

                        if (!phpData.success) {
                            throw new Error(phpData.error || 'PHP proxy returned error');
                        }

                        const botResponseContent = phpData.botResponse || "Sorry, I couldn't get a response.";

                        // Add bot message to chat history
                        chatHistory.push({ role: 'assistant', content: botResponseContent });

                        // Update chat history (keep last 20 messages to prevent memory issues)
                        if (chatHistory.length > 20) {
                            chatHistory.splice(0, chatHistory.length - 20);
                        }
                        this.chatHistories.set(botId, chatHistory);

                        return botResponseContent;
                    }
                }

            } catch (error) {
                console.error('Error in sendToOllama:', error);
                throw error;
            }
        },
        
        // Add a message to the chat
        addMessage: function(container, message, sender) {
            try {
                if (!container) {
                    console.error('Message container not found');
                    return;
                }
                
                const messageElement = document.createElement('div');
                messageElement.className = sender === 'user' ? 'user-message' : 'bot-message';
                
                let content = '';
                
                if (sender === 'bot') {
                    // Process markdown in bot messages (similar to bot.php)
                    let processedMessage = this.processMarkdown(message);
                    
                    content = `
                        <div class="bot-avatar">
                            <i class="fas fa-robot"></i>
                        </div>
                        <div class="message-content">${processedMessage}</div>
                    `;
                } else {
                    content = `
                        <div class="message-content">${this.escapeHtml(message)}</div>
                    `;
                }
                
                messageElement.innerHTML = content;
                container.appendChild(messageElement);
                
                // Scroll to bottom
                container.scrollTop = container.scrollHeight;
            } catch (error) {
                console.error('Error adding message:', error);
            }
        },
        
        // Process markdown (simplified version of marked.js functionality)
        processMarkdown: function(text) {
            try {
                // Use marked.js if available
                if (typeof marked !== 'undefined') {
                    return marked.parse(text);
                }
                
                // Simple fallback markdown processing
                let processed = this.escapeHtml(text);
                
                // Bold **text**
                processed = processed.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
                
                // Italic *text*
                processed = processed.replace(/\*(.*?)\*/g, '<em>$1</em>');
                
                // Code blocks ```code```
                processed = processed.replace(/```([\s\S]*?)```/g, '<pre class="code-block"><code>$1</code></pre>');
                
                // Inline code `code`
                processed = processed.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');
                
                // Line breaks
                processed = processed.replace(/\n/g, '<br>');
                
                return processed;
            } catch (error) {
                console.error('Error processing markdown:', error);
                return this.escapeHtml(text);
            }
        },
        
        // Add a system message
        addSystemMessage: function(container, message) {
            try {
                if (!container) {
                    console.error('System message container not found');
                    return;
                }
                
                const messageElement = document.createElement('div');
                messageElement.className = 'system-message';
                messageElement.textContent = message;
                
                container.appendChild(messageElement);
                
                // Scroll to bottom
                container.scrollTop = container.scrollHeight;
            } catch (error) {
                console.error('Error adding system message:', error);
            }
        },
        
        // Add thinking indicator
        addThinkingIndicator: function(container) {
            try {
                if (!container) {
                    console.error('Thinking indicator container not found');
                    return null;
                }
                
                const id = 'thinking-' + Math.random().toString(36).substring(2, 9);
                
                const thinkingElement = document.createElement('div');
                thinkingElement.className = 'bot-message thinking';
                thinkingElement.id = id;
                
                thinkingElement.innerHTML = `
                    <div class="bot-avatar">
                        <i class="fas fa-robot"></i>
                    </div>
                    <div class="message-content">
                        <span class="thinking-dots">
                            <span class="dot"></span>
                            <span class="dot"></span>
                            <span class="dot"></span>
                        </span>
                    </div>
                `;
                
                container.appendChild(thinkingElement);
                
                // Scroll to bottom
                container.scrollTop = container.scrollHeight;
                
                return id;
            } catch (error) {
                console.error('Error adding thinking indicator:', error);
                return null;
            }
        },
        
        // Remove thinking indicator
        removeThinkingIndicator: function(id) {
            try {
                if (!id) return;
                
                const element = document.getElementById(id);
                if (element) {
                    element.remove();
                }
            } catch (error) {
                console.error('Error removing thinking indicator:', error);
            }
        },
        
        // Escape HTML to prevent XSS
        escapeHtml: function(text) {
            try {
                if (typeof text !== 'string') {
                    return '';
                }
                
                return text
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            } catch (error) {
                console.error('Error escaping HTML:', error);
                return '';
            }
        }
    };
    
    // Add CSS for the bot if not already present
    function addBotStyles() {
        if (document.getElementById('forum-bot-styles')) {
            return;
        }
        
        const styleEl = document.createElement('style');
        styleEl.id = 'forum-bot-styles';
        styleEl.textContent = `
            /* Enhanced styles for Ollama-powered forum bot */
            .forum-bot-container {
                border: 1px solid #e0e0e0;
                border-radius: 8px;
                overflow: hidden;
                margin: 15px 0;
                background-color: #fff;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
                font-family: inherit;
            }
            
            .forum-bot-header {
                background-color: #f5f5f5;
                padding: 10px 15px;
                border-bottom: 1px solid #e0e0e0;
                font-weight: bold;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            
            .forum-bot-header i {
                margin-right: 8px;
                color: #2196F3;
            }
            
            /* Bot type toggle styles */
            .bot-type-toggle {
                display: flex;
                border-radius: 15px;
                overflow: hidden;
                background-color: #e0e0e0;
                margin-left: auto;
                border: 1px solid #ccc;
            }
            
            .toggle-label {
                padding: 3px 8px;
                cursor: pointer;
                font-size: 12px;
                display: flex;
                align-items: center;
                margin: 0;
                transition: background-color 0.2s;
            }
            
            .toggle-label input {
                position: absolute;
                opacity: 0;
                cursor: pointer;
                height: 0;
                width: 0;
            }
            
            .toggle-label input:checked + span {
                color: #fff;
                font-weight: bold;
            }
            
            .toggle-label:first-child input:checked + span {
                background-color: #4CAF50; /* Chat - Green */
            }
            
            .toggle-label:nth-child(2) input:checked + span {
                background-color: #2196F3; /* Auto - Blue */
            }
            
            .toggle-label:last-child input:checked + span {
                background-color: #FF9800; /* Code - Orange */
            }
            
            .toggle-label span {
                padding: 3px 8px;
                border-radius: 12px;
            }
            
            /* Bot status styles */
            .bot-status {
                margin-left: 10px;
                font-size: 12px;
                color: #666;
            }
            
            /* Forum bot messages container */
            .forum-bot-messages {
                height: 250px;
                overflow-y: auto;
                padding: 15px;
                display: flex;
                flex-direction: column;
                gap: 10px;
            }
            
            .bot-message, .user-message {
                display: flex;
                max-width: 80%;
            }
            
            .user-message {
                margin-left: auto;
                flex-direction: row-reverse;
            }
            
            .bot-avatar {
                width: 36px;
                height: 36px;
                background-color: #2196F3;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                margin-right: 8px;
            }
            
            .user-message .bot-avatar {
                margin-right: 0;
                margin-left: 8px;
            }
            
            .message-content {
                background-color: #f1f1f1;
                padding: 10px 15px;
                border-radius: 18px;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
                line-height: 1.4;
            }
            
            .user-message .message-content {
                background-color: #e3f2fd;
            }
            
            /* Enhanced message content styles for markdown */
            .message-content p {
                margin: 0.5em 0;
            }
            
            .message-content strong {
                font-weight: bold;
            }
            
            .message-content em {
                font-style: italic;
            }
            
            .message-content ul, .message-content ol {
                margin: 0.5em 0;
                padding-left: 1.5em;
            }
            
            .message-content h1, .message-content h2, .message-content h3,
            .message-content h4, .message-content h5, .message-content h6 {
                font-weight: bold;
                margin: 0.5em 0;
            }
            
            .message-content pre {
                background-color: #2d2d2d;
                color: #f8f8f2;
                padding: 10px;
                border-radius: 4px;
                overflow-x: auto;
                font-family: monospace;
                margin: 0.5em 0;
            }
            
            .message-content code {
                background-color: #f0f0f0;
                padding: 2px 4px;
                border-radius: 3px;
                font-family: monospace;
                font-size: 85%;
            }
            
            .message-content a {
                color: #2196F3;
                text-decoration: underline;
            }
            
            .message-content blockquote {
                border-left: 4px solid #ddd;
                padding-left: 1em;
                margin: 0.5em 0;
                color: #666;
                font-style: italic;
            }
            
            /* System messages */
            .system-message {
                text-align: center;
                font-size: 12px;
                color: #888;
                margin: 8px 0;
                font-style: italic;
            }
            
            /* Thinking animation */
            .thinking-dots {
                display: inline-flex;
                gap: 4px;
            }
            
            .thinking-dots .dot {
                width: 8px;
                height: 8px;
                background-color: #888;
                border-radius: 50%;
                animation: pulse 1.5s infinite;
            }
            
            .thinking-dots .dot:nth-child(2) {
                animation-delay: 0.2s;
            }
            
            .thinking-dots .dot:nth-child(3) {
                animation-delay: 0.4s;
            }
            
            @keyframes pulse {
                0%, 60%, 100% {
                    transform: scale(1);
                    opacity: 0.4;
                }
                20% {
                    transform: scale(1.2);
                    opacity: 1;
                }
            }
            
            /* Input area */
            .forum-bot-input {
                display: flex;
                padding: 10px;
                border-top: 1px solid #e0e0e0;
                background-color: #f9f9f9;
            }
            
            .forum-bot-input textarea {
                flex-grow: 1;
                border: 1px solid #e0e0e0;
                border-radius: 18px;
                padding: 8px 15px;
                resize: none;
                height: 38px;
                outline: none;
                font-family: inherit;
                font-size: 14px;
            }
            
            .bot-send-btn {
                width: 38px;
                height: 38px;
                border: none;
                background-color: #2196F3;
                color: white;
                border-radius: 50%;
                margin-left: 8px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: background-color 0.2s;
            }
            
            .bot-send-btn:hover {
                background-color: #1976D2;
            }
            
            /* Footer with connection status */
            .forum-bot-footer {
                padding: 8px 15px;
                background-color: #f5f5f5;
                border-top: 1px solid #e0e0e0;
                display: flex;
                justify-content: space-between;
                font-size: 12px;
                color: #666;
            }
            
            .bot-status-indicator {
                display: flex;
                align-items: center;
                gap: 5px;
            }
            
            .bot-status-indicator i {
                font-size: 10px;
            }
            
            .status-online {
                color: #4CAF50;
            }
            
            .status-offline {
                color: #F44336;
            }
            
            .status-unknown {
                color: #FFC107;
            }
            
            .bot-info {
                font-style: italic;
            }
            
            /* Dark theme support */
            [data-theme="dark"] .forum-bot-container {
                border-color: #444;
                background-color: #222;
            }
            
            [data-theme="dark"] .forum-bot-header {
                background-color: #333;
                border-color: #444;
                color: #eee;
            }
            
            [data-theme="dark"] .bot-type-toggle {
                background-color: #555;
                border-color: #666;
            }
            
            [data-theme="dark"] .toggle-label {
                color: #ccc;
            }
            
            [data-theme="dark"] .bot-status {
                color: #aaa;
            }
            
            [data-theme="dark"] .forum-bot-messages {
                background-color: #222;
            }
            
            [data-theme="dark"] .message-content {
                background-color: #333;
                color: #eee;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
            }
            
            [data-theme="dark"] .user-message .message-content {
                background-color: #1a3a5f;
            }
            
            [data-theme="dark"] .system-message {
                color: #aaa;
            }
            
            [data-theme="dark"] .forum-bot-input {
                background-color: #333;
                border-color: #444;
            }
            
            [data-theme="dark"] .forum-bot-input textarea {
                background-color: #444;
                border-color: #555;
                color: #eee;
            }
            
            [data-theme="dark"] .message-content code {
                background-color: #3a3a3a;
                color: #ddd;
            }
            
            [data-theme="dark"] .forum-bot-footer {
                background-color: #333;
                color: #aaa;
                border-color: #444;
            }
        `;
        
        document.head.appendChild(styleEl);
    }
    
    // Load marked.js for markdown processing if not already loaded
    function loadMarkedJs() {
        if (typeof marked !== 'undefined') {
            return Promise.resolve();
        }
        
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/marked/marked.min.js';
            script.onload = () => {
                console.log('Marked.js loaded for markdown processing');
                resolve();
            };
            script.onerror = () => {
                console.warn('Failed to load Marked.js, using fallback markdown processing');
                resolve(); // Don't reject, use fallback
            };
            document.head.appendChild(script);
        });
    }
    
    // Add styles
    addBotStyles();
    
    // Load markdown processor
    loadMarkedJs().then(() => {
        // Auto-initialize after a short delay to ensure DOM is ready
        setTimeout(() => {
            window.ForumBot.init();
        }, 500);
    });
    
    // Also set up a mutation observer to catch dynamically added bots
    const observer = new MutationObserver((mutations) => {
        let shouldInit = false;
        
        for (const mutation of mutations) {
            if (mutation.type === 'childList' && mutation.addedNodes.length) {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType === 1) { // Element node
                        if ((node.classList && node.classList.contains('forum-bot-container')) || 
                            node.querySelector('.forum-bot-container')) {
                            shouldInit = true;
                        }
                    }
                });
            }
        }
        
        if (shouldInit && window.ForumBot) {
            window.ForumBot.init();
        }
    });
    
    // Start observing the document body
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();// Enhanced forum-bot.js with Ollama Integration (replacing Python servers)
(function() {
    // Make ForumBot available globally
    window.ForumBot = {
        // Configuration
        serverConfig: {
            // Ollama configuration
            ollama: {
                baseUrl: 'http://secupgrade.com:11434',
                model: 'deepseek-v3.1:671b-cloud',
                endpoint: '/api/generate', // or '/api/chat' for native

                status: 'unknown',
                maxTokens: 128000,
                temperature: 0.7
            },
            timeout: 30000,
            // Fallback responses when Ollama is offline
            fallbackMode: {
                enabled: true,
                responses: {
                    code: [
                        "I'm sorry, the AI assistant is currently offline. Please make sure Ollama is running with the deepseek-v3.1:671b-cloud model.",
                        "It looks like I can't connect to Ollama right now. Please check that it's running and try again.",
                        "Code assistant requires Ollama to be running. Please start Ollama and pull the deepseek-v3.1:671b-cloud model."
                    ],
                    chat: [
                        "I'm currently offline and can't process your message. Please ensure Ollama is running.",
                        "Sorry, I'm unable to connect to the AI backend. Please check Ollama status.",
                        "Chat service requires Ollama. Please start it with: ollama serve"
                    ],
                    auto: [
                        "I apologize, but the AI assistant is currently offline. Please start Ollama and try again.",
                        "Unable to connect to Ollama. Make sure it's running with: ollama serve",
                        "Service temporarily unavailable. Please check Ollama installation and model availability."
                    ]
                }
            }
        },
        
        // Chat history storage for each bot instance
        chatHistories: new Map(),
        
        // Initialize all bot instances on the page
        init: function() {
            console.log('Auto-initializing Forum Bot with Ollama');
            
            // Find all bot containers
            const botContainers = document.querySelectorAll('.forum-bot-container');
            console.log('Found', botContainers.length, 'bot containers');
            
            // Check Ollama status first
            this.checkOllamaStatus()
                .then(() => {
                    console.log('Ollama status checked');
                    // Initialize each bot after checking status
                    botContainers.forEach((container) => {
                        this.initializeBot(container);
                    });
                    console.log('All bots initialized');
                })
                .catch((error) => {
                    console.warn('Ollama status check failed:', error);
                    console.log('Initializing bots in offline mode');
                    
                    // Initialize bots anyway, status will show as offline
                    botContainers.forEach((container) => {
                        this.initializeBot(container);
                    });
                });
            
            console.log('Forum Bot initialization complete');
            
            // Set up periodic status checks
            setInterval(() => this.checkOllamaStatus(), 60000); // Check every minute
        },
        
        // Check if Ollama is running and model is available
        checkOllamaStatus: function() {
            return new Promise((resolve, reject) => {
                this.testOllamaConnection()
                    .then((isOnline) => {
                        this.serverConfig.ollama.status = isOnline ? 'online' : 'offline';
                        
                        // Update all bot status indicators
                        document.querySelectorAll('.forum-bot-container').forEach((container) => {
                            this.updateBotStatusIndicator(container);
                        });
                        
                        if (isOnline) {
                            resolve(true);
                        } else {
                            reject(new Error('Ollama is offline'));
                        }
                    })
                    .catch((error) => {
                        console.error('Ollama connection test failed:', error);
                        this.serverConfig.ollama.status = 'offline';
                        
                        // Update all bot status indicators
                        document.querySelectorAll('.forum-bot-container').forEach((container) => {
                            this.updateBotStatusIndicator(container);
                        });
                        
                        reject(error);
                    });
            });
        },
        
        // Test Ollama connection
        testOllamaConnection: async function() {
            try {
                console.log('Testing Ollama connection...');

                // First, try direct connection to Ollama
                try {
                    // First, test if Ollama is running by checking /api/tags
                    const tagsResponse = await fetch(this.serverConfig.ollama.baseUrl + '/api/tags', {
                        method: 'GET',
                        signal: AbortSignal.timeout(5000)
                    });

                    if (!tagsResponse.ok) {
                        throw new Error(`Ollama server not responding (${tagsResponse.status})`);
                    }

                    const tagsData = await tagsResponse.json();
                    console.log('Available models:', tagsData.models?.map(m => m.name) || []);

                    // Check if our model exists
                    const modelExists = tagsData.models?.some(model =>
                        model.name.includes(this.serverConfig.ollama.model) ||
                        model.name.includes(this.serverConfig.ollama.model.replace(':3.8b', ''))
                    );

                    if (!modelExists) {
                        const availableModels = tagsData.models?.map(m => m.name).join(', ') || 'none';
                        console.warn(`Model "${this.serverConfig.ollama.model}" not found. Available: ${availableModels}`);
                        throw new Error(`Model "${this.serverConfig.ollama.model}" not available. Run: ollama pull ${this.serverConfig.ollama.model}`);
                    }

                    // Test the actual chat endpoint with a simple request
                    const endpoint = this.serverConfig.ollama.endpoint;
                    const fullUrl = this.serverConfig.ollama.baseUrl + endpoint;

                    const testPayload = endpoint === '/api/generate' ? {
                        model: this.serverConfig.ollama.model,
                        messages: [{ role: 'user', content: 'Hi' }],
                        max_tokens: 1,
                        stream: false
                    } : {
                        model: this.serverConfig.ollama.model,
                        messages: [{ role: 'user', content: 'Hi' }],
                        stream: false
                    };

                    const testResponse = await fetch(fullUrl, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(testPayload),
                        signal: AbortSignal.timeout(10000)
                    });

                    if (!testResponse.ok) {
                        if (testResponse.status === 403) {
                            throw new Error('CORS error. Falling back to PHP proxy...');
                        }
                        throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`);
                    }

                    console.log('Ollama connection test successful');
                    return true;
                } catch (directError) {
                    console.warn('Direct Ollama connection test failed, falling back to PHP proxy:', directError.message);

                    // Fallback to PHP proxy for connection test
                    try {
                        // Test the PHP proxy by making a simple call
                        const testPayload = {
                            messages: [{ role: 'user', content: 'test' }],
                            userMessage: 'test',
                            model: this.serverConfig.ollama.model
                        };

                        const phpResponse = await fetch('bot-handler.php?action=call_ollama', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(testPayload),
                            signal: AbortSignal.timeout(10000)
                        });

                        if (!phpResponse.ok) {
                            throw new Error(`PHP proxy test failed: HTTP ${phpResponse.status}`);
                        }

                        const phpData = await phpResponse.json();

                        if (!phpData.success && !phpData.botResponse) {
                            throw new Error(phpData.error || 'PHP proxy test failed');
                        }

                        console.log('Ollama connection test successful via PHP proxy');
                        return true;
                    } catch (proxyError) {
                        console.error('Both direct and proxy connection tests failed:', proxyError);
                        return false;
                    }
                }
            } catch (error) {
                console.error('Ollama connection test failed:', error);
                return false;
            }
        },
        
        // Initialize a single bot container
        initializeBot: function(container) {
            try {
                const botId = container.dataset.id;
                const botName = container.dataset.name;
                const botType = container.dataset.type || 'auto';
                
                // Skip if already initialized
                if (container.dataset.initialized === 'true') {
                    return;
                }
                
                // Mark as initialized
                container.dataset.initialized = 'true';
                
                // Initialize chat history for this bot
                if (!this.chatHistories.has(botId)) {
                    this.chatHistories.set(botId, []);
                }
                
                // Get elements
                const messagesContainer = document.getElementById(`${botId}-messages`);
                const inputField = document.getElementById(`${botId}-input`);
                const sendButton = container.querySelector('.bot-send-btn');
                const statusElement = document.getElementById(`${botId}-connection`);
                
                if (!messagesContainer || !inputField || !sendButton) {
                    console.error(`Missing required elements for bot ${botId}`);
                    return;
                }
                
                // Set initial status
                if (statusElement) {
                    statusElement.innerHTML = '<i class="fas fa-sync fa-spin"></i> Checking Ollama...';
                }
                
                // Update status indicator
                this.updateBotStatusIndicator(container);
                
                // Add event listener for send button
                sendButton.addEventListener('click', () => {
                    if (inputField.value.trim()) {
                        this.sendMessage(botId, inputField.value);
                        inputField.value = '';
                    }
                });
                
                // Add event listener for enter key
                inputField.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        if (inputField.value.trim()) {
                            this.sendMessage(botId, inputField.value);
                            inputField.value = '';
                        }
                    }
                });
                
                // Add event listeners for bot type toggle
                container.querySelectorAll('input[name^="bot-type-"]').forEach((radio) => {
                    radio.addEventListener('change', (e) => {
                        if (e.target.checked) {
                            container.dataset.type = e.target.value;
                            this.updateBotStatusIndicator(container);
                            
                            // Add a system message about bot type change
                            let modeText = e.target.value === 'auto' ? 'automatic' : e.target.value;
                            this.addSystemMessage(messagesContainer, `Switched to ${modeText} mode`);
                            
                            // Clear conversation history when switching modes
                            this.chatHistories.set(botId, []);
                            this.addSystemMessage(messagesContainer, 'Conversation history cleared');
                        }
                    });
                });
                
                console.log(`Bot "${botName}" (${botId}) initialized with Ollama backend`);
                
                // Add initial message based on Ollama status
                const isOllamaOffline = this.serverConfig.ollama.status === 'offline';
                
                if (isOllamaOffline) {
                    this.addSystemMessage(messagesContainer, 'Ollama AI assistant is offline');
                    this.addMessage(messagesContainer, "Hello! I'm currently offline because Ollama isn't running. Please make sure Ollama is running with the deepseek-v3.1:671b-cloud model.", 'bot');
                } else {
                    this.addSystemMessage(messagesContainer, `Connected to Ollama AI (${this.serverConfig.ollama.model})`);
                    this.addMessage(messagesContainer, `Hello! I'm an AI assistant powered by ${this.serverConfig.ollama.model}. How can I help you today?`, 'bot');
                }
            } catch (error) {
                console.error('Error initializing bot:', error);
            }
        },
        
        // Update bot status indicator
        updateBotStatusIndicator: function(container) {
            try {
                const botId = container.dataset.id;
                const connectionElement = document.getElementById(`${botId}-connection`);
                
                if (!connectionElement) return;
                
                let statusIcon = connectionElement.previousElementSibling;
                if (!statusIcon) return;
                
                // Remove previous status classes
                statusIcon.classList.remove('status-online', 'status-offline', 'status-unknown');
                
                // Determine status based on Ollama status
                let status = 'unknown';
                let statusText = 'Unknown';
                
                if (this.serverConfig.ollama.status === 'offline') {
                    status = 'offline';
                    statusText = 'Ollama Offline';
                } else if (this.serverConfig.ollama.status === 'online') {
                    status = 'online';
                    statusText = `AI Ready (${this.serverConfig.ollama.model})`;
                } else {
                    status = 'unknown';
                    statusText = 'Checking Ollama...';
                }
                
                // Update status text and icon color
                connectionElement.textContent = statusText;
                statusIcon.classList.add(`status-${status}`);
                
                // Log status
                console.log(`Bot ${botId} status updated to ${status} (${statusText})`);
            } catch (error) {
                console.error('Error updating bot status:', error);
            }
        },
        
        // Send a message to the bot
        sendMessage: function(botId, message) {
            try {
                if (!message.trim()) return;
                
                const container = document.querySelector(`.forum-bot-container[data-id="${botId}"]`);
                if (!container) return;
                
                const messagesContainer = document.getElementById(`${botId}-messages`);
                
                // Add user message to chat
                this.addMessage(messagesContainer, message, 'user');
                
                // Check if Ollama is available
                if (this.serverConfig.ollama.status === 'offline') {
                    // Use fallback mode
                    if (this.serverConfig.fallbackMode.enabled) {
                        const botType = container.dataset.type || 'auto';
                        const responseType = botType === 'code' ? 'code' : 
                                             botType === 'chat' ? 'chat' : 'auto';
                        
                        const responses = this.serverConfig.fallbackMode.responses[responseType];
                        const randomResponse = responses[Math.floor(Math.random() * responses.length)];
                        
                        // Show "thinking" briefly
                        const thinkingId = this.addThinkingIndicator(messagesContainer);
                        
                        setTimeout(() => {
                            this.removeThinkingIndicator(thinkingId);
                            this.addMessage(messagesContainer, randomResponse, 'bot');
                        }, 1000);
                        
                        return;
                    } else {
                        this.addSystemMessage(messagesContainer, 'Ollama is currently offline. Please start Ollama and try again.');
                        return;
                    }
                }
                
                // Show thinking indicator
                const thinkingId = this.addThinkingIndicator(messagesContainer);
                
                // Send message to Ollama
                this.sendToOllama(botId, message)
                    .then((response) => {
                        // Remove thinking indicator
                        this.removeThinkingIndicator(thinkingId);
                        
                        // Add bot response to chat
                        if (response) {
                            this.addMessage(messagesContainer, response, 'bot');
                        } else {
                            throw new Error('Empty response from Ollama');
                        }
                    })
                    .catch((error) => {
                        console.error('Error sending message to Ollama:', error);
                        
                        // Remove thinking indicator
                        this.removeThinkingIndicator(thinkingId);
                        
                        // Add error message
                        const errorMsg = error.message.includes('CORS') 
                            ? "Connection error: Please set OLLAMA_ORIGINS=* environment variable and restart Ollama."
                            : `Sorry, I encountered an error: ${error.message}`;
                        
                        this.addMessage(messagesContainer, errorMsg, 'bot');
                        
                        // Update server status
                        this.serverConfig.ollama.status = 'offline';
                        this.updateBotStatusIndicator(container);
                    });
            } catch (error) {
                console.error('Error in sendMessage:', error);
            }
        },
        
        // Send message to Ollama
        sendToOllama: async function(botId, message) {
            try {
                // Get chat history for this bot
                const chatHistory = this.chatHistories.get(botId) || [];

                // Add user message to history
                chatHistory.push({ role: 'user', content: message });

                // Check if we should use PHP proxy directly
                if (this.serverConfig.ollama.useProxy) {
                    // Use PHP proxy directly
                    const phpPayload = {
                        messages: chatHistory,
                        userMessage: message,
                        model: this.serverConfig.ollama.model
                    };

                    const phpResponse = await fetch('bot-handler.php?action=call_ollama', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(phpPayload),
                        signal: AbortSignal.timeout(this.serverConfig.timeout)
                    });

                    if (!phpResponse.ok) {
                        throw new Error(`PHP proxy error: HTTP ${phpResponse.status}`);
                    }

                    const phpData = await phpResponse.json();

                    if (!phpData.success) {
                        throw new Error(phpData.error || 'PHP proxy returned error');
                    }

                    const botResponseContent = phpData.botResponse || "Sorry, I couldn't get a response.";

                    // Add bot message to chat history
                    chatHistory.push({ role: 'assistant', content: botResponseContent });

                    // Update chat history (keep last 20 messages to prevent memory issues)
                    if (chatHistory.length > 20) {
                        chatHistory.splice(0, chatHistory.length - 20);
                    }
                    this.chatHistories.set(botId, chatHistory);

                    return botResponseContent;
                } else {
                    // First, try direct connection to Ollama
                    try {
                        // Prepare the request
                        const endpoint = this.serverConfig.ollama.endpoint;
                        const fullUrl = this.serverConfig.ollama.baseUrl + endpoint;

                        const payload = endpoint === '/v1/chat/completions' ? {
                            model: this.serverConfig.ollama.model,
                            messages: chatHistory,
                            max_tokens: this.serverConfig.ollama.maxTokens,
                            temperature: this.serverConfig.ollama.temperature,
                            stream: false
                        } : {
                            model: this.serverConfig.ollama.model,
                            messages: chatHistory,
                            stream: false
                        };

                        console.log('Sending request to Ollama:', { url: fullUrl, model: this.serverConfig.ollama.model });

                        const response = await fetch(fullUrl, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(payload),
                            signal: AbortSignal.timeout(this.serverConfig.timeout)
                        });

                        if (!response.ok) {
                            if (response.status === 403) {
                                throw new Error('CORS error (403). Falling back to PHP proxy...');
                            }
                            let errorDetails = `HTTP error! status: ${response.status}`;
                            try {
                                const errorJson = await response.json();
                                if (errorJson && errorJson.error) {
                                    errorDetails += `: ${errorJson.error}`;
                                }
                            } catch (e) {
                                // Response was not JSON, use default error message
                            }
                            throw new Error(errorDetails);
                        }

                        const data = await response.json();
                        console.log('Ollama response received');

                        // Handle different response formats
                        let botResponseContent;
                        if (endpoint === '/v1/chat/completions') {
                            // OpenAI format
                            botResponseContent = data.choices?.[0]?.message?.content || "Sorry, I couldn't get a response.";
                        } else {
                            // Native Ollama format
                            botResponseContent = data.message?.content || "Sorry, I couldn't get a response.";
                        }

                        // Add bot message to chat history
                        chatHistory.push({ role: 'assistant', content: botResponseContent });

                        // Update chat history (keep last 20 messages to prevent memory issues)
                        if (chatHistory.length > 20) {
                            chatHistory.splice(0, chatHistory.length - 20);
                        }
                        this.chatHistories.set(botId, chatHistory);

                        return botResponseContent;
                    } catch (directError) {
                        console.warn('Direct Ollama connection failed, falling back to PHP proxy:', directError.message);

                        // Fallback to PHP proxy
                        const phpPayload = {
                            messages: chatHistory,
                            userMessage: message,
                            model: this.serverConfig.ollama.model
                        };

                        const phpResponse = await fetch('bot-handler.php?action=call_ollama', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(phpPayload),
                            signal: AbortSignal.timeout(this.serverConfig.timeout)
                        });

                        if (!phpResponse.ok) {
                            throw new Error(`PHP proxy error: HTTP ${phpResponse.status}`);
                        }

                        const phpData = await phpResponse.json();

                        if (!phpData.success) {
                            throw new Error(phpData.error || 'PHP proxy returned error');
                        }

                        const botResponseContent = phpData.botResponse || "Sorry, I couldn't get a response.";

                        // Add bot message to chat history
                        chatHistory.push({ role: 'assistant', content: botResponseContent });

                        // Update chat history (keep last 20 messages to prevent memory issues)
                        if (chatHistory.length > 20) {
                            chatHistory.splice(0, chatHistory.length - 20);
                        }
                        this.chatHistories.set(botId, chatHistory);

                        return botResponseContent;
                    }
                }

            } catch (error) {
                console.error('Error in sendToOllama:', error);
                throw error;
            }
        },
        
        // Add a message to the chat
        addMessage: function(container, message, sender) {
            try {
                if (!container) {
                    console.error('Message container not found');
                    return;
                }
                
                const messageElement = document.createElement('div');
                messageElement.className = sender === 'user' ? 'user-message' : 'bot-message';
                
                let content = '';
                
                if (sender === 'bot') {
                    // Process markdown in bot messages (similar to bot.php)
                    let processedMessage = this.processMarkdown(message);
                    
                    content = `
                        <div class="bot-avatar">
                            <i class="fas fa-robot"></i>
                        </div>
                        <div class="message-content">${processedMessage}</div>
                    `;
                } else {
                    content = `
                        <div class="message-content">${this.escapeHtml(message)}</div>
                    `;
                }
                
                messageElement.innerHTML = content;
                container.appendChild(messageElement);
                
                // Scroll to bottom
                container.scrollTop = container.scrollHeight;
            } catch (error) {
                console.error('Error adding message:', error);
            }
        },
        
        // Process markdown (simplified version of marked.js functionality)
        processMarkdown: function(text) {
            try {
                // Use marked.js if available
                if (typeof marked !== 'undefined') {
                    return marked.parse(text);
                }
                
                // Simple fallback markdown processing
                let processed = this.escapeHtml(text);
                
                // Bold **text**
                processed = processed.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
                
                // Italic *text*
                processed = processed.replace(/\*(.*?)\*/g, '<em>$1</em>');
                
                // Code blocks ```code```
                processed = processed.replace(/```([\s\S]*?)```/g, '<pre class="code-block"><code>$1</code></pre>');
                
                // Inline code `code`
                processed = processed.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');
                
                // Line breaks
                processed = processed.replace(/\n/g, '<br>');
                
                return processed;
            } catch (error) {
                console.error('Error processing markdown:', error);
                return this.escapeHtml(text);
            }
        },
        
        // Add a system message
        addSystemMessage: function(container, message) {
            try {
                if (!container) {
                    console.error('System message container not found');
                    return;
                }
                
                const messageElement = document.createElement('div');
                messageElement.className = 'system-message';
                messageElement.textContent = message;
                
                container.appendChild(messageElement);
                
                // Scroll to bottom
                container.scrollTop = container.scrollHeight;
            } catch (error) {
                console.error('Error adding system message:', error);
            }
        },
        
        // Add thinking indicator
        addThinkingIndicator: function(container) {
            try {
                if (!container) {
                    console.error('Thinking indicator container not found');
                    return null;
                }
                
                const id = 'thinking-' + Math.random().toString(36).substring(2, 9);
                
                const thinkingElement = document.createElement('div');
                thinkingElement.className = 'bot-message thinking';
                thinkingElement.id = id;
                
                thinkingElement.innerHTML = `
                    <div class="bot-avatar">
                        <i class="fas fa-robot"></i>
                    </div>
                    <div class="message-content">
                        <span class="thinking-dots">
                            <span class="dot"></span>
                            <span class="dot"></span>
                            <span class="dot"></span>
                        </span>
                    </div>
                `;
                
                container.appendChild(thinkingElement);
                
                // Scroll to bottom
                container.scrollTop = container.scrollHeight;
                
                return id;
            } catch (error) {
                console.error('Error adding thinking indicator:', error);
                return null;
            }
        },
        
        // Remove thinking indicator
        removeThinkingIndicator: function(id) {
            try {
                if (!id) return;
                
                const element = document.getElementById(id);
                if (element) {
                    element.remove();
                }
            } catch (error) {
                console.error('Error removing thinking indicator:', error);
            }
        },
        
        // Escape HTML to prevent XSS
        escapeHtml: function(text) {
            try {
                if (typeof text !== 'string') {
                    return '';
                }
                
                return text
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;")
                    .replace(/"/g, "&quot;")
                    .replace(/'/g, "&#039;");
            } catch (error) {
                console.error('Error escaping HTML:', error);
                return '';
            }
        }
    };
    
    // Add CSS for the bot if not already present
    function addBotStyles() {
        if (document.getElementById('forum-bot-styles')) {
            return;
        }
        
        const styleEl = document.createElement('style');
        styleEl.id = 'forum-bot-styles';
        styleEl.textContent = `
            /* Enhanced styles for Ollama-powered forum bot */
            .forum-bot-container {
                border: 1px solid #e0e0e0;
                border-radius: 8px;
                overflow: hidden;
                margin: 15px 0;
                background-color: #fff;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
                font-family: inherit;
            }
            
            .forum-bot-header {
                background-color: #f5f5f5;
                padding: 10px 15px;
                border-bottom: 1px solid #e0e0e0;
                font-weight: bold;
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            
            .forum-bot-header i {
                margin-right: 8px;
                color: #2196F3;
            }
            
            /* Bot type toggle styles */
            .bot-type-toggle {
                display: flex;
                border-radius: 15px;
                overflow: hidden;
                background-color: #e0e0e0;
                margin-left: auto;
                border: 1px solid #ccc;
            }
            
            .toggle-label {
                padding: 3px 8px;
                cursor: pointer;
                font-size: 12px;
                display: flex;
                align-items: center;
                margin: 0;
                transition: background-color 0.2s;
            }
            
            .toggle-label input {
                position: absolute;
                opacity: 0;
                cursor: pointer;
                height: 0;
                width: 0;
            }
            
            .toggle-label input:checked + span {
                color: #fff;
                font-weight: bold;
            }
            
            .toggle-label:first-child input:checked + span {
                background-color: #4CAF50; /* Chat - Green */
            }
            
            .toggle-label:nth-child(2) input:checked + span {
                background-color: #2196F3; /* Auto - Blue */
            }
            
            .toggle-label:last-child input:checked + span {
                background-color: #FF9800; /* Code - Orange */
            }
            
            .toggle-label span {
                padding: 3px 8px;
                border-radius: 12px;
            }
            
            /* Bot status styles */
            .bot-status {
                margin-left: 10px;
                font-size: 12px;
                color: #666;
            }
            
            /* Forum bot messages container */
            .forum-bot-messages {
                height: 250px;
                overflow-y: auto;
                padding: 15px;
                display: flex;
                flex-direction: column;
                gap: 10px;
            }
            
            .bot-message, .user-message {
                display: flex;
                max-width: 80%;
            }
            
            .user-message {
                margin-left: auto;
                flex-direction: row-reverse;
            }
            
            .bot-avatar {
                width: 36px;
                height: 36px;
                background-color: #2196F3;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                margin-right: 8px;
            }
            
            .user-message .bot-avatar {
                margin-right: 0;
                margin-left: 8px;
            }
            
            .message-content {
                background-color: #f1f1f1;
                padding: 10px 15px;
                border-radius: 18px;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
                line-height: 1.4;
            }
            
            .user-message .message-content {
                background-color: #e3f2fd;
            }
            
            /* Enhanced message content styles for markdown */
            .message-content p {
                margin: 0.5em 0;
            }
            
            .message-content strong {
                font-weight: bold;
            }
            
            .message-content em {
                font-style: italic;
            }
            
            .message-content ul, .message-content ol {
                margin: 0.5em 0;
                padding-left: 1.5em;
            }
            
            .message-content h1, .message-content h2, .message-content h3,
            .message-content h4, .message-content h5, .message-content h6 {
                font-weight: bold;
                margin: 0.5em 0;
            }
            
            .message-content pre {
                background-color: #2d2d2d;
                color: #f8f8f2;
                padding: 10px;
                border-radius: 4px;
                overflow-x: auto;
                font-family: monospace;
                margin: 0.5em 0;
            }
            
            .message-content code {
                background-color: #f0f0f0;
                padding: 2px 4px;
                border-radius: 3px;
                font-family: monospace;
                font-size: 85%;
            }
            
            .message-content a {
                color: #2196F3;
                text-decoration: underline;
            }
            
            .message-content blockquote {
                border-left: 4px solid #ddd;
                padding-left: 1em;
                margin: 0.5em 0;
                color: #666;
                font-style: italic;
            }
            
            /* System messages */
            .system-message {
                text-align: center;
                font-size: 12px;
                color: #888;
                margin: 8px 0;
                font-style: italic;
            }
            
            /* Thinking animation */
            .thinking-dots {
                display: inline-flex;
                gap: 4px;
            }
            
            .thinking-dots .dot {
                width: 8px;
                height: 8px;
                background-color: #888;
                border-radius: 50%;
                animation: pulse 1.5s infinite;
            }
            
            .thinking-dots .dot:nth-child(2) {
                animation-delay: 0.2s;
            }
            
            .thinking-dots .dot:nth-child(3) {
                animation-delay: 0.4s;
            }
            
            @keyframes pulse {
                0%, 60%, 100% {
                    transform: scale(1);
                    opacity: 0.4;
                }
                20% {
                    transform: scale(1.2);
                    opacity: 1;
                }
            }
            
            /* Input area */
            .forum-bot-input {
                display: flex;
                padding: 10px;
                border-top: 1px solid #e0e0e0;
                background-color: #f9f9f9;
            }
            
            .forum-bot-input textarea {
                flex-grow: 1;
                border: 1px solid #e0e0e0;
                border-radius: 18px;
                padding: 8px 15px;
                resize: none;
                height: 38px;
                outline: none;
                font-family: inherit;
                font-size: 14px;
            }
            
            .bot-send-btn {
                width: 38px;
                height: 38px;
                border: none;
                background-color: #2196F3;
                color: white;
                border-radius: 50%;
                margin-left: 8px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: background-color 0.2s;
            }
            
            .bot-send-btn:hover {
                background-color: #1976D2;
            }
            
            /* Footer with connection status */
            .forum-bot-footer {
                padding: 8px 15px;
                background-color: #f5f5f5;
                border-top: 1px solid #e0e0e0;
                display: flex;
                justify-content: space-between;
                font-size: 12px;
                color: #666;
            }
            
            .bot-status-indicator {
                display: flex;
                align-items: center;
                gap: 5px;
            }
            
            .bot-status-indicator i {
                font-size: 10px;
            }
            
            .status-online {
                color: #4CAF50;
            }
            
            .status-offline {
                color: #F44336;
            }
            
            .status-unknown {
                color: #FFC107;
            }
            
            .bot-info {
                font-style: italic;
            }
            
            /* Dark theme support */
            [data-theme="dark"] .forum-bot-container {
                border-color: #444;
                background-color: #222;
            }
            
            [data-theme="dark"] .forum-bot-header {
                background-color: #333;
                border-color: #444;
                color: #eee;
            }
            
            [data-theme="dark"] .bot-type-toggle {
                background-color: #555;
                border-color: #666;
            }
            
            [data-theme="dark"] .toggle-label {
                color: #ccc;
            }
            
            [data-theme="dark"] .bot-status {
                color: #aaa;
            }
            
            [data-theme="dark"] .forum-bot-messages {
                background-color: #222;
            }
            
            [data-theme="dark"] .message-content {
                background-color: #333;
                color: #eee;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
            }
            
            [data-theme="dark"] .user-message .message-content {
                background-color: #1a3a5f;
            }
            
            [data-theme="dark"] .system-message {
                color: #aaa;
            }
            
            [data-theme="dark"] .forum-bot-input {
                background-color: #333;
                border-color: #444;
            }
            
            [data-theme="dark"] .forum-bot-input textarea {
                background-color: #444;
                border-color: #555;
                color: #eee;
            }
            
            [data-theme="dark"] .message-content code {
                background-color: #3a3a3a;
                color: #ddd;
            }
            
            [data-theme="dark"] .forum-bot-footer {
                background-color: #333;
                color: #aaa;
                border-color: #444;
            }
        `;
        
        document.head.appendChild(styleEl);
    }
    
    // Load marked.js for markdown processing if not already loaded
    function loadMarkedJs() {
        if (typeof marked !== 'undefined') {
            return Promise.resolve();
        }
        
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/marked/marked.min.js';
            script.onload = () => {
                console.log('Marked.js loaded for markdown processing');
                resolve();
            };
            script.onerror = () => {
                console.warn('Failed to load Marked.js, using fallback markdown processing');
                resolve(); // Don't reject, use fallback
            };
            document.head.appendChild(script);
        });
    }
    
    // Add styles
    addBotStyles();
    
    // Load markdown processor
    loadMarkedJs().then(() => {
        // Auto-initialize after a short delay to ensure DOM is ready
        setTimeout(() => {
            window.ForumBot.init();
        }, 500);
    });
    
    // Also set up a mutation observer to catch dynamically added bots
    const observer = new MutationObserver((mutations) => {
        let shouldInit = false;
        
        for (const mutation of mutations) {
            if (mutation.type === 'childList' && mutation.addedNodes.length) {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType === 1) { // Element node
                        if ((node.classList && node.classList.contains('forum-bot-container')) || 
                            node.querySelector('.forum-bot-container')) {
                            shouldInit = true;
                        }
                    }
                });
            }
        }
        
        if (shouldInit && window.ForumBot) {
            window.ForumBot.init();
        }
    });
    
    // Start observing the document body
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();