File size: 42,360 Bytes
9045c2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
const STORAGE_KEY = "hvu_qa_history_v1";
const QUESTION_COUNT_LIMITS = { min: 0, max: 100, default: 0 };
const SAMPLE_SNIPPETS = [
  {
    id: "luat-giao-duc-dai-hoc",
    title: "Luật Giáo dục đại học",
    preview: "Quy định về cơ sở giáo dục đại học, chương trình đào tạo và quyền tự chủ.",
    text: "Cơ sở giáo dục đại học có nhiệm vụ tổ chức hoạt động đào tạo, nghiên cứu khoa học, hợp tác quốc tế và phục vụ cộng đồng theo quy định của pháp luật. Cơ sở giáo dục đại học được thực hiện quyền tự chủ gắn với trách nhiệm giải trình, bảo đảm chất lượng đào tạo, công khai điều kiện bảo đảm chất lượng và kết quả hoạt động với cơ quan quản lý nhà nước, người học và xã hội.",
    suggestedCount: 5,
  },
  {
    id: "bo-luat-lao-dong",
    title: "Bộ luật Lao động",
    preview: "Nội dung về hợp đồng lao động, quyền và nghĩa vụ của người lao động.",
    text: "Hợp đồng lao động là sự thỏa thuận giữa người lao động và người sử dụng lao động về việc làm có trả công, tiền lương, điều kiện lao động, quyền và nghĩa vụ của mỗi bên. Khi giao kết hợp đồng lao động, các bên phải tuân thủ nguyên tắc tự nguyện, bình đẳng, thiện chí, hợp tác và trung thực; không được thỏa thuận nội dung làm giảm quyền lợi của người lao động so với quy định của pháp luật.",
    suggestedCount: 4,
  },
  {
    id: "luat-an-toan-thong-tin-mang",
    title: "Luật An toàn thông tin mạng",
    preview: "Yêu cầu bảo vệ thông tin, phòng ngừa rủi ro và trách nhiệm của tổ chức, cá nhân.",
    text: "Cơ quan, tổ chức, cá nhân tham gia hoạt động trên môi trường mạng có trách nhiệm bảo đảm an toàn thông tin mạng; áp dụng biện pháp quản lý, kỹ thuật phù hợp để phòng ngừa, phát hiện, ngăn chặn và xử lý nguy cơ mất an toàn thông tin. Việc thu thập, xử lý và sử dụng thông tin trên môi trường mạng phải đúng mục đích, đúng thẩm quyền và bảo đảm quyền, lợi ích hợp pháp của cơ quan, tổ chức, cá nhân có liên quan.",
    suggestedCount: 5,
  },
];
const AUTHOR_PROFILES = [
  {
    id: "do-cao-dang",
    name: "Đỗ Cao Đăng",
    role: "Sinh viên thực hiện",
    summary: "Tác giả thực hiện đề án.",
    description: "Tác giả triển khai và hoàn thiện hệ thống.",
    unit: "Khoa Kỹ thuật - Công nghệ",
    email: "docaodang532001@gmail.com",
  },
  {
    id: "nguyen-tien-ha",
    name: "TS. Nguyễn Tiến Hà",
    role: "Giảng viên hướng dẫn",
    summary: "Giảng viên hướng dẫn chuyên môn cho đề án.",
    description: "Giảng viên hướng dẫn học thuật và định hướng chuyên môn cho đề án.",
    unit: "Khoa Kỹ thuật - Công nghệ",
    email: "nguyentienha@hvu.edu.vn",
  },
];

const state = {
  history: loadHistory(),
  selectedId: null,
  thread: [],
  availableModels: [],
  activeModelId: "",
  isSwitchingModel: false,
  selectedAuthorId: null,
  isAuthorPanelOpen: false,
};

const voiceState = {
  isSupported: false,
  isListening: false,
  recognition: null,
  discardOnStop: false,
  stopRequested: false,
  baseText: "",
  finalTranscript: "",
  interimTranscript: "",
  lastErrorMessage: "",
};

const elements = {
  menuToggle: document.getElementById("menuToggle"),
  sidebarContent: document.getElementById("sidebarContent"),
  modelSelect: document.getElementById("modelSelect"),
  deviceStatus: document.getElementById("deviceStatus"),
  modelStatus: document.getElementById("modelStatus"),
  historyList: document.getElementById("historyList"),
  clearHistory: document.getElementById("clearHistory"),
  resultCard: document.getElementById("resultCard"),
  form: document.getElementById("generatorForm"),
  sourceShell: document.getElementById("sourceShell"),
  sourceText: document.getElementById("sourceText"),
  voiceInputButton: document.getElementById("voiceInputButton"),
  voiceStatus: document.getElementById("voiceStatus"),
  questionCount: document.getElementById("questionCount"),
  questionCountValue: document.getElementById("questionCountValue"),
  decreaseCount: document.getElementById("decreaseCount"),
  increaseCount: document.getElementById("increaseCount"),
  generateButton: document.getElementById("generateButton"),
  authorToggle: document.getElementById("authorToggle"),
  authorContent: document.getElementById("authorContent"),
  authorList: document.getElementById("authorList"),
  copyrightLine: document.getElementById("copyrightLine"),
  heroTitle: document.getElementById("heroTitle"),
  landingPanel: document.getElementById("landingPanel"),
  sampleList: document.getElementById("sampleList"),
  landingRuntimeBadge: document.getElementById("landingRuntimeBadge"),
  landingStatusText: document.getElementById("landingStatusText"),
  landingModelName: document.getElementById("landingModelName"),
  landingDeviceName: document.getElementById("landingDeviceName"),
  landingModelCount: document.getElementById("landingModelCount"),
};

