File size: 28,095 Bytes
97424d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
const chatContainer = document.getElementById("chat-container");
const chatBox = document.getElementById("chat-box");
const input = document.getElementById("user-input");
const intro = document.getElementById("intro");
const scrollBtn = document.getElementById("scroll-to-bottom-btn");

const currentUser = localStorage.getItem('mentorGenUser') || "guest_user";
let chats = []; 

let currentChat = [];
let currentChatId = null;
let generatingSessions = new Set();
let abortControllers = new Map();
let currentImageData = null;

/* --- AUDIO ENGINE: MECHANICAL TYPING SOUND --- */
let audioCtx;
function initAudio() {
    if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    if (audioCtx.state === 'suspended') audioCtx.resume();
}

function playTypingSound() {
    if (!audioCtx) return;
    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();
    osc.type = 'sine';
    osc.frequency.setValueAtTime(600 + Math.random() * 200, audioCtx.currentTime);
    gain.gain.setValueAtTime(0.015, audioCtx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.04);
    osc.connect(gain); gain.connect(audioCtx.destination);
    osc.start(); osc.stop(audioCtx.currentTime + 0.04);
}

/* --- MOBILE LAYOUT LOGIC --- */
function toggleMobileSidebar() {
    document.getElementById('main-sidebar').classList.toggle('mobile-open');
    document.getElementById('sidebar-overlay').classList.toggle('active');
}

function closeMobileSidebar() {
    const sidebar = document.getElementById('main-sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    if (sidebar) sidebar.classList.remove('mobile-open');
    if (overlay) overlay.classList.remove('active');
}

/* --- ATTACHMENT LOGIC --- */
function toggleAttachMenu() {
    const menu = document.getElementById('attach-menu');
    const icon = document.getElementById('plus-icon');
    if(menu) menu.classList.toggle('show');
    if(icon) icon.style.transform = menu.classList.contains('show') ? 'rotate(45deg)' : 'rotate(0deg)';
}

document.addEventListener('click', (e) => {
    const wrapper = document.querySelector('.attach-wrapper');
    if (wrapper && !wrapper.contains(e.target)) {
        const menu = document.getElementById('attach-menu');
        const icon = document.getElementById('plus-icon');
        if (menu) menu.classList.remove('show');
        if (icon) icon.style.transform = 'rotate(0deg)';
    }
});

function triggerFileInput(type) { toggleAttachMenu(); document.getElementById('file-input').click(); }
function mockDriveUpload() { toggleAttachMenu(); showToast("Drive integration requires active API keys."); }

function handleImageUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function(e) {
        currentImageData = e.target.result;
        document.getElementById('image-preview').src = currentImageData;
        document.getElementById('image-preview-container').style.display = 'inline-block';
        input.focus();
    };
    reader.readAsDataURL(file);
}

function removeImage() {
    currentImageData = null;
    document.getElementById('file-input').value = "";
    document.getElementById('image-preview-container').style.display = 'none';
}

document.addEventListener('keydown', (e) => {
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') { e.preventDefault(); input.focus(); }
    if (e.key === 'ArrowUp' && input.value.trim() === '') {
        e.preventDefault();
        for (let i = currentChat.length - 1; i >= 0; i--) {
            if (currentChat[i].role === 'user') { input.value = currentChat[i].text; autoResize(input); break; }
        }
    }
});

chatContainer.addEventListener("scroll", () => {
    if (!scrollBtn) return;
    const scrollFromBottom = chatContainer.scrollHeight - chatContainer.scrollTop - chatContainer.clientHeight;
    scrollBtn.style.display = scrollFromBottom > 150 ? "flex" : "none";
});

function scrollToBottom() { chatContainer.scrollTo({ top: chatContainer.scrollHeight, behavior: "smooth" }); }

marked.setOptions({
    highlight: function(code, lang) {
        if (lang && hljs.getLanguage(lang)) { return hljs.highlight(code, { language: lang }).value; }
        return hljs.highlightAuto(code).value;
    },
    langPrefix: 'hljs language-'
});

function toggleTheme() {
    const body = document.body; const icon = document.getElementById("theme-icon");
    if (body.classList.contains("dark-theme")) { body.classList.replace("dark-theme", "light-theme"); icon.classList.replace("fa-moon", "fa-sun"); }
    else { body.classList.replace("light-theme", "dark-theme"); icon.classList.replace("fa-sun", "fa-moon"); }
}

