document.addEventListener("DOMContentLoaded", () => { const chatBox = document.getElementById("chatBox"); const input = document.getElementById("userInput"); const micBtn = document.getElementById("micBtn"); // Append a message to the chat box 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; } // Send message to backend async function sendMessage() { const message = input.value.trim(); if (!message) return; appendMessage(message, "user"); input.value = ""; const loadingMsg = document.createElement("div"); loadingMsg.className = "bot-message"; loadingMsg.innerText = "Loading..."; chatBox.appendChild(loadingMsg); chatBox.scrollTop = chatBox.scrollHeight; try { const res = await fetch("/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question: message }) }); const data = await res.json(); loadingMsg.remove(); appendMessage(data.answer || "❌ No response from AI.", "bot"); } catch (err) { loadingMsg.remove(); appendMessage("❌ Failed to get response: " + err.message, "bot"); } } // Make sendMessage available globally for
window.sendMessage = sendMessage; // Submit on Enter key (in case form fallback fails) input.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); sendMessage(); } }); // Voice input (mic) 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."; } });