const sendBtn = document.getElementById('send-btn');
const userInput = document.getElementById('user-input');
const apiKeyInput = document.getElementById('api-key-input');
const chatBox = document.getElementById('chat-box');


function showTypingIndicator() {
    const typingIndicatorDiv = document.createElement('div');
    typingIndicatorDiv.className = 'bot-message typing-indicator';
    typingIndicatorDiv.innerHTML = '<span>Typing...</span>';
    chatBox.appendChild(typingIndicatorDiv);
    scrollToBottom();
}

function removeTypingIndicator() {
    const typingIndicatorDiv = chatBox.querySelector('.typing-indicator');
    if (typingIndicatorDiv) {
        chatBox.removeChild(typingIndicatorDiv);
    }
}

const questionButtons = document.querySelectorAll('.question_btn');
questionButtons.forEach(btn => {
    console.log(btn)
    btn.addEventListener('click', function() {
        console.log("questionButtons clicked: ", this)
        const buttonTextContent = this.innerHTML; // Get the content of the button
        userInput.value = buttonTextContent; // Set the user input to the button's content
        sendBtn.click(); // Trigger the sending process
    });
});

sendBtn.addEventListener('click', () => {
    console.log("send clicked")
    const message = userInput.value.trim();
    const apiKey = apiKeyInput.value.trim();
    console.log("message: ", message)
    console.log("apiKey: ", apiKey)

    if (message && apiKey) {
        // Display user's message immediately
        const userMessageDiv = document.createElement('div');
        userMessageDiv.className = 'user-message';
        userMessageDiv.innerText = message;
        chatBox.appendChild(userMessageDiv);
        scrollToBottom();

        showTypingIndicator();

        // Call FastAPI backend to get response
        console.log("type: ", typeof message, typeof apiKey)
        fetch('/chat/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({user_input: message, api_key: apiKey})
        })
        .then(response => {
            console.log("response: ", response)
            if (!response.ok) {
                print(response)
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log("data: ", data)
            console.log("reply: ", data.response)
            // Convert Markdown response to HTML
            removeTypingIndicator();
            const botMessageHTML = marked.parse(data.response);
            // Display chatbot's response
            const botMessageDiv = document.createElement('div');
            botMessageDiv.className = 'bot-message';
            botMessageDiv.innerHTML = botMessageHTML;
            chatBox.appendChild(botMessageDiv);
            console.log("botMessageDiv", botMessageDiv)
            scrollToBottom();
        })
        .catch(error => {
            removeTypingIndicator();
            console.log('There was a problem with the fetch operation:', error.message);
        });

        userInput.value = ''; // Clear the input field
    }
});

function scrollToBottom() {
    chatBox.scrollTop = chatBox.scrollHeight;
}