const chatForm = document.getElementById("chat-form"); const userInput = document.getElementById("user-input"); const chatBox = document.getElementById("chat-box"); const orderIdEl = document.getElementById("order_id"); const categoryEl = document.getElementById("category"); const sentimentEl = document.getElementById("sentiment"); const negativeBox = document.getElementById("negative-box"); let sentimentChart = null; // 🧠 Append User Message function appendUser(text) { chatBox.innerHTML += `
🧑 You: ${text}
`; chatBox.scrollTop = chatBox.scrollHeight; } // 🤖 Append Bot Message function appendBot(text) { chatBox.innerHTML += `🤖 Bot: ${text}
`; chatBox.scrollTop = chatBox.scrollHeight; } // ⭐ Send chat message chatForm.addEventListener("submit", async (e) => { e.preventDefault(); const text = userInput.value.trim(); const order_id = orderIdEl.value.trim(); if (!text) return; appendUser(text); userInput.value = ""; try { const res = await fetch("/chat", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ user_input: text, order_id }) }); const data = await res.json(); if (data.error) { appendBot("Sorry, could not process your message."); return; } appendBot(data.reply); categoryEl.textContent = data.category || "—"; sentimentEl.textContent = `${data.sentiment || "—"} (${data.confidence || 0}%)`; await updateAnalytics(); await updateNegatives(); } catch (err) { console.error(err); appendBot("Network error — try again."); } }); // 📊 Update Analytics Charts async function updateAnalytics() { const res = await fetch("/analytics"); const data = await res.json(); const ctx = document.getElementById("sentimentChart"); if (sentimentChart) sentimentChart.destroy(); sentimentChart = new Chart(ctx, { type: "pie", data: { labels: data.labels, datasets: [{ data: data.values, backgroundColor: ["#2ecc71", "#e74c3c", "#f1c40f"] }] } }); } // ⚠️ Update Negative Messages Box async function updateNegatives() { if (!negativeBox) return; // Safety check const res = await fetch("/admin/negatives-data"); const data = await res.json(); negativeBox.innerHTML = data.length === 0 ? "No negative messages yet.
" : data.map(msg => `⚠️ ${msg.username}: ${msg.message}
` ).join(""); } // auto-refresh negative messages setInterval(updateNegatives, 8000);