function fillPrompt(text) { input.value = text; autoResize(input); input.focus(); }
function autoResize(el) { el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px'; }
input.addEventListener('keydown', function(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });

function showToast(message, isError = false) {
    const toast = document.getElementById("toast");
    const icon = isError ? '<i class="fas fa-exclamation-circle" style="color: #ef4444;"></i>' : '<i class="fas fa-check-circle" style="color: #10b981;"></i>';
    toast.innerHTML = `${icon} ${message}`; toast.classList.add("show");
    setTimeout(() => toast.classList.remove("show"), 3000);
}

function shareChat() {
    if (!currentChatId || currentChat.length === 0) return showToast("Please start a session first.", true);
    const shareUrl = window.location.origin + "/chat?session=" + currentChatId;
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(shareUrl).then(() => showToast("Shareable link copied to clipboard!")).catch(() => fallbackCopyTextToClipboard(shareUrl));
    } else { fallbackCopyTextToClipboard(shareUrl); }
}

function fallbackCopyTextToClipboard(text) {
    const textArea = document.createElement("textarea"); textArea.value = text; textArea.style.position = "fixed";
    document.body.appendChild(textArea); textArea.focus(); textArea.select();
    try { document.execCommand('copy'); showToast("Shareable link copied to clipboard!"); } catch (err) { showToast("Failed to copy link.", true); }
    document.body.removeChild(textArea);
}

function copyMessageText(iconElement, text) {
    navigator.clipboard.writeText(text).then(() => {
        const originalClass = iconElement.className;
        iconElement.className = "fas fa-check"; iconElement.style.color = "#10b981";
        setTimeout(() => { iconElement.className = originalClass; iconElement.style.color = ""; }, 2000);
    }).catch(err => showToast("Failed to copy.", true));
}

function startListening() {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SpeechRecognition) return showToast("Microphone not supported.", true);
    const rec = new SpeechRecognition(); rec.start(); input.placeholder = "Listening...";
    rec.onresult = e => { input.value += e.results[0][0].transcript; autoResize(input); };
    rec.onend = () => input.placeholder = "Ask anything or attach a photo...";
}

let botVoice = null;
function setVoice() {
    const voices = window.speechSynthesis.getVoices();
    if (voices.length === 0) return;
    botVoice = voices.find(v => (v.name.includes('Male') || v.name.includes('David') || v.name.includes('Mark')) && !v.name.includes('Female'));
    if (!botVoice) botVoice = voices[0];
}
window.speechSynthesis.onvoiceschanged = setVoice; setVoice();