bootstrap();

function bootstrap() {
  hydrateQuestionCount();
  syncSidebar(false);
  renderHistory();
  renderAuthors();
  renderLandingSamples();
  attachEvents();
  hideResultCard();
  activateHeroTitle();
  syncCopyright();
  autoResizeTextarea();
  initVoiceInput();
  syncLandingPanel();
  fetchInfo();
}

function hydrateQuestionCount() {
  syncQuestionCount(elements.questionCount.value);
}

function attachEvents() {
  elements.menuToggle.addEventListener("click", () => {
    syncSidebar(!document.body.classList.contains("sidebar-open"));
  });

  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape" && document.body.classList.contains("sidebar-open")) {
      syncSidebar(false);
    }
  });

  elements.clearHistory.addEventListener("click", () => {
    stopVoiceInput(true);
    state.history = [];
    state.selectedId = null;
    state.thread = [];
    persistHistory();
    renderHistory();
    hideResultCard();
  });

  elements.historyList.addEventListener("click", (event) => {
    const button = event.target.closest("[data-history-id]");
    if (!button) return;

    stopVoiceInput(true);

    const entry = state.history.find((item) => item.id === button.dataset.historyId);
    if (!entry) return;

    state.selectedId = entry.id;
    state.thread = [entry];
    elements.sourceText.value = entry.text || entry.title || "";
    autoResizeTextarea();
    renderHistory();
    renderThread();
  });

  elements.resultCard.addEventListener("click", async (event) => {
    const button = event.target.closest("[data-copy-entry-id][data-copy-target]");
    if (!button) return;

    const entryId = button.dataset.copyEntryId;
    const target = button.dataset.copyTarget;
    const textToCopy = buildCopyText(entryId, target);
    if (!textToCopy) return;

    const copied = await copyToClipboard(textToCopy);
    if (!copied) return;

    button.classList.add("is-copied");
    button.setAttribute("aria-label", "Đã sao chép");
    window.setTimeout(() => {
      button.classList.remove("is-copied");
      button.setAttribute("aria-label", "Sao chép");
    }, 1400);
  });

  elements.sourceText.addEventListener("input", () => {
    autoResizeTextarea();
  });

  elements.sampleList?.addEventListener("click", (event) => {
    const button = event.target.closest("[data-sample-id]");
    if (!button) return;

    const sample = SAMPLE_SNIPPETS.find((item) => item.id === button.dataset.sampleId);
    if (!sample) return;

    stopVoiceInput(true);
    elements.sourceText.value = sample.text;
    if (Number(elements.questionCount.value || QUESTION_COUNT_LIMITS.default) <= 0) {
      syncQuestionCount(sample.suggestedCount || 5);
    }
    autoResizeTextarea();
    elements.sourceText.focus();
  });

  elements.voiceInputButton.addEventListener("click", () => {
    toggleVoiceInput();
  });

  elements.modelSelect.addEventListener("change", () => {
    const nextModelId = String(elements.modelSelect.value || "").trim();
    if (!nextModelId || nextModelId === state.activeModelId || state.isSwitchingModel) {
      return;
    }
    switchModel(nextModelId);
  });

  elements.authorToggle?.addEventListener("click", () => {
    state.isAuthorPanelOpen = !state.isAuthorPanelOpen;
    renderAuthors();
  });

  elements.authorList?.addEventListener("click", (event) => {
    const button = event.target.closest("[data-author-id]");
    if (!button) return;
    selectAuthor(button.dataset.authorId);
  });

  elements.decreaseCount.addEventListener("click", () => {
    syncQuestionCount(Number(elements.questionCount.value || QUESTION_COUNT_LIMITS.default) - 1);
  });

  elements.increaseCount.addEventListener("click", () => {
    syncQuestionCount(Number(elements.questionCount.value || QUESTION_COUNT_LIMITS.default) + 1);
  });

  elements.form.addEventListener("submit", async (event) => {
    event.preventDefault();

    if (state.isSwitchingModel) {
      renderMessage("Vui lòng chờ chuyển model xong rồi thử lại.");
      return;
    }

    if (voiceState.isListening) {
      renderMessage("Vui lòng dừng micro trước khi sinh câu hỏi.");
      return;
    }

    const text = elements.sourceText.value.trim();
    const numQuestions = Number(elements.questionCount.value || String(QUESTION_COUNT_LIMITS.default));

    if (!text) {
      renderMessage("Vui lòng nhập đoạn văn bản trước khi sinh câu hỏi.");
      elements.sourceText.focus();
      return;
    }

    if (numQuestions <= 0) {
      renderMessage("Vui lòng tăng số câu hỏi lên ít nhất 1.");
      elements.increaseCount.focus();
      return;
    }

    const pendingEntry = {
      id: makeId(),
      title: shrink(text, 52),
      text,
      questions: [],
      elapsedMs: null,
      device: null,
      count: numQuestions,
      createdAt: new Date().toISOString(),
      status: "pending",
      errorMessage: "",
    };

    state.thread = [...state.thread, pendingEntry];
    renderThread();
    elements.sourceText.value = "";
    autoResizeTextarea();

    setLoading(true);

    try {
      const response = await fetch("/api/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          model_id: state.activeModelId || undefined,
          text,
          num_questions: numQuestions,
        }),
      });
      const payload = await response.json();

      if (!response.ok || !payload.ok) {
        throw new Error(payload.error || "Không thể sinh câu hỏi lúc này.");
      }

      const entry = {
        id: pendingEntry.id,
        title: shrink(text, 52),
        text: payload.text,
        questions: payload.questions,
        elapsedMs: payload.elapsed_ms,
        device: payload.meta.active_device || payload.meta.predicted_device,
        count: payload.questions?.length || numQuestions,
        createdAt: pendingEntry.createdAt,
        status: "done",
        errorMessage: "",
      };

      state.selectedId = entry.id;
      state.history = [entry, ...state.history.filter((item) => item.questions?.length)].slice(0, 10);
      state.thread = state.thread.map((item) => (item.id === pendingEntry.id ? entry : item));
      persistHistory();
      renderHistory();
      renderThread();
    } catch (error) {
      state.thread = state.thread.map((item) =>
        item.id === pendingEntry.id
          ? {
              ...item,
              status: "error",
              errorMessage: error.message || "Có lỗi xảy ra khi sinh câu hỏi.",
            }
          : item,
      );
      renderThread();
    } finally {
      setLoading(false);
    }
  });
}

