window.addEventListener("DOMContentLoaded", () => { const form = document.getElementById("chat-form"); const input = document.getElementById("user-input"); const chatBox = document.getElementById("chat-box"); const historyList = document.getElementById("history-list"); const newChatBtn = document.getElementById("new-chat-btn"); // ✅ Use existing button let currentSession = null; // 📆 Format time function formatTime(iso) { try { const d = new Date(iso); return d.toLocaleString("en-IN", { hour: "numeric", minute: "2-digit", hour12: true, day: "2-digit", month: "short", year: "numeric", }); } catch (err) { console.error("Error formatting time:", err); return "(no date)"; } } // 💾 Load full chat of selected session async function loadSession(sessionId) { try { const res = await fetch(`/history/${sessionId}`, { method: "GET", headers: { "Content-Type": "application/json" }, }); if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch history`); const data = await res.json(); chatBox.innerHTML = ""; currentSession = sessionId; if (data.length === 0) { chatBox.innerHTML = `
No messages in this session yet.
`; } else { data.forEach(entry => { chatBox.innerHTML += `
You: ${entry.user}
Bot: ${entry.bot}
`; }); } chatBox.scrollTop = chatBox.scrollHeight; // Highlight active session [...historyList.children].forEach(li => li.classList.remove("active")); const activeLi = document.querySelector(`[data-id="${sessionId}"]`); if (activeLi) activeLi.classList.add("active"); } catch (err) { console.error(`Error loading session ${sessionId}:`, err); chatBox.innerHTML = `
⚠️ Could not load chat session: ${err.message}
`; } } // 📜 Load all session summaries async function loadHistory() { try { const res = await fetch("/sessions", { method: "GET", headers: { "Content-Type": "application/json" }, }); if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch sessions`); const sessions = await res.json(); historyList.innerHTML = ""; if (sessions.length === 0) { historyList.innerHTML = "
  • No chat sessions available.
  • "; return; } sessions.forEach(s => { const li = document.createElement("li"); li.className = "session-entry"; li.setAttribute("data-id", s.session_id); const formatted = s.created_at ? formatTime(s.created_at) : "(no date)"; li.innerHTML = ` ${formatted} `; // ✅ Load session on click li.querySelector(".session-text").addEventListener("click", () => loadSession(s.session_id)); // ✅ Delete session li.querySelector(".delete-btn").addEventListener("click", async (e) => { e.stopPropagation(); if (confirm("🗑️ Delete this chat session?")) { try { const res = await fetch(`/sessions/${s.session_id}`, { method: "DELETE", headers: { "Content-Type": "application/json" }, }); if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to delete session`); if (s.session_id === currentSession) { chatBox.innerHTML = `
    Chat session deleted.
    `; currentSession = null; } loadHistory(); } catch (err) { console.error(`Error deleting session ${s.session_id}:`, err); alert(`Failed to delete session: ${err.message}`); } } }); historyList.appendChild(li); }); // Load the current session if it exists if (currentSession) { loadSession(currentSession); } } catch (err) { console.error("Error loading sessions:", err); historyList.innerHTML = `
  • ⚠️ Failed to load chat sessions: ${err.message}
  • `; } } // 📝 Handle new message submission form.addEventListener("submit", async (e) => { e.preventDefault(); const message = input.value.trim(); if (!message) return; chatBox.innerHTML += `
    You: ${message}
    `; input.value = ""; input.disabled = true; chatBox.scrollTop = chatBox.scrollHeight; try { const response = await fetch("/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message }), }); if (!response.ok) throw new Error(`HTTP ${response.status}: Failed to send message`); const data = await response.json(); const botResponse = data.response || data.error || "⚠️ No response"; chatBox.innerHTML += `
    Bot: ${botResponse}
    `; chatBox.scrollTop = chatBox.scrollHeight; loadHistory(); // Refresh session list to include new messages } catch (error) { console.error("Error sending message:", error); chatBox.innerHTML += `
    ⚠️ Error getting response: ${error.message}
    `; } input.disabled = false; input.focus(); }); // ➕ Create new chat session newChatBtn.addEventListener("click", async () => { try { const res = await fetch("/new_session", { method: "GET", headers: { "Content-Type": "application/json" }, }); if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to create new session`); const data = await res.json(); currentSession = data.session_id; chatBox.innerHTML = `
    New chat session started.
    `; await loadHistory(); await loadSession(currentSession); } catch (err) { console.error("Error creating new session:", err); chatBox.innerHTML = `
    ⚠️ Failed to create new session: ${err.message}
    `; } }); // 🚀 Initialize: Load current session history async function init() { try { const res = await fetch("/history", { method: "GET", headers: { "Content-Type": "application/json" }, }); if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to fetch current session`); const data = await res.json(); if (data.length > 0) { currentSession = data[0].session_id; // Assume session_id is consistent in backend await loadSession(currentSession); } await loadHistory(); } catch (err) { console.error("Error initializing:", err); chatBox.innerHTML = `
    ⚠️ Could not initialize chat: ${err.message}
    `; } } init(); });