ChatBot / index.html
Ahmad140's picture
Update index.html
bd678bc verified
Raw History Blame Contribute Delete
35.5 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Elite Visuals AI – Smart Invoice & Final Report</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;400;500;600;700&display=swap" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: linear-gradient(135deg, #f5f7fa 0%, #e9eef5 100%); font-family: 'Inter', sans-serif; height: 100vh; overflow: hidden; }
/* Chat Icon (Floating Button) */
.chat-icon {
position: fixed;
bottom: 28px;
right: 28px;
width: 64px;
height: 64px;
background: linear-gradient(145deg, #25D366, #128C7E);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 10px 25px rgba(0,0,0,0.2);
animation: pulse 1.8s infinite;
z-index: 1000;
transition: all 0.3s ease;
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(37,211,102,0.5); }
70% { box-shadow: 0 0 0 15px rgba(37,211,102,0); }
100% { box-shadow: 0 0 0 0 rgba(37,211,102,0); }
}
.chat-icon:hover {
transform: scale(1.08);
background: #20b859;
}
.chat-icon i {
font-size: 32px;
color: white;
}
/* Chat Modal */
.chat-modal {
position: fixed;
bottom: 100px;
right: 28px;
width: 580px;
height: 680px;
background: rgba(255,255,255,0.98);
border-radius: 28px;
box-shadow: 0 25px 50px -12px rgba(0,0,0,0.35);
display: none;
flex-direction: column;
overflow: hidden;
z-index: 1001;
animation: slideUpFade 0.3s ease-out;
}
@keyframes slideUpFade {
from { opacity: 0; transform: translateY(30px); }
to { opacity: 1; transform: translateY(0); }
}
.chat-header {
background: linear-gradient(135deg, #075E54, #0b3b32);
color: white;
padding: 12px 18px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header-buttons {
display: flex;
gap: 10px;
align-items: center;
}
.header-btn {
background: rgba(255,255,255,0.2);
border: none;
width: 32px;
height: 32px;
border-radius: 50%;
cursor: pointer;
color: white;
transition: 0.2s;
display: inline-flex;
align-items: center;
justify-content: center;
}
.header-btn:hover {
transform: scale(1.05);
background: rgba(255,255,255,0.4);
}
.chat-invoice-container {
display: flex;
flex: 1;
overflow: hidden;
transition: all 0.3s ease;
}
.chat-column {
flex: 1.5;
display: flex;
flex-direction: column;
background: #f0f2f5;
transition: all 0.3s ease;
}
.invoice-column {
width: 40%;
background: #fff8f0;
border-left: 1px solid #ddd;
display: flex;
flex-direction: column;
overflow-y: auto;
padding: 12px;
gap: 12px;
transition: all 0.3s ease;
}
.invoice-column.hidden {
display: none;
width: 0;
padding: 0;
}
.chat-column.expanded {
flex: 1;
}
.invoice-title {
font-weight: 700;
font-size: 1rem;
color: #075E54;
border-bottom: 2px solid #25D366;
padding-bottom: 6px;
margin-bottom: 8px;
display: flex;
justify-content: space-between;
align-items: center;
}
.invoice-items {
flex: 1;
overflow-y: auto;
max-height: 280px;
}
.invoice-item {
background: white;
border-radius: 12px;
padding: 8px 12px;
margin-bottom: 8px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}
.invoice-item-name {
font-weight: 500;
font-size: 0.8rem;
}
.invoice-item-price {
font-size: 0.8rem;
color: #2d6a4f;
font-weight: 600;
}
.remove-item {
color: #e63946;
cursor: pointer;
font-size: 14px;
transition: 0.2s;
}
.remove-item:hover {
transform: scale(1.1);
}
.invoice-total {
border-top: 2px dashed #ccc;
padding-top: 10px;
margin-top: 8px;
font-weight: 700;
font-size: 0.9rem;
display: flex;
justify-content: space-between;
}
.empty-invoice {
color: #888;
font-size: 0.75rem;
text-align: center;
padding: 20px;
}
.final-report-btn, .download-report-btn {
background: #25D366;
color: white;
border: none;
border-radius: 25px;
padding: 8px 12px;
font-size: 0.75rem;
font-weight: 600;
cursor: pointer;
transition: 0.2s;
width: 100%;
margin-top: 8px;
}
.download-report-btn {
background: #2a6d4c;
margin-top: 4px;
}
.final-report-btn:hover {
background: #128C7E;
transform: scale(1.02);
}
.download-report-btn:hover {
background: #1e5a3e;
transform: scale(1.02);
}
.chat-messages {
flex: 1;
padding: 12px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 12px;
}
.message {
max-width: 85%;
padding: 8px 12px;
border-radius: 18px;
font-size: 0.8rem;
line-height: 1.4;
white-space: pre-line;
animation: fadeIn 0.2s;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(5px); }
to { opacity: 1; transform: translateY(0); }
}
.user-msg {
background: #DCF8C6;
margin-left: auto;
border-bottom-right-radius: 4px;
}
.bot-msg {
background: white;
margin-right: auto;
border-bottom-left-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.bot-message-wrapper {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
max-width: 85%;
margin-right: auto;
}
.bot-message-wrapper .message {
margin: 0;
max-width: 100%;
}
.confirm-btn {
background: #25D366;
color: white;
border: none;
border-radius: 20px;
padding: 4px 12px;
font-size: 0.7rem;
cursor: pointer;
transition: 0.2s;
display: inline-flex;
align-items: center;
gap: 4px;
}
.confirm-btn:hover {
background: #128C7E;
transform: scale(1.02);
}
.live-widget {
background: white;
border-radius: 16px;
margin: 8px 8px 0 8px;
overflow: hidden;
box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}
.widget-header {
background: linear-gradient(135deg, #1e2a3a, #0f172a);
color: white;
padding: 8px 12px;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.75rem;
font-weight: 600;
}
.widget-controls {
display: flex;
gap: 10px;
}
.widget-controls button {
background: rgba(255,255,255,0.2);
border: none;
color: white;
border-radius: 20px;
padding: 2px 8px;
font-size: 0.7rem;
cursor: pointer;
transition: 0.2s;
}
.widget-controls button:hover {
background: rgba(255,255,255,0.4);
}
.toggle-widget {
cursor: pointer;
margin-left: 8px;
}
.widget-content {
padding: 10px;
display: none;
background: #fef9e6;
font-size: 0.7rem;
}
.widget-content.show {
display: block;
}
.info-row {
margin: 4px 0;
}
.info-label {
font-weight: 700;
color: #075E54;
}
.questions-container {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 8px;
}
.question-bubble {
background: #e4e6eb;
padding: 4px 10px;
border-radius: 16px;
font-size: 0.7rem;
cursor: pointer;
transition: 0.2s;
}
.question-bubble:hover {
background: #d1d4db;
transform: translateY(-1px);
}
.typing-indicator {
background: white;
padding: 6px 12px;
border-radius: 20px;
display: inline-flex;
gap: 4px;
width: fit-content;
}
.typing-indicator span {
width: 6px;
height: 6px;
background: #888;
border-radius: 50%;
animation: wave 1.2s infinite;
}
@keyframes wave {
0%,60%,100% { transform: translateY(0); opacity: 0.4; }
30% { transform: translateY(-4px); opacity: 1; }
}
.chat-input-area {
display: flex;
padding: 10px;
background: white;
border-top: 1px solid #ddd;
gap: 8px;
}
.chat-input-area input {
flex: 1;
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 30px;
outline: none;
font-size: 0.8rem;
}
.chat-input-area button {
background: #25D366;
border: none;
width: 36px;
height: 36px;
border-radius: 50%;
color: white;
cursor: pointer;
}
.media-panel {
background: #f0f2f5;
border-radius: 16px;
padding: 12px;
margin: 10px 0;
display: none;
}
.media-panel textarea {
width: 100%;
padding: 8px;
border-radius: 12px;
border: 1px solid #ccc;
}
.media-panel input[type="file"] {
margin: 8px 0;
}
.image-preview {
max-width: 100%;
max-height: 150px;
margin-top: 8px;
}
</style>
</head>
<body>
<!-- Floating Chat Icon (VISIBLE) -->
<div class="chat-icon" id="chatIcon">
<i class="fas fa-comment-dots"></i>
</div>
<!-- Chat Modal -->
<div class="chat-modal" id="chatModal">
<div class="chat-header">
<h3><i class="fas fa-robot"></i> Elite Visuals AI</h3>
<div class="header-buttons">
<button class="header-btn" id="toggleInvoiceBtn" title="Toggle Invoice Panel"><i class="fas fa-eye-slash"></i></button>
<button class="header-btn" id="closeChat"><i class="fas fa-times"></i></button>
</div>
</div>
<div class="chat-invoice-container" id="chatInvoiceContainer">
<div class="chat-column" id="chatColumn">
<div class="chat-messages" id="chatMessages">
<div class="message bot-msg">✨ Assalam-o-Alaikum! I can help you with website packages, extra features, and **step-by-step project building**. To start a new project, simply say: **"I want to build a website"** – I'll ask you all the requirements and then generate a proposal, project ID, and total invoice. You can also ask about packages or use the confirm buttons below.</div>
<div class="live-widget" id="liveWidget">
<div class="widget-header">
<span><i class="fas fa-chart-line"></i> 📊 Live Quote</span>
<div class="widget-controls">
<button id="hideWidgetBtn"><i class="fas fa-eye-slash"></i> Hide</button>
<button id="unhideWidgetBtn" style="display: none;"><i class="fas fa-eye"></i> Show</button>
<i class="fas fa-chevron-down toggle-widget" id="toggleIcon"></i>
</div>
</div>
<div class="widget-content" id="widgetContent">
<p id="widgetEmptyMsg">💡 Ask about a package/feature to see details.</p>
<div id="widgetDetails" style="display: none;"></div>
</div>
</div>
<div id="defaultQuestionsContainer" class="questions-container"></div>
</div>
<div class="chat-input-area">
<input type="text" id="userInput" placeholder="Ask about price, timeline, confirm Basic, add SEO, or say 'I want to build a website'...">
<button id="sendBtn"><i class="fas fa-paper-plane"></i></button>
</div>
</div>
<div class="invoice-column" id="invoiceColumn">
<div class="invoice-title">
<span>🧾 Your Quote</span>
</div>
<div class="invoice-items" id="invoiceItems">
<div class="empty-invoice">✨ No services selected yet.<br>Ask or confirm a package to add.</div>
</div>
<div class="invoice-total" id="invoiceTotal">
<span>Subtotal:</span>
<span id="totalAmount">PKR 0</span>
</div>
<button class="final-report-btn" id="finalReportBtn"><i class="fas fa-file-alt"></i> Generate Final Report</button>
<button class="download-report-btn" id="downloadReportBtn"><i class="fas fa-download"></i> Download Report</button>
</div>
</div>
</div>
<script>
// ---------- Session ----------
let sessionId = localStorage.getItem('chat_session_id');
if (!sessionId) {
sessionId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 8);
localStorage.setItem('chat_session_id', sessionId);
}
const API_URL = "/api/chat";
const DEFAULT_QUESTIONS = [
"Basic website price and timeline?",
"Standard package details",
"Premium package details",
"Extra: live chat cost increase?",
"Add e-commerce to my quote",
"I want to build a website",
"Contact number"
];
let storedProjectId = localStorage.getItem(`project_id_${sessionId}`) || null;
let invoiceItems = [];
let nextId = 1;
function parsePrice(priceStr) {
let match = priceStr.match(/(\d[\d,]+)/);
if (match) return parseInt(match[0].replace(/,/g, ''));
return 0;
}
function parseTimelineDays(timelineStr) {
if (!timelineStr) return 0;
let match = timelineStr.match(/(\d+)\s*-\s*(\d+)\s*days?/);
if (match) return parseInt(match[2]);
match = timelineStr.match(/(\d+)\s*days?/);
if (match) return parseInt(match[1]);
return 0;
}
function updateInvoiceDisplay() {
const container = document.getElementById('invoiceItems');
const totalSpan = document.getElementById('totalAmount');
if (invoiceItems.length === 0) {
container.innerHTML = '<div class="empty-invoice">✨ No services selected yet.<br>Ask or confirm a package to add.</div>';
totalSpan.innerText = 'PKR 0';
return;
}
let html = '';
let total = 0;
invoiceItems.forEach(item => {
const priceNum = parsePrice(item.price);
total += priceNum;
html += `
<div class="invoice-item" data-id="${item.id}">
<div class="invoice-item-name">${item.name}</div>
<div style="display: flex; align-items: center; gap: 12px;">
<span class="invoice-item-price">${item.price}</span>
<span class="remove-item" data-id="${item.id}"><i class="fas fa-times-circle"></i></span>
</div>
</div>
`;
});
container.innerHTML = html;
totalSpan.innerText = `PKR ${total.toLocaleString()}`;
document.querySelectorAll('.remove-item').forEach(el => {
el.addEventListener('click', (e) => {
const id = parseInt(el.dataset.id);
removeInvoiceItem(id);
});
});
}
function removeInvoiceItem(id) {
invoiceItems = invoiceItems.filter(item => item.id !== id);
updateInvoiceDisplay();
}
function addInvoiceItem(serviceName, priceStr, serviceKey = null, timelineDays = null) {
if (serviceKey && invoiceItems.some(item => item.serviceKey === serviceKey)) return false;
const newItem = { id: nextId++, name: serviceName, price: priceStr, serviceKey: serviceKey || serviceName, timelineDays: timelineDays };
invoiceItems.push(newItem);
updateInvoiceDisplay();
return true;
}
// Auto-add from bot messages (NOW DISABLED – only manual confirm buttons)
function autoAddFromBotMessage(text) {
// Only extract Project ID – DO NOT automatically add any service
const match = text.match(/Project ID:\s*`([A-Z0-9\-]+)`/i);
if (match) {
storedProjectId = match[1];
localStorage.setItem(`project_id_${sessionId}`, storedProjectId);
}
// No automatic additions anymore!
}
// ---------- Media Upload ----------
let mediaPanel = null;
function createMediaPanel() {
if (mediaPanel) return;
const chatArea = document.getElementById('chatMessages');
const panel = document.createElement('div');
panel.className = 'media-panel';
panel.innerHTML = `
<label>Additional Notes (text):</label>
<textarea id="mediaText" rows="2" placeholder="Type any notes..."></textarea>
<label>Upload Image (optional):</label>
<input type="file" id="mediaImage" accept="image/*">
<img id="mediaPreview" class="image-preview" style="display:none;">
<button id="mediaSubmitBtn" class="confirm-btn" style="margin-top:8px;">Submit Media</button>
`;
chatArea.appendChild(panel);
mediaPanel = panel;
const mediaTextarea = document.getElementById('mediaText');
const mediaFileInput = document.getElementById('mediaImage');
const mediaImagePreview = document.getElementById('mediaPreview');
const submitBtn = document.getElementById('mediaSubmitBtn');
mediaFileInput.onchange = () => {
const file = mediaFileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
mediaImagePreview.src = e.target.result;
mediaImagePreview.style.display = 'block';
};
reader.readAsDataURL(file);
} else {
mediaImagePreview.style.display = 'none';
}
};
submitBtn.onclick = async () => {
const text = mediaTextarea.value.trim();
let imageBase64 = '';
if (mediaFileInput.files[0]) {
const file = mediaFileInput.files[0];
imageBase64 = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.readAsDataURL(file);
});
}
try {
const res = await fetch('/api/upload_media', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ session_id: sessionId, text: text, image: imageBase64 })
});
const data = await res.json();
if (data.status === 'ok') {
userInput.value = "DONE";
sendMessage();
mediaPanel.style.display = 'none';
} else {
alert("Failed to upload media");
}
} catch (err) {
alert("Upload error");
}
};
}
function showMediaPanel() {
if (!mediaPanel) createMediaPanel();
mediaPanel.style.display = 'block';
}
// ---------- Message Functions ----------
function addMessageWithConfirm(text, sender, widgetData = null) {
const chatMessagesDiv = document.getElementById('chatMessages');
if (sender === 'user') {
const div = document.createElement('div');
div.className = 'message user-msg';
div.innerText = text;
chatMessagesDiv.appendChild(div);
chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
return;
}
const wrapper = document.createElement('div');
wrapper.className = 'bot-message-wrapper';
const msgDiv = document.createElement('div');
msgDiv.className = 'message bot-msg';
msgDiv.innerText = text;
wrapper.appendChild(msgDiv);
// Check for media request
if (text.startsWith("MEDIA_REQUEST|")) {
const cleanMsg = text.replace("MEDIA_REQUEST|", "");
msgDiv.innerText = cleanMsg;
showMediaPanel();
} else {
// Only extract Project ID, no auto-add
autoAddFromBotMessage(text);
}
let serviceName = null, servicePrice = null, serviceKey = null, timelineStr = null;
if (widgetData) {
if (widgetData.package) {
serviceName = `${widgetData.package} Website Package`;
servicePrice = widgetData.price;
serviceKey = `pkg_${widgetData.package}`;
timelineStr = widgetData.timeline;
} else if (widgetData.service) {
serviceName = widgetData.service;
servicePrice = widgetData.price;
serviceKey = `svc_${widgetData.service}`;
timelineStr = widgetData.timeline;
} else if (widgetData.extra_feature) {
serviceName = `Extra: ${widgetData.extra_feature}`;
servicePrice = widgetData.extra_cost;
serviceKey = `extra_${widgetData.extra_feature}`;
timelineStr = widgetData.extra_timeline;
}
}
// Add a confirm button for packages/extra features (manual addition)
if (serviceName && servicePrice) {
const confirmBtn = document.createElement('button');
confirmBtn.className = 'confirm-btn';
confirmBtn.innerHTML = '<i class="fas fa-check-circle"></i> Confirm & Add to Quote';
confirmBtn.onclick = () => {
const timelineDays = timelineStr ? parseTimelineDays(timelineStr) : null;
addInvoiceItem(serviceName, servicePrice, serviceKey, timelineDays);
confirmBtn.disabled = true;
confirmBtn.style.opacity = '0.6';
confirmBtn.innerText = '✓ Added';
};
wrapper.appendChild(confirmBtn);
}
chatMessagesDiv.appendChild(wrapper);
chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
}
function addMessage(text, sender) {
const div = document.createElement('div');
div.className = `message ${sender === 'user' ? 'user-msg' : 'bot-msg'}`;
div.innerText = text;
document.getElementById('chatMessages').appendChild(div);
chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
}
// ---------- History Loading ----------
let historyLoaded = false;
async function loadChatHistory() {
try {
const res = await fetch(`/api/history?session_id=${sessionId}`);
const data = await res.json();
if (data.messages && data.messages.length) {
const chatMessagesDiv = document.getElementById('chatMessages');
const children = Array.from(chatMessagesDiv.children);
let welcomeIndex = -1;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.classList && child.classList.contains('message') &&
child.classList.contains('bot-msg') &&
child.innerText.includes("Assalam-o-Alaikum")) {
welcomeIndex = i;
break;
}
}
for (let i = children.length - 1; i >= 0; i--) {
if (i !== welcomeIndex) {
children[i].remove();
}
}
for (let msg of data.messages) {
if (msg.role === 'user') {
addMessage(msg.content, 'user');
} else if (msg.role === 'assistant') {
addMessage(msg.content, 'bot');
}
}
}
} catch (err) {
console.error("History load error", err);
}
}
// ---------- UI Event Listeners ----------
const chatIcon = document.getElementById('chatIcon');
const chatModal = document.getElementById('chatModal');
const closeChat = document.getElementById('closeChat');
const sendBtn = document.getElementById('sendBtn');
const userInput = document.getElementById('userInput');
const chatMessagesDiv = document.getElementById('chatMessages');
const questionsContainer = document.getElementById('defaultQuestionsContainer');
const finalReportBtn = document.getElementById('finalReportBtn');
const downloadReportBtn = document.getElementById('downloadReportBtn');
finalReportBtn.onclick = () => {
if (invoiceItems.length === 0) {
addMessageWithConfirm("❌ No services added yet.", 'bot');
return;
}
let report = "📋 **Final Project Report**\n\n**Selected Services:**\n";
let totalPrice = 0, totalDays = 0;
invoiceItems.forEach(item => {
totalPrice += parsePrice(item.price);
report += `- ${item.name}: ${item.price}\n`;
if (item.timelineDays) totalDays += item.timelineDays;
});
report += `\n💰 Total: PKR ${totalPrice.toLocaleString()}`;
if (totalDays) report += `\n⏱️ Timeline: ${totalDays} days`;
if (storedProjectId) report += `\n\n📌 Project ID: ${storedProjectId}`;
addMessageWithConfirm(report, 'bot');
};
downloadReportBtn.onclick = () => {
if (invoiceItems.length === 0) { alert("No services selected."); return; }
let content = "ELITE VISUALS – QUOTE REPORT\n\nDate: "+new Date().toLocaleString()+"\n\nServices:\n";
let total = 0;
invoiceItems.forEach(item => {
total += parsePrice(item.price);
content += `• ${item.name}: ${item.price}\n`;
});
content += `\nTOTAL: PKR ${total.toLocaleString()}`;
if (storedProjectId) content += `\n\nProject ID: ${storedProjectId}`;
const blob = new Blob([content], {type:"text/plain"});
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `quote_${Date.now()}.txt`;
a.click();
URL.revokeObjectURL(a.href);
};
const invoiceColumn = document.getElementById('invoiceColumn');
const chatColumn = document.getElementById('chatColumn');
const toggleInvoiceBtn = document.getElementById('toggleInvoiceBtn');
let invoiceHidden = false;
toggleInvoiceBtn.onclick = () => {
if (invoiceHidden) {
invoiceColumn.classList.remove('hidden');
chatColumn.classList.remove('expanded');
toggleInvoiceBtn.innerHTML = '<i class="fas fa-eye-slash"></i>';
} else {
invoiceColumn.classList.add('hidden');
chatColumn.classList.add('expanded');
toggleInvoiceBtn.innerHTML = '<i class="fas fa-eye"></i>';
}
invoiceHidden = !invoiceHidden;
};
function renderQuestionBubbles() {
questionsContainer.innerHTML = '';
DEFAULT_QUESTIONS.forEach(q => {
const bubble = document.createElement('div');
bubble.className = 'question-bubble';
bubble.innerText = q;
bubble.onclick = () => { userInput.value = q; sendMessage(); };
questionsContainer.appendChild(bubble);
});
}
let typingDiv = null;
function showTyping() {
if (typingDiv) return;
typingDiv = document.createElement('div');
typingDiv.className = 'typing-indicator';
typingDiv.innerHTML = '<span></span><span></span><span></span>';
chatMessagesDiv.appendChild(typingDiv);
chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
}
function hideTyping() {
if (typingDiv) { typingDiv.remove(); typingDiv = null; }
}
async function sendMessage() {
const msg = userInput.value.trim();
if (!msg) return;
if (questionsContainer) questionsContainer.style.display = 'none';
addMessageWithConfirm(msg, 'user');
userInput.value = '';
showTyping();
try {
const res = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg, session_id: sessionId })
});
const data = await res.json();
hideTyping();
addMessageWithConfirm(data.reply, 'bot', data.widget);
} catch (err) {
hideTyping();
addMessageWithConfirm("❌ Server error. Try again.", 'bot');
}
}
chatIcon.onclick = async () => {
chatModal.style.display = 'flex';
if (questionsContainer.children.length === 0) renderQuestionBubbles();
if (!historyLoaded) {
await loadChatHistory();
historyLoaded = true;
}
};
closeChat.onclick = () => chatModal.style.display = 'none';
sendBtn.onclick = sendMessage;
userInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); });
renderQuestionBubbles();
const widgetContent = document.getElementById('widgetContent');
const toggleIcon = document.getElementById('toggleIcon');
const hideWidgetBtn = document.getElementById('hideWidgetBtn');
const unhideWidgetBtn = document.getElementById('unhideWidgetBtn');
const liveWidget = document.getElementById('liveWidget');
let widgetOpen = false;
toggleIcon.onclick = (e) => {
e.stopPropagation();
if (widgetOpen) {
widgetContent.classList.remove('show');
toggleIcon.classList.remove('fa-chevron-up');
toggleIcon.classList.add('fa-chevron-down');
} else {
widgetContent.classList.add('show');
toggleIcon.classList.remove('fa-chevron-down');
toggleIcon.classList.add('fa-chevron-up');
}
widgetOpen = !widgetOpen;
};
hideWidgetBtn.onclick = () => {
liveWidget.style.display = 'none';
hideWidgetBtn.style.display = 'none';
unhideWidgetBtn.style.display = 'inline-flex';
};
unhideWidgetBtn.onclick = () => {
liveWidget.style.display = 'block';
hideWidgetBtn.style.display = 'inline-flex';
unhideWidgetBtn.style.display = 'none';
};
function updateWidget(data) {
// Not critical for core functionality
}
updateWidget(null);
</script>
</body>
</html>