function syncQuestionCount(value) {
  const parsedValue = Number(value);
  const normalizedValue = Number.isFinite(parsedValue) ? Math.trunc(parsedValue) : QUESTION_COUNT_LIMITS.default;
  const safeValue = Math.min(
    QUESTION_COUNT_LIMITS.max,
    Math.max(QUESTION_COUNT_LIMITS.min, normalizedValue),
  );
  const isLoading = isInterfaceBusy();

  elements.questionCount.value = String(safeValue);
  elements.questionCountValue.textContent = String(safeValue);
  elements.decreaseCount.disabled = isLoading || safeValue <= QUESTION_COUNT_LIMITS.min;
  elements.increaseCount.disabled = isLoading || safeValue >= QUESTION_COUNT_LIMITS.max;
}

function syncSidebar(isOpen) {
  document.body.classList.toggle("sidebar-open", isOpen);
  elements.menuToggle.setAttribute("aria-expanded", String(isOpen));
  elements.sidebarContent.setAttribute("aria-hidden", String(!isOpen));
}

function initVoiceInput() {
  const SpeechRecognitionApi = window.SpeechRecognition || window.webkitSpeechRecognition;

  if (!SpeechRecognitionApi) {
    voiceState.isSupported = false;
    syncVoiceUi(buildVoiceUnsupportedMessage(), "error");
    return;
  }

  if (!canUseBrowserVoiceInput()) {
    voiceState.isSupported = false;
    syncVoiceUi(buildVoiceOriginMessage(), "error");
    return;
  }

  voiceState.recognition = createSpeechRecognition(SpeechRecognitionApi);
  voiceState.isSupported = true;
  syncVoiceUi("");
}

function toggleVoiceInput() {
  if (!voiceState.isSupported) {
    syncVoiceUi(
      canUseBrowserVoiceInput() ? buildVoiceUnsupportedMessage() : buildVoiceOriginMessage(),
      "error",
    );
    return;
  }

  if (voiceState.isListening) {
    stopVoiceInput(false);
    return;
  }

  startVoiceInput();
}

function startVoiceInput() {
  if (!voiceState.recognition) {
    syncVoiceUi(buildVoiceUnsupportedMessage(), "error");
    return;
  }

  try {
    voiceState.baseText = elements.sourceText.value.trimEnd();
    voiceState.finalTranscript = "";
    voiceState.interimTranscript = "";
    voiceState.discardOnStop = false;
    voiceState.stopRequested = false;
    voiceState.lastErrorMessage = "";
    syncVoiceUi("Đang bật nhận giọng nói...");
    voiceState.recognition.start();
  } catch (error) {
    voiceState.discardOnStop = false;
    syncVoiceUi(humanizeVoiceStartError(error), "error");
  }
}

function stopVoiceInput(discardRecording = false) {
  if (!voiceState.isListening || !voiceState.recognition) {
    return;
  }

  voiceState.discardOnStop = Boolean(discardRecording);
  voiceState.stopRequested = true;

  if (discardRecording) {
    voiceState.finalTranscript = "";
    voiceState.interimTranscript = "";
    elements.sourceText.value = voiceState.baseText;
    autoResizeTextarea();
  }

  syncVoiceUi(discardRecording ? "Đang hủy nhận giọng nói..." : "Đang dừng micro...");
  voiceState.recognition.stop();
}

