Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
9027 lines (8700 loc) · 444 KB
/
Copy pathscript.js
File metadata and controls
9027 lines (8700 loc) · 444 KB
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================
// STATE
// ============================================================
let history = [];
let sessions = JSON.parse(localStorage.getItem('chatSessions') || '[]');
let currentSessionIndex = null;
let isStreaming = false;
let savedWords = JSON.parse(localStorage.getItem('savedWords') || '[]');
// ============================================================
// THEME SÁNG/TỐI — nút ở topbar, nhớ lựa chọn vào localStorage
// ============================================================
function initTheme() {
let t = 'light';
try { t = localStorage.getItem('appTheme') || 'light'; } catch (e) {}
if (t !== 'dark' && t !== 'light') t = 'light';
document.documentElement.setAttribute('data-theme', t);
const ic = document.getElementById('themeIcon');
if (ic) ic.className = t === 'dark' ? 'ri-moon-line' : 'ri-sun-line';
}
function toggleTheme() {
const cur = document.documentElement.getAttribute('data-theme') || 'light';
const next = cur === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', next);
try { localStorage.setItem('appTheme', next); } catch (e) {}
const ic = document.getElementById('themeIcon');
if (ic) ic.className = next === 'dark' ? 'ri-moon-line' : 'ri-sun-line';
}
// Restore history sidebar on load
document.addEventListener('DOMContentLoaded', function () {
initTheme();
if (sessions.length > 0) renderHistory();
updateBookmarkCount();
if (typeof refreshHomeTab === 'function') refreshHomeTab();
// Auth: kiểm tra phiên cũ + xử lý link đặt lại mật khẩu
checkAuthOnLoad();
const rt = new URLSearchParams(location.search).get('reset');
if (rt) {
_pendingResetToken = rt;
showAuthModal('reset');
history.replaceState(null, '', location.pathname);
}
});
// ============================================================
// WELCOME TITLE NGẪU NHIÊN
// ============================================================
const WELCOME_TITLES = [
"Bắt đầu học tiếng Anh thôi?",
"Hôm nay học từ mới nào?",
"Luyện tiếng Anh cùng AI nhé!",
"Từ vựng hôm nay là gì?",
"Ngữ pháp nào đang làm bạn khó?",
"Cùng nâng trình độ CEFR nào!",
"English time? Let's go!",
"Một từ mới mỗi ngày nhé!",
];
function setRandomTitle() {
const el = document.getElementById('welcomeTitle');
if (el) {
el.textContent = WELCOME_TITLES[Math.floor(Math.random() * WELCOME_TITLES.length)];
}
}
// Gọi ngay khi load
document.addEventListener('DOMContentLoaded', setRandomTitle);
// ============================================================
// TAB SWITCHING
// ============================================================
function switchTab(tab) {
// Chưa đăng nhập thì chỉ được ở trang chủ
if (tab !== 'home' && !isLoggedIn()) { showAuthModal(); return; }
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
document.querySelectorAll('.nav-item').forEach(el => el.classList.remove('active'));
document.getElementById(`tab-${tab}`).classList.add('active');
document.querySelector(`[data-tab="${tab}"]`).classList.add('active');
const icons = { home: 'ri-home-line', chat: 'ri-chat-3-line', cefr: 'ri-bar-chart-grouped-line', flashcard: 'ri-layers-line', reading: 'ri-book-open-line', listening: 'ri-headphone-line', lesson: 'ri-sparkles-line', progress: 'ri-line-chart-line' };
const titles = { home: 'Trang chủ', chat: 'Chat', cefr: 'Phân tích CEFR', flashcard: 'Flashcard', reading: 'Bài đọc', listening: 'Luyện nghe', lesson: 'Từ vựng & Ngữ pháp', progress: 'Tiến bộ' };
document.getElementById('topbarTitle').innerHTML = `
<i class="${icons[tab]}"></i>
<span>${titles[tab]}</span>
`;
if (tab === 'home') refreshHomeTab();
if (tab === 'flashcard') refreshFlashcardTab();
if (tab === 'reading') openReading();
if (tab === 'listening') openListening();
if (tab === 'progress') renderProgress();
}
// ============================================================
// AUTH: đăng nhập email + mật khẩu để học.
// Token lưu localStorage, gửi kèm header Authorization: Bearer.
// Từ đã lưu / tiến trình đồng bộ lên server theo tài khoản.
// ============================================================
let authToken = localStorage.getItem('authToken') || '';
let authUser = null;
try { authUser = JSON.parse(localStorage.getItem('authUser') || 'null'); } catch (e) {}
let _pendingResetToken = '';
function authHeaders() {
return authToken ? { 'Authorization': 'Bearer ' + authToken } : {};
}
function isLoggedIn() { return !!(authToken && authUser); }
function showAuthModal(view) {
showAuthView(view || 'login');
document.getElementById('authBackdrop').style.display = 'flex';
}
function hideAuthModal() {
document.getElementById('authBackdrop').style.display = 'none';
}
function showAuthView(v) {
['Login', 'Register', 'Forgot', 'Reset'].forEach(x => {
document.getElementById('auth' + x + 'View').style.display = (x.toLowerCase() === v) ? '' : 'none';
});
const titles = { login: 'Đăng nhập', register: 'Tạo tài khoản mới', forgot: 'Quên mật khẩu', reset: 'Đặt lại mật khẩu' };
document.getElementById('authTitle').textContent = titles[v] || titles.login;
const subs = { login: 'Đăng nhập để học', register: 'Tạo tài khoản để lưu từ vựng và đồng bộ tiến trình học.' };
const subEl = document.getElementById('authSub');
subEl.textContent = subs[v] || '';
subEl.style.display = subs[v] ? '' : 'none';
}
function refreshAuthUI() {
const logged = isLoggedIn();
document.getElementById('authLoginBtn').style.display = logged ? 'none' : '';
const ub = document.getElementById('authUserBtn');
ub.style.display = logged ? '' : 'none';
if (logged) document.getElementById('authUserName').textContent = authUser.name || authUser.email;
}
async function onAuthSuccess(token, user) {
authToken = token;
authUser = user;
localStorage.setItem('authToken', token);
localStorage.setItem('authUser', JSON.stringify(user));
refreshAuthUI();
hideAuthModal();
await migrateLocalToServer();
}
async function doLogin() {
const email = document.getElementById('loginEmail').value.trim();
const password = document.getElementById('loginPassword').value;
const err = document.getElementById('loginErr');
err.textContent = '';
if (!email || !password) { err.textContent = 'Nhập email và mật khẩu'; return; }
try {
const res = await fetch('/api/login', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
const d = await res.json();
if (d.error) { err.textContent = d.error; return; }
await onAuthSuccess(d.token, d.user);
} catch (e) { err.textContent = 'Lỗi kết nối: ' + e.message; }
}
async function doRegister() {
const name = document.getElementById('regName').value.trim();
const email = document.getElementById('regEmail').value.trim();
const password = document.getElementById('regPassword').value;
const err = document.getElementById('regErr');
err.textContent = '';
if (!email || !password) { err.textContent = 'Nhập email và mật khẩu'; return; }
try {
const res = await fetch('/api/register', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, name })
});
const d = await res.json();
if (d.error) { err.textContent = d.error; return; }
await onAuthSuccess(d.token, d.user);
} catch (e) { err.textContent = 'Lỗi kết nối: ' + e.message; }
}
async function doForgot() {
const email = document.getElementById('forgotEmail').value.trim();
const err = document.getElementById('forgotErr');
const ok = document.getElementById('forgotOk');
err.textContent = ''; ok.textContent = '';
if (!email) { err.textContent = 'Nhập email đã đăng ký'; return; }
try {
await fetch('/api/forgot-password', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email })
});
ok.textContent = 'Đã gửi link đặt lại mật khẩu vào email của bạn (nếu email tồn tại).';
} catch (e) { err.textContent = 'Lỗi kết nối: ' + e.message; }
}
async function doResetPassword() {
const password = document.getElementById('resetPassword').value;
const err = document.getElementById('resetErr');
const ok = document.getElementById('resetOk');
err.textContent = ''; ok.textContent = '';
if (!password) { err.textContent = 'Nhập mật khẩu mới'; return; }
try {
const res = await fetch('/api/reset-password', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: _pendingResetToken, new_password: password })
});
const d = await res.json();
if (d.error) { err.textContent = d.error; return; }
ok.textContent = 'Đặt lại mật khẩu thành công. Hãy đăng nhập lại.';
_pendingResetToken = '';
setTimeout(() => showAuthView('login'), 1500);
} catch (e) { err.textContent = 'Lỗi kết nối: ' + e.message; }
}
async function doLogout() {
try { await fetch('/api/logout', { method: 'POST', headers: authHeaders() }); } catch (e) {}
authToken = '';
authUser = null;
localStorage.removeItem('authToken');
localStorage.removeItem('authUser');
refreshAuthUI();
switchTab('home');
}
async function checkAuthOnLoad() {
if (!authToken) { refreshAuthUI(); return; }
try {
const res = await fetch('/api/me', { headers: authHeaders() });
if (!res.ok) throw new Error('expired');
const d = await res.json();
authUser = d.user;
localStorage.setItem('authUser', JSON.stringify(authUser));
} catch (e) {
authToken = '';
authUser = null;
localStorage.removeItem('authToken');
localStorage.removeItem('authUser');
}
refreshAuthUI();
}
// Đẩy dữ liệu localStorage lên server 1 lần khi đăng nhập, rồi kéo về hợp nhất
async function migrateLocalToServer() {
try {
const words = JSON.parse(localStorage.getItem('savedWords') || '[]');
if (words.length) {
await fetch('/api/user/words/bulk', {
method: 'POST', headers: { 'Content-Type': 'application/json', ...authHeaders() },
body: JSON.stringify({ words })
});
}
const prog = JSON.parse(localStorage.getItem('topicProgress') || '{}');
if (Object.keys(prog).length) {
await fetch('/api/user/progress/bulk', {
method: 'POST', headers: { 'Content-Type': 'application/json', ...authHeaders() },
body: JSON.stringify({ progress: prog })
});
}
const sw = await fetch('/api/user/words', { headers: authHeaders() }).then(r => r.json());
if (sw.words) {
savedWords = sw.words;
localStorage.setItem('savedWords', JSON.stringify(savedWords));
}
const sp = await fetch('/api/user/progress', { headers: authHeaders() }).then(r => r.json());
if (sp.progress) {
const merged = {};
for (const [g, ws] of Object.entries(sp.progress)) merged[g] = { known: ws };
localStorage.setItem('topicProgress', JSON.stringify(merged));
}
if (typeof updateBookmarkCount === 'function') updateBookmarkCount();
if (typeof renderSavedWordsPanel === 'function') renderSavedWordsPanel();
if (typeof renderBrowse === 'function') renderBrowse();
} catch (e) { /* đăng nhập vẫn ok, đồng bộ thử lại ở lần sau */ }
}
// Ghi từ đã lưu: localStorage + đồng bộ server (gọi sau mỗi lần đổi savedWords)
let _syncWordsTimer = null;
function persistSavedWords() {
try { localStorage.setItem('savedWords', JSON.stringify(savedWords)); } catch (e) {}
if (!isLoggedIn()) return;
clearTimeout(_syncWordsTimer);
_syncWordsTimer = setTimeout(async () => {
try {
await fetch('/api/user/words/bulk', {
method: 'POST', headers: { 'Content-Type': 'application/json', ...authHeaders() },
body: JSON.stringify({ words: savedWords })
});
} catch (e) {}
}, 800);
}
function removeSavedWordServer(lemma) {
if (!isLoggedIn() || !lemma) return;
fetch('/api/user/words?lemma=' + encodeURIComponent(lemma), {
method: 'DELETE', headers: authHeaders()
}).catch(() => {});
}
// ============================================================
// CHAT
// ============================================================
function handleKeydown(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
}
function autoResize(el) {
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 160) + 'px';
}
function sendChip(btn) {
const text = btn.textContent.trim();
document.getElementById('msgInput').value = text;
sendMessage();
}
async function sendMessage() {
if (isStreaming) return;
const input = document.getElementById('msgInput');
const message = input.value.trim();
if (!message) return;
input.value = '';
input.style.height = 'auto';
// đang ở chế độ hỏi đáp theo chủ đề ngữ pháp -> gắn ngữ cảnh
// bài học vào message gửi đi (pattern như drawer bài đọc). Tin nhắn hiển thị
// và history giữ nguyên câu user gõ.
let sendText = message;
if (chatGrammarTopic) {
sendText = `[Ngữ cảnh — Chủ đề ngữ pháp "${chatGrammarTopic.title}":\n${chatGrammarTopic.ctx}]\n\n` +
`Câu hỏi của người học về chủ đề trên: ${message}\n` +
`(Hãy ưu tiên giải đáp trong phạm vi chủ đề ngữ pháp này, bằng tiếng Việt, kèm ví dụ. ` +
`Nếu câu hỏi không liên quan đến chủ đề, trả lời ngắn gọn rồi nhẹ nhàng lái về chủ đề.)`;
}
// Show chat, hide welcome
showChat();
// Add user message
appendMessage('user', message);
history.push({ role: 'user', content: message });
// Add bot typing
const botId = appendBotTyping();
// Disable send
setSending(true);
let detectedWords = [];
try {
const response = await fetch('/api/chat', {
method: 'POST',
// Tài liệu đính kèm: gửi doc_id khi có chip; kèm token để
// backend xác thực chủ tài liệu. Không có doc_id -> chat thường như cũ.
headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
body: JSON.stringify({ message: sendText, history: history.slice(0, -1), doc_id: chatDocId })
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let answer = '';
let buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const lines = buf.split('\n');
buf = lines.pop(); // giữ dòng chưa hoàn chỉnh
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6);
if (data === '[DONE]') break;
try {
const parsed = JSON.parse(data);
if (parsed.error) {
answer = `Lỗi: ${parsed.error}`;
} else if (parsed.words) {
detectedWords = parsed.words;
} else if (parsed.content) {
answer += parsed.content;
}
updateBotMessage(botId, answer);
} catch {}
}
}
if (!answer) answer = 'Xin lỗi, có lỗi xảy ra. Vui lòng thử lại.';
history.push({ role: 'assistant', content: answer });
updateBotMessage(botId, answer);
saveSession();
} catch (err) {
updateBotMessage(botId, `Không thể kết nối tới server: ${err.message}`);
} finally {
setSending(false);
scrollToBottom();
if (detectedWords.length > 0) {
showWordSuggestions(botId, detectedWords);
}
}
}
function showChat() {
const welcome = document.getElementById('welcome');
const messages = document.getElementById('chatMessages');
const composerBottom = document.getElementById('composerBottom');
if (welcome) welcome.classList.add('hidden');
if (composerBottom) composerBottom.style.display = '';
messages.classList.add('visible');
}
function appendMessage(role, content) {
const wrap = getOrCreateWrap();
if (role === 'user') {
const div = document.createElement('div');
div.className = 'msg-user';
div.innerHTML = `<div class="msg-bubble">${escapeHtml(content)}</div>`;
wrap.appendChild(div);
}
scrollToBottom();
}
function appendBotTyping() {
const wrap = getOrCreateWrap();
const id = 'bot-' + Date.now();
const div = document.createElement('div');
div.className = 'msg-bot';
div.id = id;
div.innerHTML = `
<div class="msg-avatar"><i class="ri-graduation-cap-fill"></i></div>
<div class="msg-bubble">
<div class="typing-indicator">
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
</div>
</div>
`;
wrap.appendChild(div);
scrollToBottom();
return id;
}
function updateBotMessage(id, content) {
const el = document.getElementById(id);
if (!el) return;
const bubble = el.querySelector('.msg-bubble');
bubble.innerHTML = renderMarkdown(content);
scrollToBottom();
}
function getOrCreateWrap() {
const messages = document.getElementById('chatMessages');
let wrap = messages.querySelector('.message-wrap');
if (!wrap) {
wrap = document.createElement('div');
wrap.className = 'message-wrap';
messages.appendChild(wrap);
}
return wrap;
}
function scrollToBottom() {
const messages = document.getElementById('chatMessages');
messages.scrollTop = messages.scrollHeight;
}
function setSending(val) {
isStreaming = val;
const btn = document.getElementById('sendBtn');
btn.disabled = val;
}
// ============================================================
// SESSION HISTORY
// ============================================================
function saveSession() {
if (history.length === 0) return;
if (currentSessionIndex === null) {
sessions.push([...history]);
currentSessionIndex = sessions.length - 1;
} else {
sessions[currentSessionIndex] = [...history];
}
localStorage.setItem('chatSessions', JSON.stringify(sessions));
renderHistory();
}
function renderHistory() {
const list = document.getElementById('historyList');
if (sessions.length === 0) {
list.innerHTML = '<div class="history-empty">Chưa có cuộc trò chuyện nào</div>';
return;
}
list.innerHTML = '';
for (let i = sessions.length - 1; i >= 0; i--) {
const session = sessions[i];
const first = session.find(m => m.role === 'user');
const title = first ? truncate(first.content, 32) : 'Cuộc trò chuyện';
const isActive = i === currentSessionIndex;
const item = document.createElement('div');
item.className = `history-item ${isActive ? 'active' : ''}`;
item.innerHTML = `
<i class="ri-chat-1-line"></i>
<span class="history-title">${escapeHtml(title)}</span>
<button class="history-delete" onclick="deleteSession(event, ${i})" title="Xóa cuộc trò chuyện">
<i class="ri-close-line"></i>
</button>
`;
item.onclick = () => loadSession(i);
list.appendChild(item);
}
}
function deleteSession(e, index) {
e.stopPropagation(); // không trigger loadSession
sessions.splice(index, 1);
localStorage.setItem('chatSessions', JSON.stringify(sessions));
// Nếu đang xem session bị xóa → reset về màn welcome
if (currentSessionIndex === index) {
history = [];
currentSessionIndex = null;
const messages = document.getElementById('chatMessages');
messages.innerHTML = '';
messages.classList.remove('visible');
const welcome = document.getElementById('welcome');
if (welcome) welcome.classList.remove('hidden');
const composerBottom = document.getElementById('composerBottom');
if (composerBottom) composerBottom.style.display = 'none';
setRandomTitle();
const msgInput = document.getElementById('msgInput');
if (msgInput) { msgInput.value = ''; msgInput.style.height = 'auto'; }
} else if (currentSessionIndex !== null && index < currentSessionIndex) {
// Session bị xóa nằm trước session hiện tại → index lùi 1
currentSessionIndex--;
}
renderHistory();
}
function loadSession(index) {
currentSessionIndex = index;
history = [...sessions[index]];
// Clear and rebuild chat
const messages = document.getElementById('chatMessages');
messages.innerHTML = '';
showChat();
const wrap = document.createElement('div');
wrap.className = 'message-wrap';
messages.appendChild(wrap);
for (const msg of history) {
if (msg.role === 'user') {
const div = document.createElement('div');
div.className = 'msg-user';
div.innerHTML = `<div class="msg-bubble">${escapeHtml(msg.content)}</div>`;
wrap.appendChild(div);
} else if (msg.role === 'assistant') {
const id = 'bot-' + Date.now() + Math.random();
const div = document.createElement('div');
div.className = 'msg-bot';
div.id = id;
div.innerHTML = `
<div class="msg-avatar"><i class="ri-graduation-cap-fill"></i></div>
<div class="msg-bubble">${renderMarkdown(msg.content)}</div>
`;
wrap.appendChild(div);
}
}
renderHistory();
scrollToBottom();
}
document.getElementById('btnNewChat').onclick = function () {
if (history.length > 0) {
saveSession();
}
history = [];
currentSessionIndex = null;
const messages = document.getElementById('chatMessages');
messages.innerHTML = '';
messages.classList.remove('visible');
const welcome = document.getElementById('welcome');
if (welcome) welcome.classList.remove('hidden');
const composerBottom = document.getElementById('composerBottom');
if (composerBottom) composerBottom.style.display = 'none';
// Reset title ngẫu nhiên
setRandomTitle();
// Focus vào ô input welcome
const msgInput = document.getElementById('msgInput');
if (msgInput) { msgInput.value = ''; msgInput.style.height = 'auto'; msgInput.focus(); }
renderHistory();
switchTab('chat');
};
// ============================================================
// CEFR ANALYSIS
// ============================================================
function setCEFRExample(btn) {
document.getElementById('cefrInput').value = btn.textContent.trim();
}
async function analyzeCEFR() {
const text = document.getElementById('cefrInput').value.trim();
if (!text) return;
const output = document.getElementById('cefrOutput');
output.innerHTML = `
<div class="loading-overlay">
<div class="spinner"></div>
<span>Đang phân tích...</span>
</div>
`;
try {
const res = await fetch('/api/cefr', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
});
const data = await res.json();
if (data.error) {
output.innerHTML = `<div class="cefr-empty"><div class="empty-title">${escapeHtml(data.error)}</div></div>`;
return;
}
const distributionHtml = data.distribution.map(d => `
<div class="dist-row">
<div class="dist-label">
<span class="cefr-dot" style="background:${d.color}"></span>
<span class="cefr-lvl">${d.level}</span>
<span class="cefr-name">${d.desc}</span>
</div>
<div class="dist-track">
<div class="dist-fill" style="width:${d.pct}%;background:${d.color}"></div>
</div>
<div class="dist-value">${d.count} · ${d.pct}%</div>
</div>
`).join('');
output.innerHTML = `
<div class="cefr-result">
<div class="level-hero" style="--hero-color:${data.vocab_color}">
<div class="hero-left">
<div class="eyebrow">VOCABULARY PROFILE</div>
<div class="hero-level">${data.vocab_level || 'N/A'}</div>
<div class="hero-desc">${data.vocab_desc || 'Chưa xác định'}</div>
<div class="hero-note">Dựa trên mức trần từ vựng: level cao nhất có ít nhất 2 từ đạt được (bỏ qua từ chức năng).</div>
</div>
<div class="hero-ring">
<span>${data.known_pct}%</span>
<small>recognized</small>
</div>
</div>
<div class="result-section">
<div class="section-heading">
<h3><i class="ri-bar-chart-2-line"></i> Phân bố CEFR</h3>
<p>Phân bố theo số lần xuất hiện của từ.</p>
</div>
<div class="distribution">${distributionHtml}</div>
</div>
<div class="result-section">
<div class="section-heading">
<h3><i class="ri-markup-line"></i> Văn bản đã phân tích</h3>
<p>Click vào từ được tô màu để xem nghĩa tiếng Việt.</p>
</div>
<div class="highlight-box">${data.highlighted}</div>
</div>
<div class="cefr-disclaimer">
<i class="ri-information-line"></i>
<span><strong>Lưu ý:</strong> Đây là phân tích từ vựng theo CEFR, chưa phải bài đánh giá CEFR đầy đủ cho Reading, Writing, Listening và Speaking.</span>
</div>
</div>
`;
} catch (err) {
output.innerHTML = `<div class="cefr-empty"><div class="empty-title">Lỗi kết nối: ${escapeHtml(err.message)}</div></div>`;
}
}
// ============================================================
// HELPERS
// ============================================================
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function truncate(str, max) {
return str.length > max ? str.slice(0, max) + '…' : str;
}
function renderMarkdown(text) {
// Bold
text = text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
// Italic
text = text.replace(/\*(.+?)\*/g, '<em>$1</em>');
// Inline code
text = text.replace(/`([^`]+)`/g, '<code>$1</code>');
// Code block
text = text.replace(/```[\w]*\n?([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
// Heading 3
text = text.replace(/^### (.+)$/gm, '<h3>$1</h3>');
// Heading 2
text = text.replace(/^## (.+)$/gm, '<h2>$1</h2>');
// Heading 1
text = text.replace(/^# (.+)$/gm, '<h1>$1</h1>');
// HR
text = text.replace(/^---$/gm, '<hr>');
// Unordered list
text = text.replace(/^\s*[-*] (.+)$/gm, '<li>$1</li>');
text = text.replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>');
// Ordered list
text = text.replace(/^\d+\. (.+)$/gm, '<li>$1</li>');
// Paragraph
text = text.replace(/\n{2,}/g, '</p><p>');
text = '<p>' + text + '</p>';
// Line break
text = text.replace(/\n/g, '<br>');
// Clean up empty paragraphs
text = text.replace(/<p>\s*<\/p>/g, '');
return text;
}
// ============================================================
// CEFR FULL ANALYSIS
// ============================================================
async function analyzeCEFRFull() {
const text = document.getElementById('cefrInput').value.trim();
if (!text) return;
const output = document.getElementById('cefrOutput');
output.innerHTML = `
<div class="loading-overlay">
<div class="spinner"></div>
<span>Đang đánh giá toàn văn...</span>
</div>
`;
try {
const res = await fetch('/api/cefr-full', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
});
const data = await res.json();
if (data.error) {
output.innerHTML = `<div class="cefr-empty"><div class="empty-title">${escapeHtml(data.error)}</div></div>`;
return;
}
const g = data.components.grammar;
const v = data.components.vocabulary;
const r = data.components.readability;
const featuresHtml = g.features.map(f =>
`<span style="background:${g.color}18;border:1px solid ${g.color}40;color:${g.color};
padding:3px 10px;border-radius:12px;font-size:11px;font-weight:500">${escapeHtml(f)}</span>`
).join('');
output.innerHTML = `
<div class="cefr-result">
<div class="level-hero" style="--hero-color:${data.final_color}">
<div class="hero-left">
<div class="eyebrow">OVERALL CEFR LEVEL</div>
<div class="hero-level">${data.final_level}</div>
<div class="hero-desc">${data.final_desc}</div>
<div class="hero-note">Đánh giá tổng hợp: ngữ pháp, từ vựng và độ phức tạp câu.</div>
</div>
<div class="hero-ring">
<span>${data.final_level}</span>
<small>overall</small>
</div>
</div>
<div class="metric-grid" style="grid-template-columns:repeat(3,1fr);margin-top:14px">
<div class="metric-card" style="border-top:3px solid ${g.color}">
<div class="metric-value" style="color:${g.color}">${g.level}</div>
<div class="metric-label"><i class="ri-code-s-slash-line"></i> Ngữ pháp</div>
</div>
<div class="metric-card" style="border-top:3px solid ${v.color}">
<div class="metric-value" style="color:${v.color}">${v.level}</div>
<div class="metric-label"><i class="ri-text"></i> Từ vựng</div>
</div>
<div class="metric-card" style="border-top:3px solid ${r.color}">
<div class="metric-value" style="color:${r.color}">${r.level}</div>
<div class="metric-label"><i class="ri-bar-chart-line"></i> Độ phức tạp</div>
</div>
</div>
<div class="result-section" style="margin-top:16px">
<div class="section-heading">
<h3><i class="ri-code-s-slash-line"></i> Đặc điểm ngữ pháp phát hiện</h3>
</div>
<div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:8px">${featuresHtml || '<span style="color:var(--text-muted);font-size:12px">Cấu trúc cơ bản</span>'}</div>
</div>
<div class="result-section">
<div class="section-heading">
<h3><i class="ri-bar-chart-2-line"></i> Thống kê độ phức tạp</h3>
</div>
<div class="metric-grid" style="grid-template-columns:repeat(3,1fr)">
<div class="metric-card">
<div class="metric-value">${r.grade}</div>
<div class="metric-label"><i class="ri-graduation-cap-line"></i> Grade Level</div>
</div>
<div class="metric-card">
<div class="metric-value">${r.avg_sentence_length}</div>
<div class="metric-label"><i class="ri-text-wrap"></i> Từ/câu TB</div>
</div>
<div class="metric-card">
<div class="metric-value">${r.avg_syllables}</div>
<div class="metric-label"><i class="ri-sound-module-line"></i> Âm tiết/từ TB</div>
</div>
</div>
</div>
<div class="result-section">
<div class="section-heading">
<h3><i class="ri-scales-line"></i> Trọng số đánh giá</h3>
</div>
<div class="distribution">
<div class="dist-row">
<div class="dist-label">
<span class="cefr-dot" style="background:${g.color}"></span>
<span class="cefr-lvl">Ngữ pháp</span>
</div>
<div class="dist-track"><div class="dist-fill" style="width:40%;background:${g.color}"></div></div>
<div class="dist-value">40%</div>
</div>
<div class="dist-row">
<div class="dist-label">
<span class="cefr-dot" style="background:${v.color}"></span>
<span class="cefr-lvl">Từ vựng</span>
</div>
<div class="dist-track"><div class="dist-fill" style="width:35%;background:${v.color}"></div></div>
<div class="dist-value">35%</div>
</div>
<div class="dist-row">
<div class="dist-label">
<span class="cefr-dot" style="background:${r.color}"></span>
<span class="cefr-lvl">Độ phức tạp</span>
</div>
<div class="dist-track"><div class="dist-fill" style="width:25%;background:${r.color}"></div></div>
<div class="dist-value">25%</div>
</div>
</div>
</div>
<div class="cefr-disclaimer">
<i class="ri-information-line"></i>
<span><strong>Lưu ý:</strong> Đánh giá dựa trên ngữ pháp (spaCy), từ vựng (Zenodo + cefrpy) và độ phức tạp câu (textstat). Không thay thế bài kiểm tra CEFR chính thức.</span>
</div>
</div>
`;
} catch (err) {
output.innerHTML = `<div class="cefr-empty"><div class="empty-title">Lỗi: ${escapeHtml(err.message)}</div></div>`;
}
}
// ============================================================
// WORD SUGGESTIONS (từ chat)
// ============================================================
function showWordSuggestions(botId, words) {
if (!words || words.length === 0) return;
const el = document.getElementById(botId);
if (!el) return;
const existing = el.querySelector('.word-suggestions');
if (existing) existing.remove();
const div = document.createElement('div');
div.className = 'word-suggestions';
div.style.cssText = `
margin-top:12px;padding-top:12px;
border-top:1px solid rgba(255,255,255,0.06);
display:flex;flex-wrap:wrap;gap:8px;align-items:center;
`;
const label = document.createElement('span');
label.style.cssText = 'font-size:11px;color:#4a5568;font-weight:600;width:100%;margin-bottom:2px';
label.textContent = 'Từ khó phát hiện trong câu hỏi:';
div.appendChild(label);
words.forEach(w => {
const alreadySaved = savedWords.some(s => s.lemma === w.lemma);
const chip = document.createElement('div');
chip.style.cssText = `
display:inline-flex;align-items:center;gap:8px;
background:${w.color}18;border:1px solid ${w.color}40;
border-radius:10px;padding:6px 12px;font-size:13px;
`;
chip.innerHTML = `
<span style="color:${w.color};font-weight:600">${escapeHtml(w.word)}</span>
<span style="color:${w.color};opacity:0.7;font-size:11px">${w.level}</span>
<button
onclick="saveWordFromChat('${escapeHtml(w.word)}','${escapeHtml(w.lemma)}','${w.level}','${w.color}','${escapeHtml(w.desc)}',this)"
style="background:${alreadySaved ? 'transparent' : w.color};
color:${alreadySaved ? w.color : 'white'};
border:1px solid ${w.color};border-radius:6px;
padding:3px 8px;font-size:11px;cursor:pointer;font-weight:500"
${alreadySaved ? 'disabled' : ''}
>${alreadySaved ? '✓ Đã lưu' : '+ Lưu'}</button>
`;
div.appendChild(chip);
});
el.querySelector('.msg-bubble').appendChild(div);
scrollToBottom();
}
function saveWordFromChat(word, lemma, level, color, desc, btn) {
if (!isLoggedIn()) { showAuthModal(); return; }
if (savedWords.some(s => s.lemma === lemma)) return;
savedWords.push({ word, lemma, level, color, desc, savedAt: Date.now() });
persistSavedWords();
btn.textContent = '✓ Đã lưu';
btn.style.background = 'transparent';
btn.style.color = color;
btn.disabled = true;
updateBookmarkCount();
renderSavedWordsPanel();
}
// ============================================================
// BOOKMARK PANEL
// ============================================================
function toggleBookmarkPanel() {
if (!isLoggedIn()) { showAuthModal(); return; }
const panel = document.getElementById('savedWordsPanel');
const backdrop = document.getElementById('swpBackdrop');
const isOpen = panel.classList.contains('open');
if (isOpen) {
panel.classList.remove('open');
backdrop.classList.remove('open');
} else {
renderSavedWordsPanel();
panel.classList.add('open');
backdrop.classList.add('open');
}
}