function speakText(text) {
    speechSynthesis.cancel();
    let cleanText = text.replace(/`{3}[\s\S]*?`{3}/g, ' [Code block omitted] ')
                        .replace(/`[^`]*`/g, ' ')
                        .replace(/[*#_=\-><~]/g, ' ')
                        .replace(/\s+/g, ' ')
                        .trim();
    const utterance = new SpeechSynthesisUtterance(cleanText);
    if (botVoice) utterance.voice = botVoice; 
    speechSynthesis.speak(utterance);
}

function stopSpeaking() { speechSynthesis.cancel(); }
function stopGeneration() { if (abortControllers.has(currentChatId)) abortControllers.get(currentChatId).abort(); }
function getCurrentTime() { return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); }

async function sendMessage(textOverride = null, skipUserAppend = false) {
    if (currentChatId && generatingSessions.has(currentChatId)) return;

    initAudio();
    const text = textOverride || input.value.trim();
    if (!text && !currentImageData) return;

    if(intro) intro.style.display = "none";
    if (currentChatId === null) currentChatId = "Session_" + Date.now();

    const reqChatId = currentChatId; const timeSent = getCurrentTime(); const sentImage = currentImageData;

    if (!skipUserAppend) {
        appendUser(text, timeSent, sentImage);
        currentChat.push({ role: "user", text: text, image: sentImage, time: timeSent });
        if(!textOverride) { input.value = ""; input.style.height = 'auto'; }
        removeImage(); saveToHistory(); window.history.replaceState(null, null, "?session=" + reqChatId);
    }

    generatingSessions.add(reqChatId);
    const controller = new AbortController(); abortControllers.set(reqChatId, controller);
    appendPremiumThinking(); setSendButtonState("stop");
    const startTime = Date.now();

    try {
        const res = await fetch("/chat", {
            method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" },
            body: JSON.stringify({ username: currentUser, message: text, image: sentImage }), signal: controller.signal
        });
        const data = await res.json();
        const responseTime = ((Date.now() - startTime) / 1000).toFixed(1);
        const timeReceived = getCurrentTime();

        if (currentChatId === reqChatId) {
            removeThinkingUI();
            currentChat.push({ role: "bot", text: data.reply, time: timeReceived, respTime: responseTime });
            simulateTyping(data.reply, reqChatId, timeReceived, responseTime);
            saveToHistory();
        } else {
            const sessionIndex = chats.findIndex(c => c.id === reqChatId);
            if (sessionIndex > -1) {
                chats[sessionIndex].messages.push({ role: "bot", text: data.reply, time: timeReceived, respTime: responseTime });
                saveToHistorySilent(chats[sessionIndex]);
            }
        }
    } catch (e) {
        let finalMsg = "System error. Check backend connection.";
        if (e.name === 'AbortError') finalMsg = "<em>Response stopped by user.</em>";
        if (currentChatId === reqChatId) {
            removeThinkingUI();
            currentChat.push({ role: "bot", text: finalMsg, time: getCurrentTime(), respTime: null });
            appendBot(finalMsg, getCurrentTime(), null); saveToHistory();
        }
    } finally {
        generatingSessions.delete(reqChatId); abortControllers.delete(reqChatId);
        if (currentChatId === reqChatId) setSendButtonState("send"); renderHistory();
    }
}

function setSendButtonState(state) {
    const sendBtn = document.getElementById("send-btn");
    if (state === "stop") {
        sendBtn.innerHTML = '<i class="fas fa-stop"></i>'; sendBtn.classList.add("stop-mode"); sendBtn.title = "Stop Generation"; sendBtn.onclick = stopGeneration;
    } else {
        sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>'; sendBtn.classList.remove("stop-mode"); sendBtn.title = "Send Message"; sendBtn.onclick = () => sendMessage();
    }
}

function simulateTyping(text, reqChatId, timeStr, respTime) {
    const wrapper = document.createElement("div"); wrapper.className = "message-wrapper bot";
    const header = document.createElement("div"); header.className = "bot-header";
    header.innerHTML = `<img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text pulse-text">MentoraGen is thinking...</span>`;
    wrapper.appendChild(header);
    const msg = document.createElement("div"); msg.className = "message";
    wrapper.appendChild(msg); chatBox.appendChild(wrapper);
    let i = 0; let buffer = ""; let tickCounter = 0;

    const typeInterval = setInterval(() => {
        if (currentChatId !== reqChatId) { clearInterval(typeInterval); return; }
        buffer += text.substr(i, 4); i += 4;
        if (tickCounter % 3 === 0) playTypingSound();
        tickCounter++;

        // Inject the WhatsApp style time at the end of the parsed markdown
        msg.innerHTML = marked.parse(buffer) + `<span class="msg-time bot-time">${timeStr}</span>`;
        chatContainer.scrollTop = chatContainer.scrollHeight;

        if (i >= text.length) {
            clearInterval(typeInterval);
            msg.innerHTML = marked.parse(text) + `<span class="msg-time bot-time">${timeStr}</span>`;
            msg.querySelectorAll('pre code').forEach((block) => { try { hljs.highlightElement(block); } catch(e) {} });
            addCodeCopyButtons(msg);
            header.innerHTML = `<img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text">Thinking for ${respTime} seconds</span>`;
            wrapper.appendChild(createBotActions(text, timeStr)); // Time is removed from the actions visually now
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    }, 10);
}

function addCodeCopyButtons(container) {
    container.querySelectorAll('pre').forEach(pre => {
        if (pre.querySelector('.code-header')) return;
        const codeBlock = pre.querySelector('code'); let lang = "Code";
        if (codeBlock && codeBlock.className) { const match = codeBlock.className.match(/language-(\w+)/); if (match) lang = match[1]; }
        const header = document.createElement('div'); header.className = 'code-header'; header.innerHTML = `<span class="code-lang">${lang}</span>`;
        const btn = document.createElement('button'); btn.className = 'copy-code-btn'; btn.innerHTML = '<i class="far fa-clipboard"></i> Copy code';
        btn.onclick = () => { navigator.clipboard.writeText(codeBlock.innerText); btn.innerHTML = '<i class="fas fa-check" style="color:#10b981;"></i> Copied!';
        setTimeout(() => { btn.innerHTML = '<i class="far fa-clipboard"></i> Copy code'; }, 2000); };
        header.appendChild(btn); pre.prepend(header);
    });
}

function appendPremiumThinking() {
    if (document.getElementById("thinking-wrapper")) return;
    const wrapper = document.createElement("div"); wrapper.className = "message-wrapper bot"; wrapper.id = "thinking-wrapper";
    wrapper.innerHTML = `<div class="bot-header"><img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text pulse-text">MentoraGen is thinking...</span></div>`;
    chatBox.appendChild(wrapper); chatContainer.scrollTop = chatContainer.scrollHeight;
}

function removeThinkingUI() {
    const thinkingWrapper = document.getElementById("thinking-wrapper");
    if (thinkingWrapper) thinkingWrapper.remove();
}

function createUserActions(text, timeStr) {
    const actions = document.createElement("div"); 
    actions.className = "msg-actions"; 
    // Time is physically removed from here
    actions.innerHTML = `

        <i class="far fa-copy" title="Copy Message" onclick="copyMessageText(this, \`${text.replace(/`/g, '\\`')}\`)"></i>

        <i class="fas fa-edit" title="Edit Message" onclick="editUserMessageInline(this, \`${text.replace(/`/g, '\\`')}\`)"></i>

    `;

    return actions;

}