function createSpeechRecognition(SpeechRecognitionApi) {
  const recognition = new SpeechRecognitionApi();
  recognition.lang = "vi-VN";
  recognition.continuous = true;
  recognition.interimResults = true;
  recognition.maxAlternatives = 1;

  recognition.onstart = () => {
    voiceState.isListening = true;
    voiceState.stopRequested = false;
    voiceState.lastErrorMessage = "";
    syncVoiceUi("Đang nghe... hãy nói vào micro.");
  };

  recognition.onresult = (event) => {
    if (voiceState.discardOnStop) {
      return;
    }

    let nextFinalTranscript = "";
    let nextInterimTranscript = "";

    for (let index = event.resultIndex; index < event.results.length; index += 1) {
      const transcript = String(event.results[index][0]?.transcript || "").trim();
      if (!transcript) continue;

      if (event.results[index].isFinal) {
        nextFinalTranscript = appendSpeechChunk(nextFinalTranscript, transcript);
      } else {
        nextInterimTranscript = appendSpeechChunk(nextInterimTranscript, transcript);
      }
    }

    if (nextFinalTranscript) {
      voiceState.finalTranscript = appendSpeechChunk(voiceState.finalTranscript, nextFinalTranscript);
    }

    voiceState.interimTranscript = nextInterimTranscript;
    syncSpeechDraft();
    syncVoiceUi("Đang nghe... bấm lại nếu muốn dừng.");
  };

  recognition.onerror = (event) => {
    console.warn("SpeechRecognition error:", event.error);

    if (event.error === "aborted" && (voiceState.discardOnStop || voiceState.stopRequested)) {
      voiceState.lastErrorMessage = "";
      return;
    }

    voiceState.lastErrorMessage = humanizeVoiceRecognitionError(event.error);
  };

  recognition.onend = () => {
    const shouldDiscard = voiceState.discardOnStop;
    const recognizedText = appendSpeechChunk(voiceState.finalTranscript, voiceState.interimTranscript);
    const hasRecognizedText = Boolean(recognizedText.trim());

    voiceState.isListening = false;

    if (!shouldDiscard && hasRecognizedText) {
      elements.sourceText.value = appendSpeechChunk(voiceState.baseText, recognizedText);
      autoResizeTextarea();
    }

    let finalMessage = "";
    let finalTone = "default";

    if (voiceState.lastErrorMessage) {
      finalMessage = voiceState.lastErrorMessage;
      finalTone = "error";
    } else if (!shouldDiscard && hasRecognizedText) {
      finalMessage = "Đã chèn nội dung giọng nói vào ô nhập.";
    } else if (!shouldDiscard && !voiceState.stopRequested) {
      finalMessage = "Không nhận diện được nội dung giọng nói. Hãy thử lại.";
      finalTone = "error";
    }

    voiceState.discardOnStop = false;
    voiceState.stopRequested = false;
    voiceState.finalTranscript = "";
    voiceState.interimTranscript = "";
    voiceState.lastErrorMessage = "";
    voiceState.baseText = elements.sourceText.value.trimEnd();

    syncVoiceUi(finalMessage, finalTone);
  };

  return recognition;
}

function appendSpeechChunk(base, chunk) {
  const normalizedBase = String(base || "");
  const normalizedChunk = String(chunk || "").trim();

  if (!normalizedChunk) return normalizedBase;
  if (!normalizedBase.trim()) return normalizedChunk;

  return /[\s(]$/.test(normalizedBase) ? `${normalizedBase}${normalizedChunk}` : `${normalizedBase} ${normalizedChunk}`;
}

function humanizeVoiceStartError(error) {
  const errorName = error?.name || "";

  if (errorName === "InvalidStateError") {
    return "Micro đang hoạt động. Hãy dừng phiên hiện tại trước khi bật lại.";
  }

  if (errorName === "NotAllowedError" || errorName === "SecurityError") {
    if (!canUseBrowserVoiceInput()) {
      return buildVoiceOriginMessage();
    }
    return "Bạn chưa cấp quyền micro cho trình duyệt.";
  }

  if (errorName === "NotFoundError" || errorName === "DevicesNotFoundError") {
    return "Không tìm thấy thiết bị micro.";
  }

  return "Không thể bật nhận giọng nói lúc này. Hãy thử lại.";
}

function humanizeVoiceRecognitionError(errorCode) {
  if (errorCode === "not-allowed" || errorCode === "service-not-allowed") {
    if (!canUseBrowserVoiceInput()) {
      return buildVoiceOriginMessage();
    }
    return "Bạn chưa cấp quyền micro hoặc nhận giọng nói cho trình duyệt.";
  }

  if (errorCode === "audio-capture") {
    return "Không tìm thấy micro hoặc micro đang bị chiếm dụng.";
  }

  if (errorCode === "network") {
    if (!navigator.onLine) {
      return "Thiết bị đang offline. Hãy kết nối Internet rồi thử lại.";
    }

    if (!canUseBrowserVoiceInput()) {
      return buildVoiceOriginMessage();
    }

    return "Trình duyệt không kết nối được dịch vụ nhận giọng nói. Hãy dùng Chrome hoặc Edge, kiểm tra mạng, VPN hay firewall rồi thử lại.";
  }

  if (errorCode === "language-not-supported") {
    return "Trình duyệt không hỗ trợ nhận giọng nói tiếng Việt.";
  }

  if (errorCode === "no-speech") {
    return "Không nghe thấy giọng nói. Hãy thử nói gần micro hơn.";
  }

  return "Không thể nhận giọng nói lúc này. Hãy thử lại.";
}

function canUseBrowserVoiceInput() {
  return window.isSecureContext || isLocalhost(window.location.hostname);
}

function isLocalhost(hostname) {
  return (
    hostname === "localhost" ||
    hostname.endsWith(".localhost") ||
    hostname === "127.0.0.1" ||
    hostname === "::1" ||
    hostname === "[::1]"
  );
}

function buildVoiceUnsupportedMessage() {
  return "Trình duyệt này chưa hỗ trợ nhập giọng nói trực tiếp. Hãy dùng Chrome hoặc Edge bản mới.";
}

function buildVoiceOriginMessage() {
  return "Nhập bằng giọng nói qua trình duyệt chỉ hoạt động trên HTTPS hoặc localhost. Hãy mở ứng dụng bằng https:// hoặc http://localhost.";
}

function syncSpeechDraft() {
  const stableText = appendSpeechChunk(voiceState.baseText, voiceState.finalTranscript);
  elements.sourceText.value = appendSpeechChunk(stableText, voiceState.interimTranscript);
  autoResizeTextarea();
}

function syncVoiceUi(message, tone = "default") {
  const resolvedMessage = String(message || "").trim();

  elements.voiceStatus.textContent = resolvedMessage;
  elements.voiceStatus.classList.toggle("is-empty", !resolvedMessage);
  elements.voiceStatus.classList.toggle("is-error", tone === "error");
  elements.voiceStatus.classList.toggle("is-active", voiceState.isListening);
  elements.voiceInputButton.disabled = !voiceState.isSupported;
  elements.voiceInputButton.classList.toggle("is-listening", voiceState.isListening);
  elements.voiceInputButton.classList.toggle("is-unsupported", !voiceState.isSupported);
  elements.voiceInputButton.setAttribute(
    "aria-label",
    voiceState.isListening ? "Dừng nhận giọng nói" : "Nhập bằng giọng nói qua trình duyệt",
  );
}

function autoResizeTextarea() {
  const collapsedHeight = 30;
  const expandedMinHeight = 86;
  const hasContent = elements.sourceText.value.trim().length > 0;

  elements.sourceText.style.height = `${collapsedHeight}px`;
  const nextHeight = Math.min(elements.sourceText.scrollHeight, 240);
  elements.sourceText.style.height = `${Math.max(nextHeight, hasContent ? expandedMinHeight : collapsedHeight)}px`;
  elements.sourceShell.classList.toggle("is-expanded", hasContent || nextHeight > collapsedHeight + 4);
}

function loadHistory() {
  try {
    const saved = window.localStorage.getItem(STORAGE_KEY);
    if (!saved) {
      return [];
    }

    const parsed = JSON.parse(saved);
    if (!Array.isArray(parsed)) return [];

    return parsed
      .map((item) => ({
        ...item,
        id: item.id || makeId(),
        createdAt: item.createdAt || new Date().toISOString(),
      }))
      .filter((item) => Array.isArray(item.questions) && item.questions.length > 0);
  } catch {
    return [];
  }
}

function persistHistory() {
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state.history));
}

