Repository navigation
Expand file tree
/
Copy pathchatbot.js
More file actions
1329 lines (1210 loc) · 59.1 KB
/
Copy pathchatbot.js
File metadata and controls
1329 lines (1210 loc) · 59.1 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
/* ────────────────────────────────────────────────────────────
AI Interview Coach — Gemini-powered chatbot
Context bám sát bộ câu hỏi trong questions.json
──────────────────────────────────────────────────────────── */
(() => {
'use strict';
const KEY_API = 'java_qa_gemini_key'; // định dạng cũ (1 key) — chỉ còn để migrate
const KEY_KEYS = 'java_qa_gemini_keys'; // tách riêng, KHÔNG nằm trong export JSON
const KEY_MODEL = 'java_qa_gemini_model';
const KEY_CHAT = 'java_qa_chat_history';
const KEY_MODE = 'java_qa_ui_mode'; // 'split' (mặc định) | 'float'
const KEY_SUGG = 'java_qa_ai_suggestions';
const KEY_SCORE = 'java_qa_interview_scores'; // điểm chấm phỏng vấn theo từng câu
const DEFAULT_MODEL = 'gemini-3.5-flash';
const SUGG_TTL = 6 * 60 * 60 * 1000; // cache gợi ý AI 6 giờ
const API = (m, method) => `https://generativelanguage.googleapis.com/v1beta/models/${m}:${method}`;
const getModel = () => localStorage.getItem(KEY_MODEL) || DEFAULT_MODEL;
/* ── Kho API key ────────────────────────────────────────
Nhiều key xoay vòng: key nào dính 429 thì bị "nghỉ" (cd = hết nghỉ lúc nào),
key nào sai/hỏng thì đánh dấu bad và bỏ qua hẳn cho tới khi user Test lại.
Mỗi phần tử: { k: 'AIza…', cd?: timestamp, bad?: 'lý do' } */
function loadKeys() {
let arr = [];
try { arr = JSON.parse(localStorage.getItem(KEY_KEYS)) || []; } catch {}
if (!Array.isArray(arr)) arr = [];
arr = arr.filter(x => x && typeof x.k === 'string' && x.k.trim());
const legacy = (localStorage.getItem(KEY_API) || '').trim(); // migrate key đơn cũ
if (legacy && !arr.some(x => x.k === legacy)) arr.unshift({ k: legacy });
return arr;
}
function saveKeys(arr) {
try {
localStorage.setItem(KEY_KEYS, JSON.stringify(arr));
localStorage.removeItem(KEY_API); // đã gộp vào danh sách
} catch {}
}
const isReady = x => !x.bad && (!x.cd || x.cd <= Date.now());
// Mỗi key chạy model riêng; chưa chọn thì theo model mặc định trong Settings
const keyModel = x => x.m || getModel();
const hasKey = () => loadKeys().length > 0;
function fmtWait(ms) {
const s = Math.max(0, Math.ceil(ms / 1000));
return s < 60 ? s + 's' : Math.floor(s / 60) + 'p' + String(s % 60).padStart(2, '0');
}
function patchKey(k, patch) {
const arr = loadKeys();
const e = arr.find(x => x.k === k);
if (!e) return;
Object.assign(e, patch);
if (patch.cd === null) delete e.cd;
if (patch.bad === null) delete e.bad;
saveKeys(arr);
paintKeys();
}
// 429 có kèm RetryInfo.retryDelay và QuotaFailure.quotaId → dùng để định thời gian nghỉ
function quotaWait(err) {
const d = err?.error?.details || [];
const retry = d.find(x => String(x['@type']).includes('RetryInfo'))?.retryDelay;
const m = /^([\d.]+)s$/.exec(retry || '');
if (m) return Math.max(20e3, Math.ceil(parseFloat(m[1]) * 1000));
const q = d.find(x => String(x['@type']).includes('QuotaFailure'))?.violations?.[0]?.quotaId || '';
return /PerDay/i.test(q) ? 15 * 60e3 : 60e3; // hết quota ngày thì nghỉ lâu hơn
}
const getMode = () => localStorage.getItem(KEY_MODE) || 'split';
// ── Utils ───────────────────────────────────────────────
const COMBINING = new RegExp('[' + String.fromCharCode(0x300) + '-' + String.fromCharCode(0x36f) + ']', 'g');
// Giữ nguyên độ dài chuỗi để prefix-match ghost text khớp vị trí ký tự
const deaccent = s => s.normalize('NFD').replace(COMBINING, '').replace(/đ/g, 'd').replace(/Đ/g, 'D').toLowerCase();
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const STOP = new Set('la gi cua va cho co the nao khi nhu duoc voi trong den mot cac nhung ra thi de bang khac nhau ve tai sao lam viec giua what how why is the a an of to in for and or'.split(' '));
const tokenize = s => deaccent(s).split(/[^a-z0-9+#.]+/).filter(t => t.length > 1 && !STOP.has(t));
const stripHtml = (() => {
const div = document.createElement('div');
return html => { div.innerHTML = html; return div.textContent.replace(/\n{3,}/g, '\n\n').replace(/[ \t]{2,}/g, ' ').trim(); };
})();
// ── Question index (RAG-lite) ───────────────────────────
let INDEX = [];
function buildIndex() {
if (INDEX.length) return true;
const data = window.QA_DATA;
if (!data || !data.length) return false;
INDEX = data.map(q => ({
num: q.num, question: q.question, level: q.level, section: q.section,
subsection: q.subsection || '', tags: q.tags || '', html: q.answerHtml,
_q: deaccent(q.question), _meta: deaccent(`${q.tags} ${q.section} ${q.subsection || ''}`), _a: null
}));
return true;
}
const answerText = e => (e._a ??= stripHtml(e.html));
const byNum = n => INDEX.find(e => e.num === Number(n));
/* Token ngắn phải khớp trọn tiếng, không khớp kiểu substring:
"so" mà substring thì trúng cả "re-so-urce" → gợi ý lạc đề.
Regex compile 1 lần cho mỗi token rồi tái dùng cho cả 262 câu. */
const RE_ESC = /[.*+?^${}()|[\]\\]/g;
function prepTerms(query) {
return tokenize(query).map(t => ({
t,
re: t.length > 3 ? null : new RegExp('(^|[^a-z0-9])' + t.replace(RE_ESC, '\\$&') + '([^a-z0-9]|$)')
}));
}
const hit = (hay, x) => x.re ? x.re.test(hay) : hay.includes(x.t);
function search(query, limit = 6) {
if (!buildIndex()) return [];
const terms = prepTerms(query);
if (!terms.length) return [];
/* Hạ trọng số từ quá phổ biến. "hoạt động" nằm trong hàng chục tiêu đề nên
nếu tính ngang "hashmap" thì "HashSet hoạt động…" đội lên bằng
"HashMap vs HashTable…". Tự đo tần suất, không cần nuôi stopword list. */
const df = terms.map(() => 0);
const marks = [];
for (const e of INDEX) {
let m = null;
terms.forEach((t, j) => {
const inQ = hit(e._q, t);
const inM = hit(e._meta, t);
if (inQ || inM) { (m ||= []).push([j, inQ, inM]); if (inQ) df[j]++; }
});
marks.push(m);
}
const cap = INDEX.length * 0.08;
let common = df.map(n => n > cap);
if (common.every(Boolean)) common = df.map(() => false); // mọi từ đều phổ biến → đừng hạ hết
const scored = [];
INDEX.forEach((e, i) => {
const m = marks[i];
if (!m) return;
let s = 0;
for (const [j, inQ, inM] of m) {
const w = common[j] ? 0.25 : 1;
if (inQ) s += 4 * w;
if (inM) s += 2 * w;
}
if (s > 0) scored.push({ e, s });
});
// Chỉ quét toàn bộ đáp án khi kết quả theo tiêu đề quá ít
if (scored.length < limit) {
const seen = new Set(scored.map(x => x.e));
const need = Math.max(1, terms.length - 1);
for (const e of INDEX) {
if (seen.has(e)) continue;
const a = deaccent(answerText(e));
let s = 0;
for (const t of terms) if (hit(a, t)) s += 1;
if (s >= need) scored.push({ e, s });
}
}
return scored.sort((a, b) => b.s - a.s).slice(0, limit).map(x => x.e);
}
// ── Prompt ──────────────────────────────────────────────
function outline() {
if (!buildIndex()) return '';
const map = new Map();
for (const e of INDEX) {
if (!map.has(e.section)) map.set(e.section, new Map());
const subs = map.get(e.section);
const k = e.subsection || '-';
subs.set(k, (subs.get(k) || 0) + 1);
}
return [...map].map(([sec, subs]) =>
`- ${sec}: ${[...subs].map(([s, n]) => `${s} (${n})`).join(', ')}`).join('\n');
}
const SYSTEM = () => `Bạn là "AI Interview Coach" — trợ lý luyện phỏng vấn Java/Spring Boot backend cho thị trường tuyển dụng Việt Nam.
PHẠM VI (bắt buộc):
Chỉ trả lời trong phạm vi bộ câu hỏi phỏng vấn của trang này: Java Core, Spring Boot, Kafka, Redis, Microservice, Database, Cloud, DevOps, Architecture, System Design, ELK Stack, Testing — cùng các chủ đề phụ trợ trực tiếp (CV/JD backend, lộ trình ôn tập, cách trả lời phỏng vấn, kỳ vọng theo level).
Nếu câu hỏi nằm ngoài phạm vi, từ chối ngắn gọn trong 1 câu rồi gợi ý 2 câu hỏi thuộc phạm vi.
CẤU TRÚC BỘ CÂU HỎI (${INDEX.length} câu):
${outline()}
CÁCH TRẢ LỜI:
1. Ưu tiên tuyệt đối nội dung trong "NGỮ CẢNH" được cung cấp. Khi dùng, trích số câu dạng #12.
2. Nếu NGỮ CẢNH không đủ, được phép bổ sung kiến thức của bạn nhưng phải ghi rõ "(ngoài bộ câu hỏi)".
3. Bám sát yêu cầu tuyển dụng hiện tại: Java 17/21 (virtual threads, records, pattern matching), Spring Boot 3.x + Jakarta EE, GraalVM native, observability (OpenTelemetry, Micrometer), event-driven với Kafka, Kubernetes, và tích hợp AI/LLM vào backend. Khi liên quan, nêu rõ nhà tuyển dụng thường đào sâu điểm nào và bẫy thường gặp.
4. Trả lời bằng tiếng Việt; thuật ngữ kỹ thuật giữ nguyên tiếng Anh.
5. NGẮN GỌN: mặc định dưới 200 từ, ưu tiên gạch đầu dòng. Code chỉ khi thực sự cần, tối đa khoảng 15 dòng.
6. Kết thúc bằng đúng 1 dòng: "👉 Follow-up: <câu hỏi nhà tuyển dụng sẽ hỏi tiếp>".`;
// Câu đã dùng làm ngữ cảnh cho lượt vừa rồi → không gợi ý hỏi lại chính nó
let lastCtxNums = new Set();
function buildContext(query, pinned) {
const hits = search(query, 6);
if (pinned && !hits.includes(pinned)) hits.unshift(pinned);
lastCtxNums = new Set(hits.slice(0, 6).map(e => e.num));
if (!hits.length) return '';
return 'NGỮ CẢNH (trích từ bộ câu hỏi):\n\n' + hits.slice(0, 6).map(e =>
`[#${e.num} | ${e.section}${e.subsection ? ' > ' + e.subsection : ''} | ${e.level} | tags: ${e.tags}]\nQ: ${e.question}\nA: ${answerText(e).slice(0, 1200)}`
).join('\n\n---\n\n');
}
/* ── Sổ điểm phỏng vấn ──────────────────────────────────
{ [num]: { best, last, count, at } } — chỉ để người học thấy mình tiến bộ,
không đồng bộ đi đâu cả. */
function loadScores() {
try { return JSON.parse(localStorage.getItem(KEY_SCORE)) || {}; } catch { return {}; }
}
function saveScore(num, score) {
const all = loadScores();
const cur = all[num] || { best: 0, count: 0 };
const rec = {
best: Math.max(cur.best || 0, score),
last: score,
count: (cur.count || 0) + 1,
at: Date.now()
};
all[num] = rec;
try { localStorage.setItem(KEY_SCORE, JSON.stringify(all)); } catch {}
return { rec, isBest: score > (cur.best || 0) && (cur.count || 0) > 0 };
}
// ── Mini markdown ───────────────────────────────────────
const PH = i => '%%CBBLOCK' + i + '%%';
function md(src) {
const blocks = [];
let t = esc(src).replace(/```(\w*)\n?([\s\S]*?)```/g, (_, lang, code) =>
PH(blocks.push(`<pre class="cb-code"><code>${code.replace(/\n$/, '')}</code></pre>`) - 1));
t = t.replace(/`([^`\n]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|\s)\*([^*\n]+)\*/g, '$1<em>$2</em>')
.replace(/#(\d{1,3})\b/g, '<a class="cb-ref" href="#q$1" data-q="$1">#$1</a>');
const out = [];
let list = null;
for (const line of t.split('\n')) {
const ul = line.match(/^\s*[-*•]\s+(.*)/);
const ol = line.match(/^\s*\d+[.)]\s+(.*)/);
const h = line.match(/^#{1,4}\s+(.*)/);
const tag = ul ? 'ul' : ol ? 'ol' : null;
if (tag) {
if (list !== tag) { if (list) out.push(`</${list}>`); out.push(`<${tag}>`); list = tag; }
out.push(`<li>${(ul || ol)[1]}</li>`);
continue;
}
if (list) { out.push(`</${list}>`); list = null; }
const ph = line.trim().match(/^%%CBBLOCK(\d+)%%$/); // code block đứng riêng → không bọc <p>
if (ph) out.push(blocks[ph[1]]);
else if (h) out.push(`<h4>${h[1]}</h4>`);
else if (line.trim()) out.push(`<p>${line}</p>`);
}
if (list) out.push(`</${list}>`);
return out.join('').replace(/%%CBBLOCK(\d+)%%/g, (_, i) => blocks[i]);
}
// ── State ───────────────────────────────────────────────
let messages = [];
let busy = false, controller = null;
let suggestions = [], sugIdx = 0; // pool đang dùng cho ghost text
let aiSuggestions = []; // gợi ý do AI sinh theo ngữ cảnh
let pinned = null; // câu hỏi đang "Hỏi AI về câu này"
let chips = [];
let interviewMode = false; // true → mọi thứ gõ vào là câu TRẢ LỜI, AI chấm điểm
let gradedOnce = false; // đã chấm ít nhất 1 lần cho câu đang ghim
// Fallback khi AI chưa load được
const FALLBACK_SUGG = [
'Lộ trình ôn phỏng vấn Middle Java trong 2 tuần?',
'Virtual Threads (Java 21) thay ThreadPool được không?',
'Kafka đảm bảo exactly-once bằng cách nào?',
'Cách chống N+1 query trong JPA?',
'Thiết kế hệ thống rút gọn URL chịu 10k RPS?',
'Nhà tuyển dụng Senior Java hiện nay đào sâu những gì?'
];
const FALLBACK_CHIPS = [
'Giải thích đơn giản hơn',
'Cho ví dụ code thực tế',
'Nhà tuyển dụng sẽ đào sâu thế nào?',
'Câu hỏi bẫy thường gặp?',
'So sánh với giải pháp thay thế'
];
/* Chip của chế độ phỏng vấn. ask:1 = câu HỎI (bấm vào sẽ tự thoát chế độ chấm
điểm), không có ask = nội dung gửi đi như một câu TRẢ LỜI. */
const INTERVIEW_CHIPS = [
{ t: 'Mình chưa biết câu này' },
{ t: 'Gợi ý dàn ý trước đã', ask: 1 }
];
const INTERVIEW_CHIPS_AFTER = [
{ t: 'Giải thích chỗ mình sai', ask: 1 },
{ t: 'Đáp án mẫu đầy đủ hơn', ask: 1 },
{ t: 'Interviewer vặn tiếp gì?', ask: 1 },
{ t: 'Câu tương tự để luyện thêm', ask: 1 }
];
const loadHistory = () => { try { messages = JSON.parse(localStorage.getItem(KEY_CHAT)) || []; } catch { messages = []; } };
const saveHistory = () => { try { localStorage.setItem(KEY_CHAT, JSON.stringify(messages.slice(-30))); } catch {} };
// ── Gemini transport ────────────────────────────────────
// Mỗi thế hệ model nhận cấu hình "thinking" khác nhau; nếu API từ chối thì
// thử lại đúng 1 lần với body đã bỏ thinkingConfig.
function thinkingFor(model) {
if (model.startsWith('gemini-3')) return { thinkingLevel: 'low' };
if (model.includes('flash')) return { thinkingBudget: 0 }; // 2.5 flash / flash-lite
return null; // 2.5 pro: không tắt được
}
// Gọi bằng ĐÚNG 1 key. Model từ chối thinkingConfig thì thử lại 1 lần đã bỏ field.
async function rawCall(k, model, method, payload, signal) {
const url = API(model, method) + (method.startsWith('stream') ? '?alt=sse' : '');
const send = p => fetch(url, {
method: 'POST', signal,
headers: { 'content-type': 'application/json', 'x-goog-api-key': k },
body: JSON.stringify(p)
});
let res = await send(payload);
if (res.status === 400 && payload.generationConfig?.thinkingConfig) {
const { thinkingConfig, ...rest } = payload.generationConfig;
res = await send({ ...payload, generationConfig: rest });
}
return res;
}
const KEY_IS_BAD = /api key not valid|api_key_invalid|api key expired|api key must be set/i;
// Thông báo đã soạn sẵn cho người dùng — explain() phải để nguyên, đừng dịch lại
function friendly(msg) { const e = new Error(msg); e.friendly = true; return e; }
/* Xoay vòng key: hết quota (429) hoặc key hỏng thì tự nhảy sang key kế tiếp.
Lỗi không liên quan tới key (payload sai, 5xx…) thì ném ra luôn,
đổi key cũng vô ích mà còn đốt thêm request. */
async function callGemini(method, makeBody, signal) {
const all = loadKeys();
if (!all.length) throw friendly('Chưa có API key nào — mở Settings để thêm.');
const usable = all.filter(isReady);
if (!usable.length) {
const cds = all.filter(x => x.cd).map(x => x.cd);
const bad = all.filter(x => x.bad).length;
throw friendly(cds.length
? `Cả ${all.length} key đều hết quota — key sớm nhất mở lại sau ${fmtWait(Math.min(...cds) - Date.now())}`
: `Cả ${bad} key đều lỗi — mở Settings bấm Test để kiểm tra lại.`);
}
let lastErr = null;
for (const entry of usable) {
// body dựng lại cho từng key vì thinkingConfig/token phụ thuộc model của key đó
const model = keyModel(entry);
const res = await rawCall(entry.k, model, method, makeBody(model), signal);
if (res.ok) {
if (entry.cd || entry.bad) patchKey(entry.k, { cd: null, bad: null });
activeKey = entry.k;
activeModel = model;
if (el.cbModel) el.cbModel.textContent = modelLabel();
paintStatusLine();
return res;
}
const err = await res.json().catch(() => null);
const msg = err?.error?.message || `HTTP ${res.status} ${res.statusText}`;
lastErr = new Error(msg);
if (res.status === 429) {
patchKey(entry.k, { cd: Date.now() + quotaWait(err) });
continue; // → key kế tiếp
}
if (res.status === 403 || res.status === 404 ||
(res.status === 400 && KEY_IS_BAD.test(msg))) {
patchKey(entry.k, { bad: explain(msg, model) });
continue; // → key kế tiếp
}
throw lastErr; // lỗi không phải do key
}
throw lastErr || new Error('Không key nào gọi được');
}
// Gemini phát text tăng dần qua SSE; gói thành generator cho send() dễ dùng
async function* streamAnswer(req, signal) {
const res = await callGemini('streamGenerateContent', model => {
const think = thinkingFor(model);
return {
systemInstruction: { parts: [{ text: req.system }] },
contents: [
...req.history.map(m => ({ role: m.role, parts: [{ text: m.text }] })),
{ role: 'user', parts: [{ text: req.prompt }] }
],
generationConfig: {
temperature: 0.6,
maxOutputTokens: model.includes('pro') ? 4096 : 2048,
...(think ? { thinkingConfig: think } : {})
}
};
}, signal);
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
const lines = buf.split('\n');
buf = lines.pop();
let out = '';
for (const line of lines) {
if (!line.startsWith('data:')) continue;
const payload = line.slice(5).trim();
if (!payload || payload === '[DONE]') continue;
try {
const chunk = JSON.parse(payload);
for (const p of chunk?.candidates?.[0]?.content?.parts || []) {
if (!p.thought) out += p.text || '';
}
} catch {}
}
if (out) yield out;
}
}
// ── Gợi ý sinh bởi AI ───────────────────────────────────
const SUGG_SCHEMA = { type: 'ARRAY', items: { type: 'STRING' }, minItems: 4, maxItems: 5 };
function parseSuggList(raw) {
let s = String(raw).trim().replace(/^```(?:json)?\s*|\s*```$/g, '').trim();
const a = s.indexOf('['), b = s.lastIndexOf(']');
if (a !== -1 && b > a) s = s.slice(a, b + 1);
const arr = JSON.parse(s);
return Array.isArray(arr) ? arr.map(x => String(x).trim()).filter(Boolean).slice(0, 5) : [];
}
// Gọi 1 lượt non-stream, ép model trả JSON đúng schema
async function askJson(instruction, schema, opt = {}) {
const res = await callGemini('generateContent', model => {
const think = thinkingFor(model);
return {
contents: [{ role: 'user', parts: [{ text: instruction }] }],
generationConfig: {
temperature: opt.temperature ?? 0.9,
maxOutputTokens: opt.maxOutputTokens ?? 512,
responseMimeType: 'application/json',
responseSchema: schema,
...(think ? { thinkingConfig: think } : {})
}
};
}, opt.signal);
const data = await res.json();
return data?.candidates?.[0]?.content?.parts?.map(p => p.text || '').join('') || '';
}
async function askForSuggestions(instruction) {
return parseSuggList(await askJson(instruction, SUGG_SCHEMA) || '[]');
}
function applySuggestions(list) {
const seen = new Set();
const clean = list.map(s => String(s).trim()).filter(s => {
const k = deaccent(s);
if (!s || seen.has(k)) return false;
seen.add(k);
return true;
}).slice(0, 5);
if (!clean.length) return;
aiSuggestions = clean;
sugIdx = 0; // pool đổi thì quay về gợi ý đầu
if (el.cbText && !el.cbText.value.trim()) onInput();
}
/* Gợi ý tức thì sau khi model trả lời — không đợi thêm 1 vòng API.
Nguồn 1: dòng "👉 Follow-up:" model đã tự viết ở cuối câu trả lời.
Nguồn 2: câu trong bộ đề khớp với nội dung đáp án, TRỪ những câu vừa
được dùng làm ngữ cảnh (hỏi lại đúng cái vừa trả lời thì vô nghĩa). */
const FOLLOWUP_RE = /👉\s*Follow-?\s*up\s*[::]?\s*(.+)/i;
function seedFollowUps(question, answer) {
const out = [];
const m = answer.match(FOLLOWUP_RE);
if (m) {
const s = m[1].trim().replace(/^["'*\s]+|["'*\s]+$/g, '');
if (s) out.push(s);
}
/* Dò bộ đề bằng câu hỏi + dòng follow-up, KHÔNG bằng cả đoạn đáp án:
đáp án dài toàn từ phổ thông nên search sẽ khớp lung tung.
Dòng follow-up ngắn và chỉ đúng chủ đề kế tiếp nên là truy vấn tốt nhất. */
const probe = [out[0], question].filter(Boolean).join(' ');
for (const e of search(probe, 10)) {
if (out.length >= 5) break;
if (lastCtxNums.has(e.num)) continue;
out.push(e.question);
}
return out;
}
// Gợi ý "nguội": chưa có hội thoại → gợi ý mở đầu, cache 6h cho đỡ tốn quota
async function coldSuggestions() {
try {
const c = JSON.parse(localStorage.getItem(KEY_SUGG));
if (c && Date.now() - c.at < SUGG_TTL && c.items?.length) { applySuggestions(c.items); return; }
} catch {}
const sample = INDEX.filter((_, i) => i % 17 === 0).map(e => e.question).slice(0, 12);
const items = await askForSuggestions(`Bạn tạo gợi ý câu hỏi mở đầu cho một trang luyện phỏng vấn Java/Spring Boot backend (${INDEX.length} câu hỏi).
Các chủ đề có sẵn:
${outline()}
Ví dụ câu hỏi trong bộ đề:
${sample.map(s => '- ' + s).join('\n')}
Sinh 5 câu hỏi mà người dùng nhiều khả năng muốn hỏi trợ lý đầu tiên.
Yêu cầu: tiếng Việt, mỗi câu tối đa 70 ký tự, kết thúc bằng dấu hỏi, bám sát chủ đề trên và yêu cầu tuyển dụng backend hiện tại, không trùng ý nhau.
Trả về JSON array các string.`);
if (items.length) {
applySuggestions(items);
try { localStorage.setItem(KEY_SUGG, JSON.stringify({ at: Date.now(), items })); } catch {}
}
}
// Gợi ý "nóng": đào sâu vào ĐÚNG câu trả lời vừa đọc
async function followUpSuggestions(question, answer) {
const items = await askForSuggestions(`Người học vừa hỏi: "${question}"
Trợ lý đã trả lời:
${answer.slice(0, 2000)}
Sinh 5 câu hỏi TIẾP THEO đào sâu vào chính câu trả lời trên: trade-off, cách triển khai thực tế, trường hợp hỏng/giới hạn, cách đo đạc, hoặc hướng nhà tuyển dụng sẽ vặn tiếp.
Yêu cầu: tiếng Việt, mỗi câu tối đa 70 ký tự, kết thúc bằng dấu hỏi, KHÔNG lặp lại câu người học vừa hỏi, không hỏi chung chung, bám phạm vi Java/Spring backend.
Trả về JSON array các string.`);
if (items.length) applySuggestions(items);
}
async function refreshSuggestions() {
if (!hasKey() || !buildIndex()) return;
const last = messages[messages.length - 1];
const prevUser = [...messages].reverse().find(m => m.role === 'user');
try {
if (last?.role === 'model' && prevUser) await followUpSuggestions(prevUser.text, last.text);
else await coldSuggestions();
} catch { /* im lặng — seed + FALLBACK_SUGG vẫn còn đó */ }
}
/* Chip cho câu đang ghim. Trước khi hỏi: dựa trên đáp án có sẵn trong bộ đề.
Sau khi model trả lời: chuyển thành follow-up của chính câu trả lời đó. */
async function refreshChips(entry, lastAnswer) {
if (interviewMode) return;
if (!lastAnswer) { chips = FALLBACK_CHIPS.slice(); paintChips(); }
if (!hasKey()) return;
const prompt = lastAnswer
? `Câu hỏi phỏng vấn đang ôn: "${entry.question}".
Trợ lý vừa trả lời:
${lastAnswer.slice(0, 1400)}
Sinh 5 lời nhắc ngắn để người học bấm hỏi tiếp, đào sâu vào chính câu trả lời trên.
Yêu cầu: tiếng Việt, mỗi lời nhắc tối đa 34 ký tự, khác nhau rõ rệt, không lặp nội dung đã trả lời.
Trả về JSON array các string.`
: `Câu hỏi phỏng vấn: "${entry.question}" (chủ đề ${entry.section}, level ${entry.level}).
Đáp án tóm tắt: ${answerText(entry).slice(0, 700)}
Sinh 5 lời nhắc ngắn mà người học sẽ bấm để hỏi thêm về đúng câu này.
Yêu cầu: tiếng Việt, mỗi lời nhắc tối đa 34 ký tự, dạng mệnh lệnh hoặc câu hỏi ngắn, khác nhau rõ rệt.
Trả về JSON array các string.`;
try {
const items = await askForSuggestions(prompt);
if (items.length && pinned === entry && !interviewMode) { chips = items; paintChips(); }
} catch {}
}
/* ── Chế độ phỏng vấn: người học tự trả lời, AI chấm điểm ──
Bốn tiêu chí cộng lại đúng 10 điểm, tên và điểm tối đa cố định ở đây để
thanh bar vẽ được kể cả khi model trả về thiếu. */
const RUBRIC = [
{ name: 'Độ chính xác', max: 4 },
{ name: 'Độ đầy đủ', max: 3 },
{ name: 'Chiều sâu thực chiến', max: 2 },
{ name: 'Cách trình bày', max: 1 }
];
const GRADE_SCHEMA = {
type: 'OBJECT',
properties: {
score: { type: 'NUMBER' },
verdict: { type: 'STRING' },
level_estimate: { type: 'STRING' },
breakdown: {
type: 'ARRAY', minItems: 4, maxItems: 4,
items: {
type: 'OBJECT',
properties: { name: { type: 'STRING' }, score: { type: 'NUMBER' }, max: { type: 'NUMBER' }, note: { type: 'STRING' } },
required: ['name', 'score', 'max', 'note'],
propertyOrdering: ['name', 'score', 'max', 'note']
}
},
strengths: { type: 'ARRAY', items: { type: 'STRING' }, maxItems: 4 },
gaps: { type: 'ARRAY', items: { type: 'STRING' }, maxItems: 5 },
missing_keywords: { type: 'ARRAY', items: { type: 'STRING' }, maxItems: 8 },
model_answer: { type: 'STRING' },
followup: { type: 'STRING' }
},
required: ['score', 'verdict', 'breakdown', 'gaps', 'model_answer', 'followup'],
propertyOrdering: ['score', 'verdict', 'level_estimate', 'breakdown', 'strengths', 'gaps', 'missing_keywords', 'model_answer', 'followup']
};
function parseJsonLoose(raw) {
let t = String(raw).trim().replace(/^```(?:json)?\s*|\s*```$/g, '').trim();
const a = t.indexOf('{'), b = t.lastIndexOf('}');
if (a !== -1 && b > a) t = t.slice(a, b + 1);
return JSON.parse(t);
}
const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, Number(n) || 0));
const round5 = n => Math.round(n * 2) / 2;
// Model đôi khi đổi tên tiêu chí hoặc trả sai điểm tối đa → nắn lại theo RUBRIC
function normalizeGrade(g) {
const src = Array.isArray(g.breakdown) ? g.breakdown : [];
const breakdown = RUBRIC.map((r, i) => {
const f = src.find(x => deaccent(String(x?.name || '')).includes(deaccent(r.name).slice(0, 8))) || src[i] || {};
return { name: r.name, max: r.max, score: round5(clamp(f.score, 0, r.max)), note: String(f.note || '').trim() };
});
const sum = round5(breakdown.reduce((a, x) => a + x.score, 0));
const raw = clamp(g.score, 0, 10);
// Lệch nhiều giữa tổng tiêu chí và điểm model tự chấm thì tin phần tiêu chí
const score = Math.abs(raw - sum) > 1.5 ? sum : round5(raw);
const arr = k => (Array.isArray(g[k]) ? g[k] : []).map(x => String(x).trim()).filter(Boolean);
return {
score, breakdown,
verdict: String(g.verdict || '').trim(),
level_estimate: String(g.level_estimate || '').trim(),
strengths: arr('strengths').slice(0, 4),
gaps: arr('gaps').slice(0, 5),
missing_keywords: arr('missing_keywords').slice(0, 8),
model_answer: String(g.model_answer || '').trim(),
followup: String(g.followup || '').trim()
};
}
async function gradeAnswer(entry, userAnswer, signal) {
const where = entry.section + (entry.subsection ? ' > ' + entry.subsection : '');
const raw = await askJson(`Bạn là interviewer backend Java/Spring Boot nhiều năm kinh nghiệm, đang phỏng vấn ứng viên tại Việt Nam.
CÂU HỎI (#${entry.num} · ${where} · level ${entry.level}):
${entry.question}
ĐÁP ÁN THAM CHIẾU (chuẩn của bộ đề, dùng làm mốc chấm — không đọc lại nguyên văn cho ứng viên):
${answerText(entry).slice(0, 3000)}
CÂU TRẢ LỜI CỦA ỨNG VIÊN:
"""
${String(userAnswer).slice(0, 4000)}
"""
Chấm nghiêm túc như phỏng vấn thật, thang 10, chia đúng 4 tiêu chí sau (giữ nguyên tên và điểm tối đa):
${RUBRIC.map(r => `- "${r.name}" tối đa ${r.max}`).join('\n')}
"score" = tổng 4 tiêu chí, làm tròn 0.5.
Quy tắc chấm:
- Sai kiến thức thì trừ mạnh "Độ chính xác" và chỉ rõ chỗ sai trong "gaps".
- Ứng viên nói không biết / trả lời trống rỗng → score 0, nói thẳng, và vẫn đưa "model_answer".
- Diễn đạt khác đáp án tham chiếu nhưng đúng ý thì vẫn tính đúng; đừng bắt bẻ câu chữ.
- Đừng nới tay: mức ${entry.level} thì đòi hỏi đúng mức ${entry.level}.
- "note" mỗi tiêu chí: 1 câu ngắn giải thích vì sao trừ điểm.
- "level_estimate": câu trả lời này ở tầm nào — Fresher / Junior / Middle / Senior.
- "strengths": ý ứng viên nói đúng, trích lại chính chữ họ dùng.
- "gaps": ý thiếu hoặc sai, mỗi ý 1 dòng ngắn.
- "missing_keywords": thuật ngữ interviewer mong nghe mà ứng viên chưa nhắc tới.
- "model_answer": dàn ý đáp án chuẩn khoảng 120 từ, gạch đầu dòng markdown, nhấn vào đúng phần ứng viên còn thiếu.
- "followup": 1 câu interviewer sẽ vặn tiếp ngay sau câu trả lời này.
Tiếng Việt, thuật ngữ kỹ thuật giữ nguyên tiếng Anh. "verdict" tối đa 25 từ.`,
GRADE_SCHEMA, { temperature: 0.35, maxOutputTokens: 2048, signal });
return normalizeGrade(parseJsonLoose(raw));
}
const scoreTier = n => n >= 8 ? 'good' : n >= 5 ? 'mid' : 'bad';
const fmtScore = n => Number.isInteger(n) ? String(n) : n.toFixed(1);
function gradeHtml(entry, g, meta) {
const bars = g.breakdown.map(b => `
<div class="cb-bar" title="${esc(b.note)}">
<span class="cb-bar-name">${esc(b.name)}</span>
<span class="cb-bar-track"><i class="${scoreTier(b.score / b.max * 10)}" style="width:${Math.round(b.score / b.max * 100)}%"></i></span>
<span class="cb-bar-val">${fmtScore(b.score)}/${b.max}</span>
</div>`).join('');
const notes = g.breakdown.filter(b => b.note).map(b =>
`<li><b>${esc(b.name)}:</b> ${esc(b.note)}</li>`).join('');
const list = (title, cls, items) => items.length
? `<div class="cb-gsec ${cls}"><h5>${title}</h5><ul>${items.map(x => `<li>${esc(x)}</li>`).join('')}</ul></div>` : '';
return `<div class="cb-grade">
<div class="cb-grade-top">
<div class="cb-score ${scoreTier(g.score)}"><b>${fmtScore(g.score)}</b><span>/10</span></div>
<div class="cb-grade-meta">
<div class="cb-grade-q">#${entry.num} · ${esc(entry.question)}</div>
${g.verdict ? `<div class="cb-grade-verdict">${esc(g.verdict)}</div>` : ''}
<div class="cb-grade-tags">
${g.level_estimate ? `<span class="cb-gtag">Tầm ${esc(g.level_estimate)}</span>` : ''}
<span class="cb-gtag">Lần ${meta.rec.count}</span>
<span class="cb-gtag">Cao nhất ${fmtScore(meta.rec.best)}</span>
${meta.isBest ? '<span class="cb-gtag best">🎉 Kỷ lục mới</span>' : ''}
</div>
</div>
</div>
<div class="cb-bars">${bars}</div>
${notes ? `<details class="cb-gdet"><summary>Vì sao trừ điểm</summary><ul>${notes}</ul></details>` : ''}
${list('✅ Đã nói đúng', 'ok', g.strengths)}
${list('⚠️ Thiếu / chưa chuẩn', 'bad', g.gaps)}
${g.missing_keywords.length ? `<div class="cb-kws"><span>Từ khoá còn thiếu</span>${g.missing_keywords.map(k => `<code>${esc(k)}</code>`).join('')}</div>` : ''}
${g.model_answer ? `<details class="cb-gdet ans" open><summary>📘 Đáp án mẫu</summary>${md(g.model_answer)}</details>` : ''}
${g.followup ? `<div class="cb-gfu">👉 Interviewer sẽ hỏi tiếp: ${esc(g.followup)}</div>` : ''}
</div>`;
}
// Bản chữ để đưa vào history gửi lên API (và làm fallback nếu mất object grade)
function gradeText(entry, g) {
return [
`**Kết quả chấm câu #${entry.num}: ${fmtScore(g.score)}/10** — ${g.verdict}`,
g.breakdown.map(b => `- ${b.name}: ${fmtScore(b.score)}/${b.max}${b.note ? ' — ' + b.note : ''}`).join('\n'),
g.gaps.length ? '**Thiếu / chưa chuẩn:**\n' + g.gaps.map(x => '- ' + x).join('\n') : '',
g.model_answer ? '**Đáp án mẫu:**\n' + g.model_answer : '',
g.followup ? '👉 Follow-up: ' + g.followup : ''
].filter(Boolean).join('\n\n');
}
// ── DOM ─────────────────────────────────────────────────
const el = {};
function mount() {
const root = document.createElement('div');
root.innerHTML = `
<button class="cb-fab" id="cbFab" aria-label="AI Interview Coach" data-tooltip="AI Coach (Ctrl+/)">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
</button>
<aside class="cb-panel" id="cbPanel" role="complementary" aria-label="AI Interview Coach">
<div class="cb-head">
<span class="cb-dot"></span>
<span class="cb-title">AI Interview Coach</span>
<span class="cb-model" id="cbModel"></span>
<button class="cb-icon" id="cbClear" data-tooltip="Xoá hội thoại">↻</button>
<button class="cb-icon cb-only-float" id="cbClose" data-tooltip="Đóng (Esc)">×</button>
</div>
<div class="cb-body" id="cbBody"></div>
<div class="cb-pin" id="cbPin" hidden>
<span class="cb-pin-num" id="cbPinNum"></span>
<span class="cb-pin-text" id="cbPinText"></span>
<span class="cb-pin-best" id="cbPinBest" hidden></span>
<button class="cb-pin-mode" id="cbPinMode" data-tooltip="Tự trả lời câu này, AI chấm điểm">🎤 Trả lời & chấm điểm</button>
<button class="cb-pin-x" id="cbPinX" aria-label="Bỏ ghim">×</button>
</div>
<div class="cb-chips" id="cbChips" hidden></div>
<div class="cb-input">
<div class="cb-ta-wrap">
<div class="cb-ghost" id="cbGhost" aria-hidden="true"></div>
<textarea id="cbText" rows="1" spellcheck="false" aria-label="Nhập câu hỏi"></textarea>
</div>
<button class="cb-send" id="cbSend" aria-label="Gửi">
<svg class="cb-ico-send" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>
<svg class="cb-ico-stop" width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>
</button>
</div>
</aside>`;
document.body.appendChild(root);
for (const id of ['cbFab', 'cbPanel', 'cbBody', 'cbText', 'cbGhost', 'cbSend', 'cbClear', 'cbClose',
'cbModel', 'cbPin', 'cbPinNum', 'cbPinText', 'cbPinX', 'cbPinBest', 'cbPinMode', 'cbChips'])
el[id] = document.getElementById(id);
el.cbFab.onclick = () => toggle();
el.cbClose.onclick = () => toggle(false);
el.cbClear.onclick = () => { messages = []; saveHistory(); unpin(); render(); refreshSuggestions(); };
el.cbSend.onclick = () => busy ? abort() : send();
el.cbPinX.onclick = unpin;
el.cbPinMode.onclick = () => setInterviewMode(!interviewMode);
el.cbText.addEventListener('input', onInput);
el.cbText.addEventListener('keydown', onKeydown);
el.cbText.addEventListener('scroll', () => { el.cbGhost.scrollTop = el.cbText.scrollTop; });
el.cbBody.addEventListener('click', onRefClick);
el.cbChips.addEventListener('click', e => {
const b = e.target.closest('.cb-chip');
if (!b) return;
const text = b.textContent;
if (b.dataset.ask === '1' && interviewMode) setInterviewMode(false);
el.cbText.value = text;
onInput();
send();
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && getMode() === 'float' && el.cbPanel.classList.contains('open')) { toggle(false); e.stopPropagation(); }
else if (e.key === '/' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); focusChat(); }
}, true);
}
function onRefClick(e) {
const ref = e.target.closest('.cb-ref');
if (!ref) return;
e.preventDefault();
revealCard(ref.dataset.q);
}
function revealCard(num) {
const card = document.getElementById('q' + num);
if (!card) return;
if (!card.classList.contains('open')) card.querySelector('.qa-question').click();
card.scrollIntoView({ behavior: 'smooth', block: 'center' });
card.classList.add('cb-flash');
setTimeout(() => card.classList.remove('cb-flash'), 1400);
}
// ── Mode: split (mặc định) | float ──────────────────────
function applyMode(mode) {
document.documentElement.dataset.mode = mode; // khớp với style pre-paint trong <head>
document.body.classList.toggle('mode-split', mode === 'split');
document.body.classList.toggle('mode-float', mode !== 'split');
document.querySelectorAll('.mode-btn').forEach(b => {
b.classList.toggle('active', mode === 'split');
b.setAttribute('data-tooltip', mode === 'split' ? 'Chuyển sang chat nổi' : 'Chuyển sang chat cạnh trang');
});
if (mode === 'split' && el.cbPanel) { el.cbPanel.classList.remove('open'); el.cbFab.classList.remove('active'); }
}
window.cbToggleMode = () => {
const next = getMode() === 'split' ? 'float' : 'split';
localStorage.setItem(KEY_MODE, next);
applyMode(next);
if (next === 'split') { render(); onInput(); }
};
const isVisible = () => getMode() === 'split' || el.cbPanel.classList.contains('open');
function toggle(force) {
if (getMode() === 'split') return; // split thì panel luôn hiện
const open = force ?? !el.cbPanel.classList.contains('open');
el.cbPanel.classList.toggle('open', open);
el.cbFab.classList.toggle('active', open);
if (open) { render(); onInput(); el.cbText.focus(); }
}
function focusChat() {
if (getMode() === 'float') toggle(true);
el.cbText.focus();
}
// ── Ghim 1 câu hỏi ("Hỏi AI về câu hỏi này") ────────────
window.cbAsk = (num, event) => {
if (event) event.stopPropagation();
const entry = byNum(num);
if (!entry) return;
const changed = pinned !== entry;
pinned = entry;
if (changed) gradedOnce = false;
el.cbPin.hidden = false;
el.cbPinNum.textContent = '#' + entry.num;
el.cbPinText.textContent = entry.question;
paintPinBest();
setInterviewMode(false);
focusChat();
refreshChips(entry);
};
// Vào thẳng chế độ phỏng vấn từ nút 🎤 trên thẻ câu hỏi
window.cbInterview = (num, event) => {
window.cbAsk(num, event);
if (pinned && pinned.num === Number(num)) setInterviewMode(true);
};
function unpin() {
pinned = null;
chips = [];
gradedOnce = false;
el.cbPin.hidden = true;
setInterviewMode(false);
paintChips();
onInput();
}
/* Bật/tắt chế độ phỏng vấn. Khi bật, MỌI thứ gõ trong ô nhập được hiểu là câu
trả lời của ứng viên nên phải tắt ghost gợi ý và đổi hẳn bộ chip — chip dạng
"hỏi" mà bấm nhầm lúc này thì sẽ bị chấm điểm như một câu trả lời. */
function setInterviewMode(on) {
interviewMode = !!on && !!pinned;
el.cbPinMode.classList.toggle('on', interviewMode);
el.cbPinMode.innerHTML = interviewMode ? '🎤 Đang phỏng vấn' : '🎤 Trả lời & chấm điểm';
el.cbPinMode.setAttribute('data-tooltip',
interviewMode ? 'Quay lại hỏi đáp bình thường' : 'Tự trả lời câu này, AI chấm điểm');
el.cbPin.classList.toggle('interview', interviewMode);
el.cbPanel.classList.toggle('cb-interview', interviewMode);
el.cbText.placeholder = interviewMode && pinned
? `Trả lời câu #${pinned.num} như đang phỏng vấn…` : '';
if (interviewMode) {
chips = (gradedOnce ? INTERVIEW_CHIPS_AFTER : INTERVIEW_CHIPS).slice();
paintChips();
} else if (pinned) {
chips = FALLBACK_CHIPS.slice();
paintChips();
}
onInput();
}
function paintPinBest() {
const r = pinned ? loadScores()[pinned.num] : null;
el.cbPinBest.hidden = !r;
if (!r) return;
el.cbPinBest.textContent = '🏆 ' + fmtScore(r.best);
el.cbPinBest.title = `Cao nhất ${fmtScore(r.best)}/10 · gần nhất ${fmtScore(r.last)}/10 · đã trả lời ${r.count} lần`;
}
const chipText = c => typeof c === 'string' ? c : c.t;
const chipAsk = c => typeof c === 'object' && !!c.ask;
function paintChips() {
const show = pinned && chips.length;
el.cbChips.hidden = !show;
el.cbChips.innerHTML = show
? chips.map(c => `<button class="cb-chip${chipAsk(c) ? ' ask' : ''}"${chipAsk(c) ? ' data-ask="1"' : ''}>${esc(chipText(c))}</button>`).join('')
: '';
}
// ── Ghost suggestion trong input ────────────────────────
function pool() {
const ai = aiSuggestions.length ? aiSuggestions : FALLBACK_SUGG;
if (!pinned) return ai;
// Chưa hỏi gì: ghost mời các chip của câu đang ghim.
// Đã có câu trả lời: ghost ưu tiên follow-up (chip vốn đã hiện thành nút rồi).
const cs = chips.map(chipText);
return messages.length ? [...ai, ...cs] : [...cs, ...ai];
}
function onInput() {
const t = el.cbText;
t.style.height = 'auto';
t.style.height = Math.min(t.scrollHeight, 132) + 'px';
const raw = t.value;
const v = raw.trim();
// Đang phỏng vấn: người dùng viết đáp án của chính mình, gợi ý sẵn chỉ làm nhiễu
if (interviewMode) { suggestions = []; paintGhost(); return; }
if (!v) {
suggestions = pool();
} else {
// deaccent giữ nguyên độ dài → cắt đúng vị trí ký tự để ghép ghost
const key = deaccent(raw);
const cand = [...pool(), ...(buildIndex() ? INDEX.map(e => e.question) : [])];
suggestions = cand.filter(s => s.length > raw.length && deaccent(s).startsWith(key));
}
if (sugIdx >= suggestions.length) sugIdx = 0;
paintGhost();
}
function ghostRest() {
const s = suggestions[sugIdx];
if (!s) return null;
const raw = el.cbText.value;
return raw ? s.slice(raw.length) : s;
}
function paintGhost() {
const rest = ghostRest();
const raw = el.cbText.value;
el.cbGhost.innerHTML = rest
? `<span class="cb-ghost-typed">${esc(raw)}</span><span class="cb-ghost-rest">${esc(rest)}</span>` +
`<span class="cb-ghost-tab">Tab</span>`
: '';
el.cbGhost.scrollTop = el.cbText.scrollTop;
}
function accept() {
const s = suggestions[sugIdx];
if (!s || ghostRest() == null) return;
el.cbText.value = s; // lấy nguyên câu gợi ý (đúng dấu) thay vì nối đuôi phần đã gõ
suggestions = [];
onInput();
el.cbText.focus();
}
function onKeydown(e) {
if (e.key === 'Tab' && ghostRest() != null) { e.preventDefault(); accept(); return; }
if (suggestions.length > 1 && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
e.preventDefault();
sugIdx = (sugIdx + (e.key === 'ArrowDown' ? 1 : suggestions.length - 1)) % suggestions.length;
paintGhost();
return;
}
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
}
// ── Render ──────────────────────────────────────────────
function render() {
if (!messages.length) {
const total = INDEX.length || window.QA_DATA?.length || 0;
el.cbBody.innerHTML = hasKey()
? `<div class="cb-empty">
<div class="cb-empty-icon">🤖</div>
<p>Hỏi bất kỳ điều gì về <strong>${total} câu hỏi phỏng vấn</strong> trong trang.</p>
<p class="cb-hint">Gợi ý hiện mờ ngay trong ô nhập — <kbd class="cb-kbd">Tab</kbd> chèn · <kbd class="cb-kbd">↑↓</kbd> đổi gợi ý · <kbd class="cb-kbd">Enter</kbd> gửi</p>
<p class="cb-hint">Bấm <span class="cb-inline-btn">🤖</span> trên mỗi câu hỏi để hỏi riêng câu đó, hoặc <span class="cb-inline-btn">🎤</span> để tự trả lời và được chấm điểm.</p>
</div>`
: `<div class="cb-empty">
<div class="cb-empty-icon">🔑</div>
<p>Chưa có <strong>Gemini API key</strong>.</p>
<button class="cb-link" id="cbGoSettings">Mở Settings để nhập key →</button>
<p class="cb-hint">Lấy key miễn phí tại <a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">aistudio.google.com/apikey</a></p>