function createBotActions(text, timeStr) {

    const actions = document.createElement("div"); actions.className = "msg-actions";

    const btnCopy = document.createElement("i"); btnCopy.className = "far fa-copy"; btnCopy.title = "Copy"; btnCopy.onclick = (e) => copyMessageText(e.target, text);

    const btnLike = document.createElement("i"); btnLike.className = "far fa-thumbs-up";

    const btnDislike = document.createElement("i"); btnDislike.className = "far fa-thumbs-down";

    btnLike.onclick = function() {

        this.classList.toggle("fas"); this.classList.toggle("far");

        btnDislike.className = "far fa-thumbs-down"; btnDislike.style.color = "";

        this.style.color = this.classList.contains("fas") ? "var(--accent-solid)" : "";

        if (this.classList.contains("fas")) showToast("Thank you for your feedback");

    };

    btnDislike.onclick = function() {

        this.classList.toggle("fas"); this.classList.toggle("far");

        btnLike.className = "far fa-thumbs-up"; btnLike.style.color = "";

        this.style.color = this.classList.contains("fas") ? "#ef4444" : "";

        if (this.classList.contains("fas")) showToast("Share your valuable opinion in contact section for improvement", true);

    };

    const btnSpeak = document.createElement("i"); btnSpeak.className = "fas fa-volume-up"; btnSpeak.onclick = () => speakText(text);

    const btnStop = document.createElement("i"); btnStop.className = "fas fa-stop-circle"; btnStop.onclick = stopSpeaking;



    // Time is physically removed from here

    actions.append(btnCopy, btnLike, btnDislike, btnSpeak, btnStop); return actions;

}



function editUserMessageInline(iconElement, oldText) {

    const wrapper = iconElement.closest('.message-wrapper'); const msgDiv = wrapper.querySelector('.message'); const actionsDiv = wrapper.querySelector('.msg-actions');

    const originalHTML = msgDiv.innerHTML; actionsDiv.style.display = 'none';

    msgDiv.innerHTML = `<textarea class="inline-edit-box" rows="3">${oldText}</textarea><div class="inline-edit-actions"><button class="btn-cancel">Cancel</button><button class="btn-save">Send</button></div>`;

    const textarea = msgDiv.querySelector('.inline-edit-box'); textarea.focus();



    msgDiv.querySelector('.btn-cancel').onclick = () => { msgDiv.innerHTML = originalHTML; actionsDiv.style.display = 'flex'; };

    msgDiv.querySelector('.btn-save').onclick = () => {

        const newText = textarea.value.trim();

        if(!newText || newText === oldText) { msgDiv.innerHTML = originalHTML; actionsDiv.style.display = 'flex'; return; }

        let nextSibling = wrapper.nextElementSibling; while(nextSibling) { const toRemove = nextSibling; nextSibling = nextSibling.nextElementSibling; toRemove.remove(); }

        const index = Array.from(chatBox.querySelectorAll('.message-wrapper')).indexOf(wrapper); const updatedTime = getCurrentTime();

        if (index > -1) { currentChat = currentChat.slice(0, index + 1); currentChat[index].text = newText; currentChat[index].time = updatedTime; saveToHistory(); }

        

        // WhatsApp style rebuild for edited user message

        msgDiv.innerHTML = '';

        const textContainer = document.createElement("div");

        textContainer.className = "user-text-content clamped-text";

        textContainer.innerText = newText;

        msgDiv.appendChild(textContainer);

        

        const timeSpan = document.createElement("span");

        timeSpan.className = "msg-time user-time";

        timeSpan.innerText = updatedTime;

        msgDiv.appendChild(timeSpan);

        

        wrapper.replaceChild(createUserActions(newText, updatedTime), actionsDiv); sendMessage(newText, true);

    };

}