async function fetchInfo() {
  try {
    const response = await fetch("/api/info");
    const payload = await response.json();

    if (!response.ok || !payload.ok) {
      throw new Error(payload.error || "Không đọc được thông tin hệ thống.");
    }

    applySystemInfo(payload);
  } catch (error) {
    state.availableModels = [];
    state.activeModelId = "";
    renderModelOptions("Không tải được danh sách model.");
    elements.deviceStatus.textContent = "Không kết nối được backend.";
    elements.modelStatus.textContent = error.message || "Vui lòng kiểm tra lại backend hoặc server Flask.";
    syncLandingStatus({
      modelName: "Không tải được danh sách model",
      deviceName: "Chưa kết nối backend",
      modelCount: 0,
      badgeText: "Lỗi kết nối",
      badgeTone: "error",
      statusText: error.message || "Không thể đọc thông tin hệ thống từ backend.",
    });
  }
}

async function switchModel(modelId) {
  const previousModelId = state.activeModelId;

  state.isSwitchingModel = true;
  syncInteractiveControls();
  elements.modelStatus.textContent = "Đang chuyển model...";
  syncLandingStatus({
    modelName: state.availableModels.find((item) => item.id === modelId)?.label || "Đang chuyển model...",
    deviceName: elements.deviceStatus.textContent || "Đang kiểm tra...",
    modelCount: state.availableModels.length,
    badgeText: "Đang chuyển",
    badgeTone: "pending",
    statusText: "Hệ thống đang chuyển model theo lựa chọn của bạn.",
  });

  try {
    const response = await fetch("/api/model", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ model_id: modelId }),
    });
    const payload = await response.json();

    if (!response.ok || !payload.ok) {
      throw new Error(payload.error || "Không thể chuyển model lúc này.");
    }

    applySystemInfo(payload);
  } catch (error) {
    state.activeModelId = previousModelId;
    renderModelOptions();
    elements.modelStatus.textContent = error.message || "Không thể chuyển model lúc này.";
    syncLandingStatus({
      modelName:
        state.availableModels.find((item) => item.id === previousModelId)?.label
        || state.availableModels[0]?.label
        || "Không xác định",
      deviceName: elements.deviceStatus.textContent || "Đang kiểm tra...",
      modelCount: state.availableModels.length,
      badgeText: "Lỗi chuyển model",
      badgeTone: "error",
      statusText: error.message || "Không thể chuyển model lúc này.",
    });
  } finally {
    state.isSwitchingModel = false;
    syncInteractiveControls();
  }
}

