const chatContainer = document.getElementById('chat-container');
let lastMessageCount = 0;

function fetchChatMessages() {
    fetch('http://127.0.0.1:5000/chat')
        .then(response => response.json())
        .then(messages => {
            // Only append new messages
            if (messages.length > lastMessageCount) {
                for (let i = lastMessageCount; i < messages.length; i++) {
                    const messageData = messages[i];
                    const messageElement = document.createElement('div');
                    messageElement.classList.add('chat-message');

                    const authorElement = document.createElement('span');
                    authorElement.classList.add('chat-author');
                    authorElement.style.color = messageData.author_color; // Apply author color
                    authorElement.textContent = `${messageData.author}: `;

                    const textElement = document.createElement('span');
                    textElement.classList.add('chat-text');
                    // Basic rich markup conversion (e.g., [blue]text[/blue] to <span class="blue-text">text</span>)
                    let formattedMessage = messageData.message;
                    formattedMessage = formattedMessage.replace(/\[magenta\](.*?)\[\/magenta\]/g, '<span class="emoji">$1</span>');
                    formattedMessage = formattedMessage.replace(/\[blue\](.*?)\[\/blue\]/g, '<span class="blue-text">$1</span>');
                    textElement.innerHTML = formattedMessage;

                    messageElement.appendChild(authorElement);
                    messageElement.appendChild(textElement);
                    chatContainer.prepend(messageElement); // Add new messages to the top (due to flex-direction: column-reverse)

                    // Keep only a certain number of messages visible
                    while (chatContainer.children.length > 50) { // Keep last 50 messages
                        chatContainer.removeChild(chatContainer.lastChild);
                    }
                }
                lastMessageCount = messages.length;
            }
        })
        .catch(error => console.error('Error fetching chat messages:', error));
}

// Fetch messages every 1 second
setInterval(fetchChatMessages, 1000);

// Initial fetch
fetchChatMessages();
