let chatId = '';

document.addEventListener("DOMContentLoaded", async () => {
    const newChatBtn = document.getElementById("new-chat-btn");
    const chatList = document.getElementById("chat-list");
    const form = document.getElementById('chat-form');
    const promptInput = document.getElementById('prompt');
    const chatLog = document.getElementById('chat-log');
    const sendBtn = document.getElementById('send-btn');
    const spinner = document.getElementById('spinner');
    const thinkingText = document.getElementById('thinking-text');

    await loadHistory();

    async function loadHistory() {
        try {
            const response = await fetch("/api/v1/chats", { method: "GET" });
            const data = await response.json();

            chatList.innerHTML = "";

            data.forEach(chat => {
                const li = document.createElement("li");
                li.textContent = chat.name;
                li.setAttribute("data-chat-id", chat.id);
                if (chat.id === chatId) {
                    li.classList.add("active");
                }

                li.addEventListener("click", async () => {
                    const selectedId = chat.id;
                    if (selectedId !== chatId) {
                        chatId = selectedId;
                        highlightActiveChat(li);
                        await loadMessages(chatId);
                    }
                });

                chatList.appendChild(li);
            });

            // Autoabrir primer chat si no hay chatId activo
            if (!chatId && data.length > 0) {
                chatId = data[0].id;
                const firstLi = chatList.querySelector('li');
                if (firstLi) {
                    firstLi.classList.add("active");
                    await loadMessages(chatId);
                }
            }

        } catch (error) {
            console.error("Error cargando historial:", error);
        }
    }

    async function loadMessages(chatId) {
        try {
            const response = await fetch(`/api/v1/chats/${chatId}`);
            const messages = await response.json();

            chatLog.innerHTML = "";

            messages.forEach(msg => {
                appendMessage(msg.role, msg.text, msg.date);
            });

        } catch (error) {
            appendMessage("bot", "❌ Error cargando mensajes del chat.");
            console.error("Error al cargar mensajes:", error);
        }
    }

    function highlightActiveChat(selectedLi) {
        const lis = chatList.querySelectorAll("li");
        lis.forEach(li => li.classList.remove("active"));
        selectedLi.classList.add("active");
    }

    function appendMessage(role, text, date) {
        const bubble = document.createElement('div');
        bubble.className = `bubble ${role}`;
        bubble.textContent = text;
        chatLog.appendChild(bubble);

        const timestamp = document.createElement('em');
        timestamp.className = 'timestamp';
        timestamp.textContent = date;
        bubble.appendChild(timestamp);

        chatLog.scrollTop = chatLog.scrollHeight;
    }

    async function createNewChat() {
        try {
            const response = await fetch("/api/v1/chats", {
                method: "POST"
            });
            chatId = await response.text();

            await loadHistory();
            await loadMessages(chatId);

            const li = chatList.querySelector(`li[data-chat-id="${chatId}"]`);
            if (li) highlightActiveChat(li);

        } catch (error) {
            console.error("Error al crear nuevo chat:", error);
            appendMessage("bot", "❌ Error creando nuevo chat.");
        }
    }
    newChatBtn.addEventListener("click", async () => {
        await createNewChat()
    });

    form.addEventListener('submit', async function (e) {
        e.preventDefault();

        if (chatId === undefined || chatId === null || chatId === '') {
            await createNewChat();
        }

        const prompt = promptInput.value.trim();
        if (!prompt) return;

        appendMessage("user", prompt, formatDate(new Date()));
        promptInput.value = "";
        sendBtn.disabled = true;
        spinner.style.display = 'block';
        thinkingText.style.display = 'block';

        try {
            const response = await fetch(`/api/v1/chats/${chatId}`, {
                method: "PUT",
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({ prompt })
            });

            const data = await response.json();
            chatId = data.chatId;

            appendMessage("bot", data.text, data.date);

            await loadHistory();

        } catch (error) {
            appendMessage("bot", "❌ Error procesando la respuesta.");
            console.error(error);
        } finally {
            sendBtn.disabled = false;
            spinner.style.display = 'none';
            thinkingText.style.display = 'none';
        }
    });

    function formatDate(date) {
        const day = date.getDate().toString().padStart(2, '0');
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const year = date.getFullYear();
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');

        return `${day}/${month}/${year} ${hours}:${minutes}`;
    }
});