function applySystemInfo(payload) {
  const availableModels = Array.isArray(payload.available_models) ? payload.available_models : [];
  const fallbackModelId = String(payload.selected_model_id || payload.model_name || "default-model");
  const fallbackModelLabel = String(payload.model_name || "Model hiện tại");

  state.availableModels = availableModels.length
    ? availableModels
    : [{ id: fallbackModelId, label: fallbackModelLabel }];
  state.activeModelId = String(payload.selected_model_id || state.availableModels[0]?.id || "");
  renderModelOptions();

  const activeModel =
    state.availableModels.find((item) => item.id === state.activeModelId)?.label || payload.model_name || "Model";

  elements.deviceStatus.textContent = humanizeDevice(payload.meta.active_device || payload.meta.predicted_device);
  elements.modelStatus.textContent = payload.meta.loaded
    ? `${activeModel} đã sẵn sàng cho tác vụ sinh câu hỏi.`
    : `Đã chọn ${activeModel}. Model sẽ được nạp tự động ở lần sinh câu hỏi đầu tiên.`;

  syncLandingStatus({
    modelName: activeModel,
    deviceName: humanizeDeviceCompact(payload.meta.active_device || payload.meta.predicted_device),
    modelCount: state.availableModels.length,
    badgeText: payload.meta.loaded ? "Sẵn sàng" : "Chờ nạp model",
    badgeTone: payload.meta.loaded ? "ready" : "pending",
    statusText: payload.meta.loaded
      ? `${activeModel} đã nạp xong và có thể sử dụng ngay.`
      : `${activeModel} sẽ được nạp tự động ở lần sinh câu hỏi đầu tiên.`,
  });
}

function renderModelOptions(emptyLabel = "Chưa có model khả dụng.") {
  elements.modelSelect.innerHTML = "";

  if (!state.availableModels.length) {
    const fallbackOption = document.createElement("option");
    fallbackOption.value = "";
    fallbackOption.textContent = emptyLabel;
    elements.modelSelect.appendChild(fallbackOption);
    elements.modelSelect.disabled = true;
    return;
  }

  for (const model of state.availableModels) {
    const option = document.createElement("option");
    option.value = model.id;
    option.textContent = model.label;
    elements.modelSelect.appendChild(option);
  }

  if (!state.availableModels.some((item) => item.id === state.activeModelId)) {
    state.activeModelId = state.availableModels[0].id;
  }

  elements.modelSelect.value = state.activeModelId;
  syncInteractiveControls();
}

function renderAuthors() {
  if (!elements.authorToggle || !elements.authorContent || !elements.authorList) return;

  elements.authorToggle.setAttribute("aria-expanded", String(state.isAuthorPanelOpen));
  elements.authorToggle.classList.toggle("is-open", state.isAuthorPanelOpen);
  elements.authorContent.hidden = !state.isAuthorPanelOpen;

  if (!state.isAuthorPanelOpen) {
    elements.authorList.innerHTML = "";
    return;
  }

  elements.authorList.innerHTML = AUTHOR_PROFILES.map((author) => {
    const isActive = author.id === state.selectedAuthorId;
    const detailMarkup = isActive ? buildAuthorDetailMarkup(author) : "";
    return `
      <article
        class="author-person ${isActive ? "is-active" : ""}"
        data-author-shell="${escapeHtml(author.id)}"
      >
        <button
          class="author-person-trigger"
          type="button"
          data-author-id="${escapeHtml(author.id)}"
          aria-expanded="${String(isActive)}"
        >
          <div class="author-person-top">
            <span class="author-person-role">${escapeHtml(author.role)}</span>
            <span class="author-person-chevron" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none">
                <path
                  d="m8 10 4 4 4-4"
                  stroke="currentColor"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="1.8"
                />
              </svg>
            </span>
          </div>
          <strong>${escapeHtml(author.name)}</strong>
          <span class="author-person-summary">${escapeHtml(author.summary)}</span>
        </button>
        ${detailMarkup}
      </article>
    `;
  }).join("");
}

function renderLandingSamples() {
  if (!elements.sampleList) return;

  elements.sampleList.innerHTML = SAMPLE_SNIPPETS.map((sample) => `
    <button class="sample-card" type="button" data-sample-id="${escapeHtml(sample.id)}">
      <strong>${escapeHtml(sample.title)}</strong>
      <span>${escapeHtml(sample.preview)}</span>
    </button>
  `).join("");
}

function syncLandingPanel() {
  if (!elements.landingPanel) return;
  elements.landingPanel.hidden = !elements.resultCard.hidden;
}

function syncLandingStatus({
  modelName = "Đang tải...",
  deviceName = "Đang kiểm tra...",
  modelCount = 0,
  badgeText = "Đang kiểm tra",
  badgeTone = "pending",
  statusText = "Đang đồng bộ trạng thái hệ thống.",
} = {}) {
  if (
    !elements.landingRuntimeBadge
    || !elements.landingStatusText
    || !elements.landingModelName
    || !elements.landingDeviceName
    || !elements.landingModelCount
  ) {
    return;
  }

  elements.landingRuntimeBadge.textContent = badgeText;
  elements.landingRuntimeBadge.classList.remove("is-ready", "is-pending", "is-error");
  elements.landingRuntimeBadge.classList.add(
    badgeTone === "ready" ? "is-ready" : badgeTone === "error" ? "is-error" : "is-pending",
  );
  elements.landingStatusText.textContent = statusText;
  elements.landingModelName.textContent = modelName;
  elements.landingDeviceName.textContent = deviceName;
  elements.landingModelCount.textContent = String(modelCount);
}