function appendUser(text, time = null, imageData = null) {

    if (!time) time = getCurrentTime();

    const wrapper = document.createElement("div"); 

    wrapper.className = "message-wrapper user"; 



    const msg = document.createElement("div"); 

    msg.className = "message";



    if (imageData) { 

        const imgEl = document.createElement("img"); 

        imgEl.src = imageData; 

        imgEl.className = "chat-uploaded-img"; 

        msg.appendChild(imgEl); 

    }

    

    if (text) {

        const textContainer = document.createElement("div");

        textContainer.className = "user-text-content clamped-text";

        textContainer.innerText = text;

        msg.appendChild(textContainer);



        requestAnimationFrame(() => {

            if (textContainer.scrollHeight > textContainer.clientHeight) {

                const expandBtn = document.createElement("div");

                expandBtn.className = "expand-toggle";

                expandBtn.innerHTML = '<i class="fas fa-chevron-down"></i>';

                

                expandBtn.onclick = function() {

                    textContainer.classList.toggle("expanded");

                    this.innerHTML = textContainer.classList.contains("expanded") ? '<i class="fas fa-chevron-up"></i>' : '<i class="fas fa-chevron-down"></i>';

                };

                msg.appendChild(expandBtn);

            }

        });

    }

    

    // Inject the WhatsApp style time at the end of the User bubble

    const timeSpan = document.createElement("span");

    timeSpan.className = "msg-time user-time";

    timeSpan.innerText = time;

    msg.appendChild(timeSpan);



    wrapper.appendChild(msg); 

    wrapper.appendChild(createUserActions(text, time));

    chatBox.appendChild(wrapper); 

    chatContainer.scrollTop = chatContainer.scrollHeight;

}



function appendBot(text, time = null, respTime = null) {

    if (!time) time = getCurrentTime();

    const wrapper = document.createElement("div"); wrapper.className = "message-wrapper bot";

    const latencyText = respTime ? `Thinking for ${respTime} seconds` : "MentoraGen";

    wrapper.innerHTML = `<div class="bot-header"><img src="./static/logo.png" class="bot-avatar"> <span class="thinking-text">${latencyText}</span></div>`;

    const msg = document.createElement("div"); msg.className = "message";

    

    // Inject the WhatsApp style time at the end of the AI bubble

    msg.innerHTML = marked.parse(text) + `<span class="msg-time bot-time">${time}</span>`;

    

    msg.querySelectorAll('pre code').forEach((block) => { try { hljs.highlightElement(block); } catch(e) {} });

    addCodeCopyButtons(msg);

    wrapper.appendChild(msg); wrapper.appendChild(createBotActions(text, time));

    chatBox.appendChild(wrapper); chatContainer.scrollTop = chatContainer.scrollHeight;

}



function generateSummary(text) {

    let cleanText = text.replace(/[^a-zA-Z0-9 ]/g, " ").replace(/\s+/g, " ").trim();

    const fillers = ["can you explain how to", "can you explain how", "explain how", "what is the difference between", "how do i", "tell me about", "debug this", "write a", "what are", "what is", "difference between"];

    let lowerText = cleanText.toLowerCase();

    for (let filler of fillers) { if (lowerText.startsWith(filler)) { cleanText = cleanText.substring(filler.length).trim(); break; } }

    const words = cleanText.split(" "); let title = words.slice(0, 4).join(" ") + (words.length > 4 ? "..." : "");

    return title.length === 0 ? "New Session" : title.split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');

}



async function loadAllChats() {

    if (currentUser === "guest_user") return;

    try {

        const res = await fetch("/get_chats/" + currentUser, { headers: {"ngrok-skip-browser-warning": "true"} });

        if (res.ok) {

            chats = await res.json();

            renderHistory();

        }

    } catch (e) { console.error("Could not load chats from DB", e); }

}



