document.addEventListener('DOMContentLoaded', () => {
    const chatBox = document.querySelector('.chat-box');
    const chatInput = document.querySelector('.chat-input input');
    const sendButton = document.querySelector('.chat-input button');

    sendButton.addEventListener('click', sendMessage);
    chatInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    function sendMessage() {
        const messageText = chatInput.value.trim();
        if (messageText === '') return;

        addMessage(messageText, 'sent');
        chatInput.value = '';

        getAIResponse(messageText);
    }

    async function getAIResponse(message) {
        const SERVER_URL = 'http://localhost:3000/api/chat';

        try {
            const response = await fetch(SERVER_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message })
            });

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

            const data = await response.json();
            const botMessage = data.candidates[0].content.parts[0].text;
            addMessage(botMessage, 'received');

        } catch (error) {
            console.error('Error fetching AI response:', error);
            addMessage('Lo siento, no pude obtener una respuesta. Por favor, inténtalo de nuevo.', 'received');
        }
    }

    function addMessage(text, type) {
        const messageElement = document.createElement('div');
        messageElement.classList.add('chat-message', type);

        const paragraphElement = document.createElement('p');
        paragraphElement.textContent = text;

        messageElement.appendChild(paragraphElement);
        chatBox.appendChild(messageElement);
        chatBox.scrollTop = chatBox.scrollHeight;
    }
});