function selectAuthor(authorId) {
  if (!AUTHOR_PROFILES.some((author) => author.id === authorId)) {
    return;
  }

  state.selectedAuthorId = state.selectedAuthorId === authorId ? null : authorId;
  renderAuthors();
}

function buildAuthorDetailMarkup(author) {
  const metaItems = [
    { label: "Vai trò", value: author.description },
    { label: "Đơn vị", value: author.unit },
    ...(author.email ? [{ label: "Email", value: author.email }] : []),
  ];

  return `
    <div class="author-person-body">
      <div class="author-person-meta">
        ${metaItems
          .map(
            (item) => `
              <div class="author-person-meta-row" title="${escapeHtml(item.value)}">
                <span class="author-person-meta-label">${escapeHtml(item.label)}</span>
                <span class="author-person-meta-value">${escapeHtml(item.value)}</span>
              </div>
            `,
          )
          .join("")}
      </div>
    </div>
  `;
}

function humanizeDevice(device) {
  if (device === "cuda") return "Đang sử dụng GPU CUDA.";
  return "Đang sử dụng CPU.";
}

function humanizeDeviceCompact(device) {
  if (device === "cuda") return "GPU CUDA";
  return "CPU";
}

function renderHistory() {
  if (!state.history.length) {
    elements.historyList.innerHTML = '<div class="history-empty">Chưa có lịch sử. Hãy tạo bộ câu hỏi đầu tiên của bạn.</div>';
    return;
  }

  elements.historyList.innerHTML = state.history
    .map((item) => {
      const activeClass = item.id === state.selectedId ? "is-active" : "";
      return `
        <button class="history-item ${activeClass}" type="button" data-history-id="${item.id}">
          <span class="history-icon" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none">
              <path d="M12 20c4.4 0 8-2.9 8-6.5S16.4 7 12 7 4 9.9 4 13.5c0 1.6.7 3 1.9 4.1L5 21l3.2-1.6c1.1.4 2.4.6 3.8.6Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
            </svg>
          </span>
          <span class="history-main">
            <strong>${escapeHtml(item.title || "Đoạn văn mới")}</strong>
            <span>${escapeHtml(formatTimestamp(item.createdAt))}</span>
          </span>
        </button>
      `;
    })
    .join("");
}

function showResultCard() {
  elements.resultCard.hidden = false;
  elements.resultCard.classList.add("is-visible");
  syncLandingPanel();
}

function hideResultCard() {
  elements.resultCard.hidden = true;
  elements.resultCard.classList.remove("is-visible");
  elements.resultCard.classList.remove("has-entry");
  elements.resultCard.classList.remove("is-updating");
  elements.resultCard.innerHTML = "";
  syncLandingPanel();
}

function renderMessage(message) {
  showResultCard();
  elements.resultCard.classList.remove("is-updating");

  if (state.thread.length) {
    elements.resultCard.classList.add("has-entry");
    elements.resultCard.innerHTML = `
      <p class="result-message result-message-inline">${escapeHtml(message)}</p>
      ${renderThreadMarkup(state.thread)}
    `;
    return;
  }

  elements.resultCard.classList.remove("has-entry");
  elements.resultCard.innerHTML = `
    <p class="result-message">${escapeHtml(message)}</p>
  `;
}

function renderThread() {
  if (!state.thread.length) {
    hideResultCard();
    return;
  }

  showResultCard();
  elements.resultCard.classList.add("has-entry");
  elements.resultCard.classList.remove("is-updating");
  elements.resultCard.innerHTML = renderThreadMarkup(state.thread);
}

function renderThreadMarkup(entries) {
  return `
    <div class="result-feed">
      ${entries.map((entry) => renderThreadItem(entry)).join("")}
    </div>
  `;
}

function renderThreadItem(entry) {
  const questions = Array.isArray(entry.questions) ? entry.questions : [];
  const questionItems = questions.map((item) => `<li>${escapeHtml(item)}</li>`).join("");
  const statusLabel =
    entry.status === "pending" ? "ĐANG XỬ LÝ" : entry.status === "error" ? "LỖI" : entry.device ? entry.device.toUpperCase() : "AUTO";
  const questionBlock =
    entry.status === "pending"
      ? `
        <div class="result-pending">
          <div class="atom-loader atom-loader-inline" aria-hidden="true">
            <span class="atom-core"></span>
            <span class="atom-orbit atom-orbit-a"><span class="atom-electron"></span></span>
            <span class="atom-orbit atom-orbit-b"><span class="atom-electron"></span></span>
            <span class="atom-orbit atom-orbit-c"><span class="atom-electron"></span></span>
          </div>
          <p class="result-note">Đang sinh câu hỏi từ đoạn văn bản này...</p>
        </div>
      `
      : entry.status === "error"
        ? `<p class="result-message">${escapeHtml(entry.errorMessage || "Có lỗi xảy ra khi sinh câu hỏi.")}</p>`
        : questions.length
          ? `<ol class="result-questions">${questionItems}</ol>`
          : '<p class="result-note">Mục lịch sử này chưa lưu danh sách câu hỏi. Hãy bấm “Sinh câu hỏi” để tạo lại.</p>';

  return `
    <article class="result-thread-item" data-entry-id="${escapeHtml(entry.id)}">
      <div class="result-meta">
        <span>${escapeHtml(formatTimestamp(entry.createdAt))}</span>
        <span>${escapeHtml(statusLabel)}</span>
        <span>${escapeHtml(String(entry.count || questions.length || 0))} câu hỏi</span>
        ${entry.elapsedMs ? `<span>${escapeHtml(String(entry.elapsedMs))} ms</span>` : ""}
      </div>

      <section class="result-section">
        <div class="result-section-head">
          <h3 class="result-source-title">Văn bản đầu vào</h3>
          <button class="copy-button" type="button" data-copy-entry-id="${escapeHtml(entry.id)}" data-copy-target="source" aria-label="Sao chép">
            ${copyIconMarkup()}
          </button>
        </div>
        <p class="result-source">${escapeHtml(entry.text || entry.title || "")}</p>
      </section>

      <section class="result-section">
        <div class="result-section-head">
          <h3 class="result-questions-title">Câu hỏi sinh ra</h3>
          <button class="copy-button" type="button" data-copy-entry-id="${escapeHtml(entry.id)}" data-copy-target="response" aria-label="Sao chép">
            ${copyIconMarkup()}
          </button>
        </div>
        ${questionBlock}
      </section>
    </article>
  `;
}

