document.addEventListener("DOMContentLoaded", function () { const chatFab = document.getElementById("chat-fab"); const chatWindow = document.getElementById("chat-window"); const closeChatBtn = document.getElementById("close-chat"); const chatForm = document.getElementById("chat-form"); const chatInput = document.getElementById("chat-input"); const chatBody = document.getElementById("chat-body"); // --- Toggle Chat Window --- chatFab.addEventListener("click", () => { chatWindow.classList.toggle("open"); chatFab.classList.toggle("d-none"); }); closeChatBtn.addEventListener("click", () => { chatWindow.classList.remove("open"); chatFab.classList.remove("d-none"); }); // --- Handle Message Sending --- chatForm.addEventListener("submit", function (e) { e.preventDefault(); const messageText = chatInput.value.trim(); if (messageText) { // 1. Add user message to UI addMessage(messageText, "user"); chatInput.value = ""; chatBody.scrollTop = chatBody.scrollHeight; // 2. Get bot reply from API showTypingIndicator(); fetch('api/get_reply.php') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { hideTypingIndicator(); const botReply = data.reply || "Sorry, I couldn't get a response."; addMessage(botReply, "bot"); chatBody.scrollTop = chatBody.scrollHeight; }) .catch(error => { hideTypingIndicator(); console.error('Error fetching reply:', error); addMessage("Sorry, something went wrong. Please try again.", "bot"); chatBody.scrollTop = chatBody.scrollHeight; }); } }); function addMessage(text, type) { const messageElement = document.createElement("div"); messageElement.classList.add("chat-message", type); messageElement.textContent = text; chatBody.appendChild(messageElement); } function showTypingIndicator() { const typingIndicator = document.createElement("div"); typingIndicator.classList.add("chat-message", "bot", "typing-indicator"); typingIndicator.innerHTML = ''; chatBody.appendChild(typingIndicator); chatBody.scrollTop = chatBody.scrollHeight; } function hideTypingIndicator() { const typingIndicator = document.querySelector(".typing-indicator"); if (typingIndicator) { typingIndicator.remove(); } } // Add initial bot message setTimeout(() => { addMessage("Hi there! How can I help you today?", "bot"); }, 1000); });