document.addEventListener("DOMContentLoaded", () => { const chatBox = document.getElementById("chatBox"); const input = document.getElementById("userInput"); const micBtn = document.getElementById("micBtn"); let isWaiting = false; function appendMessage(text, sender = "bot") { const msg = document.createElement("div"); msg.className = sender === "bot" ? "bot-message" : "user-message"; msg.innerText = text; chatBox.appendChild(msg); chatBox.scrollTop = chatBox.scrollHeight; } async function sendMessage() { if (isWaiting) return; const message = input.value.trim(); if (!message) return; appendMessage(message, "user"); input.value = ""; isWaiting = true; const loadingMsg = document.createElement("div"); loadingMsg.className = "bot-message"; loadingMsg.innerText = "Loading..."; chatBox.appendChild(loadingMsg); chatBox.scrollTop = chatBox.scrollHeight; try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 30000); // optional 30s timeout const res = await fetch("/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question: message }), signal: controller.signal }); clearTimeout(timeoutId); const data = await res.json(); loadingMsg.remove(); appendMessage(data.answer || "❌ No response from AI.", "bot"); } catch (err) { loadingMsg.remove(); appendMessage("❌ Error: " + (err.message || "Unknown error"), "bot"); } finally { isWaiting = false; } } window.sendMessage = sendMessage; input.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); sendMessage(); } }); // Voice support if ("webkitSpeechRecognition" in window || "SpeechRecognition" in window) { const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)(); recognition.lang = "en-IN"; recognition.onstart = () => appendMessage("🎙️ Listening...", "bot"); recognition.onresult = (e) => { const transcript = e.results[0][0].transcript; input.value = transcript; sendMessage(); }; recognition.onerror = (e) => { appendMessage("⚠️ Mic error: " + e.error, "bot"); }; micBtn.onclick = () => recognition.start(); } else { micBtn.disabled = true; micBtn.title = "🎤 Voice input not supported in this browser."; } });