function copyIconMarkup() {
  return `
    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path
        d="M9 9.75A2.25 2.25 0 0 1 11.25 7.5h6A2.25 2.25 0 0 1 19.5 9.75v6A2.25 2.25 0 0 1 17.25 18h-6A2.25 2.25 0 0 1 9 15.75v-6Z"
        stroke="currentColor"
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="1.7"
      />
      <path
        d="M15 7.5v-.75A2.25 2.25 0 0 0 12.75 4.5h-6A2.25 2.25 0 0 0 4.5 6.75v6A2.25 2.25 0 0 0 6.75 15H9"
        stroke="currentColor"
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="1.7"
      />
    </svg>
  `;
}

function buildCopyText(entryId, target) {
  const entry = state.thread.find((item) => item.id === entryId) || state.history.find((item) => item.id === entryId);
  if (!entry) return "";

  if (target === "source") {
    return String(entry.text || entry.title || "").trim();
  }

  if (entry.status === "pending") {
    return "Đang sinh câu hỏi từ đoạn văn bản này...";
  }

  if (entry.status === "error") {
    return String(entry.errorMessage || "Có lỗi xảy ra khi sinh câu hỏi.").trim();
  }

  const questions = Array.isArray(entry.questions) ? entry.questions : [];
  if (questions.length) {
    return questions.map((item, index) => `${index + 1}. ${item}`).join("\n");
  }

  return "Mục lịch sử này chưa lưu danh sách câu hỏi. Hãy bấm “Sinh câu hỏi” để tạo lại.";
}

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    try {
      const area = document.createElement("textarea");
      area.value = text;
      area.setAttribute("readonly", "");
      area.style.position = "fixed";
      area.style.opacity = "0";
      document.body.appendChild(area);
      area.select();
      const success = document.execCommand("copy");
      area.remove();
      return success;
    } catch {
      return false;
    }
  }
}

function setLoading(isLoading) {
  elements.generateButton.classList.toggle("is-loading", isLoading);
  document.body.classList.toggle("is-generating", isLoading);
  elements.resultCard.classList.toggle("is-updating", isLoading && elements.resultCard.classList.contains("has-entry"));
  syncQuestionCount(elements.questionCount.value);
  syncInteractiveControls();
}

function isInterfaceBusy() {
  return document.body.classList.contains("is-generating") || state.isSwitchingModel;
}

function syncInteractiveControls() {
  const isBusy = isInterfaceBusy();
  elements.generateButton.disabled = isBusy;
  elements.modelSelect.disabled = isBusy || state.availableModels.length <= 1;
}

function activateHeroTitle() {
  const node = elements.heroTitle;
  if (!node) return;

  const fullText = String(node.dataset.text || "").trim();
  if (!fullText) return;

  node.textContent = fullText;
  node.classList.remove("is-ready");

  if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
    node.classList.add("is-ready");
    return;
  }

  window.requestAnimationFrame(() => {
    node.classList.add("is-ready");
  });
}

function shrink(text, maxLength) {
  const normalized = String(text || "").trim();
  if (normalized.length <= maxLength) return normalized;
  return `${normalized.slice(0, maxLength - 3).trim()}...`;
}

function formatTimestamp(value) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Vừa xong";

  const now = new Date();
  const sameDay = date.toDateString() === now.toDateString();
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);

  const timeLabel = date.toLocaleTimeString("vi-VN", { hour: "2-digit", minute: "2-digit" });
  if (sameDay) return `Hôm nay ${timeLabel}`;
  if (date.toDateString() === yesterday.toDateString()) return `Hôm qua ${timeLabel}`;

  return date.toLocaleDateString("vi-VN", { day: "2-digit", month: "2-digit", year: "numeric" });
}

function syncCopyright() {
  const year = new Date().getFullYear();
  elements.copyrightLine.textContent = ${year} HVU - KTCN`;
}

function escapeHtml(value) {
  return String(value || "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

function makeId() {
  if (window.crypto && typeof window.crypto.randomUUID === "function") {
    return window.crypto.randomUUID();
  }
  return `item-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}