async function saveToHistory() {

    if (!currentChatId || currentChat.length === 0) return;

    const sessionData = { id: currentChatId, title: generateSummary(currentChat[0].text || "Image Upload"), messages: [...currentChat] };

    const existingIndex = chats.findIndex(c => c.id === currentChatId);

    if (existingIndex > -1) chats[existingIndex] = sessionData; 

    else chats.unshift(sessionData);

    renderHistory();

    fetch("/save_chat", {

        method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" },

        body: JSON.stringify({ chat_id: sessionData.id, username: currentUser, title: sessionData.title, messages: sessionData.messages })

    }).catch(e => console.log("DB save failed", e));

}



function saveToHistorySilent(sessionData) {

    fetch("/save_chat", {

        method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" },

        body: JSON.stringify({ chat_id: sessionData.id, username: currentUser, title: sessionData.title, messages: sessionData.messages })

    }).catch(e => console.log("DB silent save failed", e));

}



async function deleteChat(e, id) {

    e.stopPropagation();

    chats = chats.filter(c => c.id !== id);

    currentChatId === id ? newChat() : renderHistory();

    fetch("/delete_chat/" + id, { method: "DELETE", headers: { "ngrok-skip-browser-warning": "true" } }).catch(e => console.log("DB delete failed", e));

}



function renderHistory() {

    const ul = document.getElementById("history"); ul.innerHTML = "";

    chats.forEach(session => {

        const li = document.createElement("li");

        if (session.id === currentChatId) li.classList.add("active"); 

        li.onclick = () => loadSession(session);

        li.innerHTML = `<i class="fas fa-message" style="color: var(--accent-solid); opacity: 0.8;"></i><span class="history-text">${session.title}</span><i class="fas fa-trash delete-chat-btn" onclick="deleteChat(event, '${session.id}')" title="Delete Session"></i>`;

        ul.appendChild(li);

    });

}



function resetBackendContext() {

    fetch("/chat", { method: "POST", headers: { "Content-Type": "application/json", "ngrok-skip-browser-warning": "true" }, body: JSON.stringify({ username: currentUser, message: "reset" }) }).catch(e => console.log("Context isolated."));

}



function loadSession(session) {

    resetBackendContext(); currentChatId = session.id; currentChat = session.messages; chatBox.innerHTML = "";

    if(intro) intro.style.display = "none";

    currentChat.forEach(msg => { if(msg.role === "user") appendUser(msg.text, msg.time, msg.image); else appendBot(msg.text, msg.time, msg.respTime); });

    setSendButtonState(generatingSessions.has(currentChatId) ? "stop" : "send");

    window.history.replaceState(null, null, "?session=" + currentChatId);

    renderHistory(); 

    closeMobileSidebar(); 

}



function newChat() {

    resetBackendContext(); currentChat = []; currentChatId = null; chatBox.innerHTML = "";

    if(intro) { intro.style.display = "flex"; chatBox.appendChild(intro); }

    stopSpeaking(); setSendButtonState("send"); window.history.replaceState(null, null, window.location.pathname);

    renderHistory(); 

    closeMobileSidebar(); 

}



async function init() {

    const savedUser = localStorage.getItem('mentorGenUser');

    const profileBtn = document.getElementById('user-profile-btn');

    const userNameEl = document.querySelector('.user-name');

    const userActionEl = document.querySelector('.user-action');



    if (savedUser) {

        if (userNameEl) userNameEl.innerText = savedUser;

        if (userActionEl) userActionEl.innerText = "Manage Profile";

        if (profileBtn) { profileBtn.href = "/profile"; profileBtn.onclick = null; }

    } else {

        if (userNameEl) userNameEl.innerText = "Guest User";

        if (userActionEl) userActionEl.innerText = "Log in / Sign up";

        if (profileBtn) { profileBtn.href = "/login"; profileBtn.onclick = null; }

    }



    await loadAllChats();



    const sharedSessionId = new URLSearchParams(window.location.search).get('session');

    if (sharedSessionId) {

        const sessionToLoad = chats.find(c => c.id === sharedSessionId);

        if (sessionToLoad) { loadSession(sessionToLoad); } else { showToast("Shared session not found.", true); newChat(); }

    } else { newChat(); }

}

init();