document.addEventListener('DOMContentLoaded', function () { const chatWindow = document.getElementById('chat-window'); const chatToggleButton = document.getElementById('chat-toggle-button'); const chatCloseButton = document.getElementById('chat-close-button'); const chatForm = document.getElementById('chat-form'); const chatInput = document.getElementById('chat-input'); const chatMessages = document.getElementById('chat-messages'); const toggleChat = (forceState) => { const isOpen = chatWindow.classList.contains('open'); const show = forceState !== undefined ? forceState : !isOpen; if (show) { chatWindow.classList.add('open'); chatToggleButton.style.display = 'none'; } else { chatWindow.classList.remove('open'); chatToggleButton.style.display = 'flex'; } }; chatToggleButton.addEventListener('click', () => toggleChat(true)); chatCloseButton.addEventListener('click', () => toggleChat(false)); const addMessage = (text, type, isTyping = false) => { const messageDiv = document.createElement('div'); messageDiv.classList.add('message', type); const contentDiv = document.createElement('div'); contentDiv.classList.add('message-content'); contentDiv.textContent = text; messageDiv.appendChild(contentDiv); if (isTyping) { messageDiv.id = 'typing-indicator'; messageDiv.classList.add('typing'); } chatMessages.appendChild(messageDiv); chatMessages.scrollTop = chatMessages.scrollHeight; return messageDiv; }; chatForm.addEventListener('submit', async (e) => { e.preventDefault(); const userInput = chatInput.value.trim(); if (!userInput) return; addMessage(userInput, 'sent'); chatInput.value = ''; chatInput.disabled = true; const typingIndicator = addMessage('Festverse AI is typing...', 'received', true); try { const response = await fetch('api/ai_chat.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: userInput }), }); if (!response.ok) { throw new Error('Network response was not ok.'); } const data = await response.json(); typingIndicator.remove(); if (data.reply) { addMessage(data.reply, 'received'); } else { addMessage('Sorry, I encountered an error. Please try again.', 'received'); } } catch (error) { console.error('Chat error:', error); typingIndicator.remove(); addMessage('Sorry, I could not connect to the AI assistant.', 'received'); } finally { chatInput.disabled = false; chatInput.focus(); } }); });