This repository was archived by the owner on Sep 17, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlashFix.html
More file actions
1284 lines (1225 loc) · 86.9 KB
/
Copy pathFlashFix.html
File metadata and controls
1284 lines (1225 loc) · 86.9 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
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>⚡ FlashFix AI</title>
<link href="https://fonts.googleapis.com/css2?family=Shippori+Mincho+B1:wght@400;600;800&family=Noto+Sans+Thai:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<style>
*{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent}
:root{
--cream:#FAF9F6;--b1:#E5DFD5;--b2:#C8C0B5;
--t1:#1C1A18;--t2:#6B6460;--t3:#A8A49F;
--red:#8B1A1A;--redl:#F7EEEE;--redm:#C44040;
--ok:#2A6049;--okl:#EBF5EF;--okb:#A8D5BC;
--warn:#C44B1A;--warnl:#FDF0E8;--warnb:#F0C4A8;
--gold:#7A6200;--goldl:#FFFBF0;--goldb:#E8D98A;
--blue:#1A4A8B;--bluel:#EEF3FA;--blueb:#B0C8E8;
--pur:#5A1A8B;--purl:#F3EEFD;--purb:#C8B0E8;
--teal:#0D6B6B;--teall:#E8F6F6;--tealb:#7ECECE;
--r:10px;--shadow:0 4px 24px rgba(0,0,0,.08);--shadow-sm:0 2px 12px rgba(0,0,0,.06);
--ease:cubic-bezier(.4,0,.2,1);--ease-spring:cubic-bezier(.34,1.56,.64,1);
}
html,body{height:100%;background:var(--cream);font-family:'Noto Sans Thai',sans-serif;font-size:14px;color:var(--t1);line-height:1.6}
.serif{font-family:'Shippori Mincho B1',serif}
/* ── Animations ── */
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
@keyframes fadeIn{from{opacity:0}to{opacity:1}}
@keyframes slideInR{from{opacity:0;transform:translateX(32px)}to{opacity:1;transform:translateX(0)}}
@keyframes slideInL{from{opacity:0;transform:translateX(-32px)}to{opacity:1;transform:translateX(0)}}
@keyframes slideOutL{from{opacity:1;transform:translateX(0)}to{opacity:0;transform:translateX(-32px)}}
@keyframes slideOutR{from{opacity:1;transform:translateX(0)}to{opacity:0;transform:translateX(28px)}}
@keyframes scaleIn{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}
@keyframes barFill{from{width:0}to{width:var(--w)}}
@keyframes bk{0%,80%,100%{opacity:.12}40%{opacity:1}}
@keyframes pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.05)}}
@keyframes shimmer{0%{background-position:-500px 0}100%{background-position:500px 0}}
@keyframes countUp{from{opacity:0;transform:translateY(16px) scale(.9)}to{opacity:1;transform:translateY(0) scale(1)}}
@keyframes spin{to{transform:rotate(360deg)}}
@keyframes cardFlipIn{from{opacity:0;transform:rotateX(8deg) scale(.96)}to{opacity:1;transform:rotateX(0) scale(1)}}
@keyframes glowPulse{0%,100%{box-shadow:0 0 0 0 rgba(139,26,26,.15)}50%{box-shadow:0 0 0 8px rgba(139,26,26,0)}}
@keyframes slideDrawer{from{transform:translateX(100%)}to{transform:translateX(0)}}
/* ── Base ── */
.sk{height:14px;margin-bottom:10px;border-radius:6px;background:linear-gradient(90deg,#f0ede8 0%,#e4dfd6 50%,#f0ede8 100%);background-size:800px 100%;animation:shimmer 1.4s ease infinite}
.sk-lg{height:22px}.sk-sm{height:10px;width:55%}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:11px 20px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;transition:all .18s var(--ease);border:1.5px solid transparent;font-family:'Noto Sans Thai',sans-serif;touch-action:manipulation;min-height:44px;letter-spacing:.1px}
.btn:active{transform:scale(.96)}
.btn-p{background:var(--red);color:#fff;border-color:var(--red)}.btn-p:hover{background:var(--redm);transform:translateY(-1px);box-shadow:0 4px 12px rgba(139,26,26,.3)}
.btn-p:disabled{opacity:.4;cursor:not-allowed;transform:none;box-shadow:none}
.btn-g{background:transparent;color:var(--t2);border-color:var(--b1)}.btn-g:hover{background:#F5F2EE;border-color:var(--b2)}
.btn-o{background:#fff;color:var(--t1);border-color:var(--b1);padding:8px 16px;font-size:12px}.btn-o:hover{border-color:var(--b2);background:#FAFAF8}
.btn-o:disabled{opacity:.35;cursor:not-allowed}
.btn-b{background:var(--bluel);color:var(--blue);border-color:var(--blueb)}.btn-b:hover{background:#d4e6f6;transform:translateY(-1px)}
.btn-teal{background:var(--teall);color:var(--teal);border-color:var(--tealb)}.btn-teal:hover{background:#d0ecec}
.btn-cal{display:inline-flex;align-items:center;gap:7px;padding:10px 16px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;transition:all .18s;border:1.5px solid;min-height:40px;font-family:'Noto Sans Thai',sans-serif}
.card{background:#fff;border:1px solid var(--b1);border-radius:var(--r);padding:20px}
.card-hover{transition:box-shadow .22s,transform .22s}.card-hover:hover{box-shadow:var(--shadow);transform:translateY(-2px)}
.badge{display:inline-block;padding:2px 10px;border-radius:5px;font-size:11px;font-weight:700;letter-spacing:.2px}
.divider{height:1px;background:var(--b1);margin:18px 0}
.step-dot{width:27px;height:27px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;transition:all .3s;flex-shrink:0}
.step-conn{height:1px;flex:1;max-width:28px;transition:background .3s}
.drop-zone{border:2px dashed var(--b2);border-radius:14px;padding:36px 24px;text-align:center;cursor:pointer;transition:all .22s;position:relative;overflow:hidden;background:#fff}
.drop-zone:hover,.drop-zone.hover{border-color:var(--red);background:var(--redl)}
.drop-zone.dragging{border-color:var(--red);background:var(--redl)}
.opt{display:flex;align-items:flex-start;gap:12px;padding:13px 16px;border:1.5px solid var(--b1);border-radius:var(--r);cursor:pointer;transition:all .18s;background:#fff;text-align:left;width:100%;font-family:'Noto Sans Thai',sans-serif;min-height:52px}
.opt:hover:not([disabled]){border-color:var(--b2);background:#FAFAF8;transform:translateY(-1px);box-shadow:var(--shadow-sm)}
.opt.selected{border-color:var(--red);background:var(--redl)}
.opt.correct{border-color:var(--ok)!important;background:var(--okl)!important}
.opt.wrong{border-color:var(--warn)!important;background:var(--warnl)!important}
.opt-lbl{width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;flex-shrink:0;transition:all .18s;margin-top:1px}
.tab{padding:10px 14px;border:none;background:transparent;font-size:12px;font-weight:600;color:var(--t3);cursor:pointer;border-bottom:2.5px solid transparent;transition:all .18s;font-family:'Noto Sans Thai',sans-serif;white-space:nowrap}
.tab.on{color:var(--red);border-bottom-color:var(--red)}
.tab:hover:not(.on){color:var(--t2)}
.prog-bar{height:5px;background:#EDE8E0;border-radius:3px;overflow:hidden}
.prog-fill{height:100%;border-radius:3px;animation:barFill .9s var(--ease) forwards;width:var(--w)}
.dot-load span{width:7px;height:7px;border-radius:50%;background:var(--red);display:inline-block;animation:bk 1.3s infinite}
.dot-load span:nth-child(2){animation-delay:.22s}.dot-load span:nth-child(3){animation-delay:.44s}
.spin{display:inline-block;width:18px;height:18px;border:2.5px solid var(--b1);border-top-color:var(--red);border-radius:50%;animation:spin .7s linear infinite}
::-webkit-scrollbar{width:4px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--b2);border-radius:4px}
.g2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.g4{display:grid;grid-template-columns:repeat(4,1fr);gap:9px}
textarea,input,select{font-family:'Noto Sans Thai',sans-serif;outline:none}
textarea:focus,input:focus,select:focus{border-color:var(--red)!important}
/* ── Flashcard 3D ── */
.fc-scene{perspective:1200px;cursor:pointer;user-select:none}
.fc-inner{transform-style:preserve-3d;transition:transform .6s cubic-bezier(.45,.05,.55,.95);position:relative;width:100%;height:100%}
.fc-inner.flipped{transform:rotateY(180deg)}
.fc-face{backface-visibility:hidden;position:absolute;inset:0;border-radius:14px;display:flex;flex-direction:column;overflow:hidden}
.fc-back{transform:rotateY(180deg)}
.fc-gradient-accent{background:linear-gradient(135deg,#8B1A1A 0%,#C44040 100%)}
.fc-gradient-blue{background:linear-gradient(135deg,#1A4A8B 0%,#3b72d6 100%)}
.fc-gradient-purple{background:linear-gradient(135deg,#5A1A8B 0%,#9b4bdb 100%)}
.fc-gradient-teal{background:linear-gradient(135deg,#0D6B6B 0%,#1ea0a0 100%)}
.fc-gradient-gold{background:linear-gradient(135deg,#7A6200 0%,#c49b00 100%)}
/* ── History Sidebar ── */
#layout{display:flex;gap:0;min-height:100vh;position:relative}
#main-col{flex:1;min-width:0;padding:24px 16px 52px}
#hist-col{width:280px;flex-shrink:0;background:#fff;border-left:1px solid var(--b1);padding:0;overflow-y:auto;position:sticky;top:0;height:100vh;transition:transform .3s var(--ease)}
#hist-toggle{display:none;position:fixed;bottom:20px;right:16px;z-index:200;width:48px;height:48px;border-radius:50%;background:var(--red);border:none;color:#fff;font-size:20px;cursor:pointer;box-shadow:0 4px 16px rgba(139,26,26,.35);transition:all .2s;animation:glowPulse 2.5s ease infinite}
.hist-item{padding:12px 16px;border-bottom:1px solid var(--b1);cursor:default;transition:background .15s;animation:fadeIn .25s ease}
.hist-item:hover{background:#FAFAF8}
.hist-empty{padding:32px 16px;text-align:center;color:var(--t3);font-size:12px}
/* ── API Settings Modal ── */
#api-modal{display:none;position:fixed;inset:0;z-index:9000;background:rgba(28,26,24,.7);backdrop-filter:blur(8px);align-items:center;justify-content:center;padding:20px}
#api-modal.open{display:flex}
@media(max-width:899px){
#hist-col{position:fixed;right:0;top:0;bottom:0;z-index:500;transform:translateX(100%);box-shadow:-4px 0 24px rgba(0,0,0,.12)}
#hist-col.open{transform:translateX(0);animation:slideDrawer .28s var(--ease)}
#hist-toggle{display:flex;align-items:center;justify-content:center}
#main-col{padding:18px 12px 80px}
.g4{grid-template-columns:repeat(2,1fr)}
.g2{grid-template-columns:1fr}
.inner{padding:20px 16px!important}
.btn{font-size:12px;min-height:42px}
}
@media(min-width:900px){
#main-col{padding:28px 20px 60px}
.inner{padding:28px 30px!important}
}
.pad-inner{max-width:660px;margin:0 auto}
.inner{background:#fff;border:1px solid var(--b1);border-radius:12px}
</style>
</head>
<body>
<!-- API Settings Modal -->
<div id="api-modal">
<div style="background:#fff;border-radius:16px;padding:28px 24px;max-width:420px;width:100%;animation:scaleIn .22s ease;box-shadow:0 28px 80px rgba(0,0,0,.2)">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px">
<div style="font-size:17px;font-weight:700">⚙️ ตั้งค่า API</div>
<button id="api-close" style="background:none;border:none;cursor:pointer;font-size:20px;color:var(--t3);line-height:1;padding:4px">×</button>
</div>
<div style="font-size:12px;color:var(--t2);margin-bottom:16px;line-height:1.9;background:var(--bluel);border-radius:8px;padding:10px 12px">
ใช้ Anthropic Claude (built-in ไม่ต้องใส่ key) หรือ OpenAI / Gemini (ใส่ key ด้านล่าง)
</div>
<div style="margin-bottom:14px">
<label style="font-size:11px;font-weight:700;color:var(--t2);display:block;margin-bottom:6px">AI Provider</label>
<select id="api-provider" style="width:100%;padding:10px 12px;border:1.5px solid var(--b1);border-radius:8px;font-size:13px;background:#fff;cursor:pointer">
<option value="anthropic">🤖 Anthropic Claude (ฟรี built-in)</option>
<option value="openai">🟢 OpenAI GPT-4o</option>
<option value="gemini">🔵 Google Gemini Flash</option>
</select>
</div>
<div id="key-row" style="margin-bottom:16px;display:none">
<label style="font-size:11px;font-weight:700;color:var(--t2);display:block;margin-bottom:6px">API Key</label>
<input id="api-key-input" type="password" placeholder="sk-... หรือ AIzaSy..."
style="width:100%;padding:10px 12px;border:1.5px solid var(--b1);border-radius:8px;font-size:13px">
<div style="font-size:10px;color:var(--t3);margin-top:5px">Key จะเก็บไว้ใน localStorage ของเบราว์เซอร์เท่านั้น</div>
</div>
<button id="api-save" class="btn btn-p" style="width:100%">บันทึก</button>
</div>
</div>
<!-- Layout -->
<div id="layout">
<!-- ── MAIN COLUMN ── -->
<div id="main-col">
<div class="pad-inner">
<!-- Header -->
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
<div style="display:flex;align-items:center;gap:10px">
<button id="btn-home-logo" style="background:none;border:none;cursor:pointer;padding:0">
<span class="serif" style="font-size:20px;font-weight:800;letter-spacing:-.3px">⚡ FlashFix <span style="color:var(--red)">AI</span></span>
</button>
<span id="mode-badge" style="display:none"></span>
</div>
<div id="hdr-right" style="display:flex;align-items:center;gap:8px">
<button id="btn-api-open" title="ตั้งค่า API"
style="background:none;border:1.5px solid var(--b1);border-radius:8px;padding:7px 11px;cursor:pointer;font-size:12px;color:var(--t3);transition:all .18s"
onmouseover="this.style.borderColor='var(--b2)';this.style.color='var(--t1)'"
onmouseout="this.style.borderColor='var(--b1)';this.style.color='var(--t3)'">⚙️</button>
</div>
</div>
<div id="step-bar" style="display:flex;align-items:center;justify-content:center;margin-bottom:22px"></div>
<div id="pg" class="inner" style="padding:28px 30px"></div>
</div>
</div>
<!-- ── HISTORY SIDEBAR ── -->
<div id="hist-col">
<div style="padding:18px 16px 12px;border-bottom:1px solid var(--b1);position:sticky;top:0;background:#fff;z-index:10">
<div style="display:flex;justify-content:space-between;align-items:center">
<div style="font-size:13px;font-weight:700">📋 ประวัติการเรียน</div>
<button id="hist-clear" style="background:none;border:none;cursor:pointer;font-size:11px;color:var(--t3);padding:4px 8px;border-radius:4px;transition:all .15s" onmouseover="this.style.color='var(--warn)'" onmouseout="this.style.color='var(--t3)'">ลบทั้งหมด</button>
</div>
<div id="hist-count" style="font-size:11px;color:var(--t3);margin-top:3px"></div>
</div>
<div id="hist-list"></div>
</div>
</div><!-- /layout -->
<!-- History toggle button (mobile) -->
<button id="hist-toggle" onclick="toggleHistDrawer()">📋</button>
<script>
/* ════════════════════════════════
CONSTANTS & STATE
════════════════════════════════ */
const TOPICS=[
{id:'derivative',th:'อนุพันธ์',jp:'微分',lv:'ม.4-5',sym:'∂',color:'accent'},
{id:'integral',th:'อินทิกรัล',jp:'積分',lv:'ม.5',sym:'∫',color:'blue'},
{id:'limit',th:'ลิมิต',jp:'極限',lv:'ม.4',sym:'lim',color:'purple'},
{id:'trigonometry',th:'ตรีโกณมิติ',jp:'三角',lv:'ม.4',sym:'sin',color:'teal'},
{id:'algebra',th:'พีชคณิต',jp:'代数',lv:'ม.1-3',sym:'x²',color:'gold'},
{id:'probability',th:'ความน่าจะเป็น',jp:'確率',lv:'ม.5-6',sym:'P',color:'accent'},
{id:'geometry',th:'เรขาคณิต',jp:'幾何',lv:'ม.1-3',sym:'△',color:'blue'},
{id:'statistics',th:'สถิติ',jp:'統計',lv:'ม.5-6',sym:'x̄',color:'purple'},
];
const API_URL='https://api.anthropic.com/v1/messages';
let CFG={provider:'anthropic',key:''};
try{const c=JSON.parse(localStorage.getItem('ff_cfg')||'{}');if(c.provider)CFG=c;}catch{}
let S={
page:'home',mode:'',
fileName:'',fileText:'',fileB64:null,fileMime:null,
fileSummary:null,examQ:[],examA:{},examResult:null,
wrongIdx:0,wrongExplains:{},
topic:null,quiz:null,answer:'',solution:null,showAnswer:false,
teachBack:'',tbResult:null,activeTab:'solution',
flashcards:[],cardIdx:0,flipped:false,cardsDone:{},
remMiniQuiz:[],quizReveal:{},examIdx:0,loading:false,
mastery:{derivative:22,integral:15,limit:48,trigonometry:62,algebra:78,probability:35,geometry:55,statistics:42}
};
let busy=false;
/* ════════════════════════════════
HISTORY SYSTEM
════════════════════════════════ */
let HIST=[];
try{HIST=JSON.parse(localStorage.getItem('ff_history')||'[]');}catch{}
function saveHistory(){try{localStorage.setItem('ff_history',JSON.stringify(HIST.slice(0,80)));}catch{}}
function addHistory(type,data){
HIST.unshift({type,data,ts:Date.now()});
saveHistory();renderHistory();
}
function fmtDate(ts){
const d=new Date(ts);
return `${d.getDate()}/${d.getMonth()+1}/${d.getFullYear().toString().slice(2)} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
}
function renderHistory(){
const list=document.getElementById('hist-list');
const cnt=document.getElementById('hist-count');
if(!list)return;
if(cnt)cnt.textContent=`${HIST.length} รายการ`;
if(!HIST.length){list.innerHTML='<div class="hist-empty">🌱 ยังไม่มีประวัติ<br>เริ่มเรียนเพื่อบันทึก</div>';return;}
list.innerHTML=HIST.map((h,i)=>{
const icons={file:'📄',quiz:'🧮',exam:'📝',flashcard:'🎴',teachback:'🎓'};
const ic=icons[h.type]||'📌';
let title='',sub='',score='';
if(h.type==='file'){title=h.data.title||'ไฟล์';sub=h.data.fileName||'';}
else if(h.type==='quiz'){title=h.data.topic;sub=h.data.question?.substring(0,40)+'...';}
else if(h.type==='exam'){title='ข้อสอบ '+h.data.title;sub=`${h.data.score}/${h.data.total} ข้อ`;score=`${Math.round(h.data.score/h.data.total*100)}%`;}
else if(h.type==='flashcard'){title='Flashcard';sub=h.data.topic||h.data.title||'';}
else if(h.type==='teachback'){title='Teach-Back '+h.data.topic;sub=`คะแนน ${h.data.score}/10`;}
return`<div class="hist-item" style="animation:fadeUp .2s ${i*.03}s both ease">
<div style="display:flex;gap:10px;align-items:flex-start">
<div style="font-size:18px;margin-top:1px">${ic}</div>
<div style="flex:1;min-width:0">
<div style="font-size:12px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${title}</div>
<div style="font-size:11px;color:var(--t3);margin-top:1px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${sub}</div>
<div style="font-size:10px;color:var(--t3);margin-top:3px">${fmtDate(h.ts)}</div>
</div>
${score?`<div style="font-size:13px;font-weight:700;color:${parseInt(score)>=60?'var(--ok)':'var(--warn)'};flex-shrink:0">${score}</div>`:''}
</div>
</div>`;
}).join('');
}
function toggleHistDrawer(){
document.getElementById('hist-col')?.classList.toggle('open');
}
document.addEventListener('click',e=>{
const hc=document.getElementById('hist-col');
const ht=document.getElementById('hist-toggle');
if(hc&&ht&&!hc.contains(e.target)&&!ht.contains(e.target)&&window.innerWidth<900){
hc.classList.remove('open');
}
});
/* ════════════════════════════════
API LAYER
════════════════════════════════ */
async function callAI(sys,userContent,maxT=1200){
let msgs=[];
let content;
if(typeof userContent==='string') content=userContent;
else content=userContent; // array of parts
// Anthropic (default, no key needed here - proxied)
if(CFG.provider==='anthropic'||!CFG.provider){
if(typeof content==='string') msgs=[{role:'user',content}];
else msgs=[{role:'user',content}];
const body={model:'claude-sonnet-4-20250514',max_tokens:maxT,messages:msgs};
if(sys)body.system=sys;
const res=await fetch(API_URL,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
const d=await res.json();
if(!res.ok||d.error)throw new Error(d.error?.message||`HTTP ${res.status}`);
const raw=d.content?.[0]?.text||'';
if(!raw)throw new Error('Empty');
return JSON.parse(raw.replace(/```json\n?|```\n?/g,'').trim());
}
// OpenAI
if(CFG.provider==='openai'){
const parts=typeof content==='string'?[{type:'text',text:content}]:
content.map(p=>p.type==='text'?{type:'text',text:p.text}:
{type:'image_url',image_url:{url:`data:${p.source?.media_type};base64,${p.source?.data}`}});
const res=await fetch('https://api.openai.com/v1/chat/completions',{
method:'POST',headers:{'Content-Type':'application/json','Authorization':`Bearer ${CFG.key}`},
body:JSON.stringify({model:'gpt-4o',max_tokens:maxT,temperature:0.2,
response_format:{type:'json_object'},
messages:[...(sys?[{role:'system',content:sys}]:[]),{role:'user',content:parts}]})
});
const d=await res.json();
if(!res.ok)throw new Error(d.error?.message||'OpenAI error');
return JSON.parse(d.choices[0].message.content);
}
// Gemini
if(CFG.provider==='gemini'){
const parts2=typeof content==='string'?[{text:content}]:
content.map(p=>p.type==='text'?{text:p.text}:{inlineData:{mimeType:p.source?.media_type,data:p.source?.data}});
const body2={contents:[{parts:parts2}],generationConfig:{maxOutputTokens:maxT,temperature:0.2,responseMimeType:'application/json'}};
if(sys)body2.system_instruction={parts:[{text:sys}]};
const res=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${CFG.key}`,
{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body2)});
const d=await res.json();
if(!res.ok||d.error)throw new Error(d.error?.message||'Gemini error');
const raw=d.candidates?.[0]?.content?.parts?.[0]?.text||'';
return JSON.parse(raw.replace(/```json\n?|```\n?/g,'').trim());
}
throw new Error('Unknown provider');
}
/* ════════════════════════════════
AI CALLS (compact prompts = fast)
════════════════════════════════ */
async function callAnalyze(){
const sys=`FlashFix AI: วิเคราะห์เนื้อหาและสร้างข้อสอบ 5 ข้อ ตอบ JSON ไม่มี markdown:
{"title":"ชื่อ","subject":"วิชา","topics":["t1","t2","t3"],"summary":"สรุป 3 ประโยค",
"questions":[{"q":"คำถาม","options":["A...","B...","C...","D..."],"correct":0,"explain":"เหตุผล"}]}
ตรวจสอบ correct index ให้ถูกต้องก่อนส่ง`;
let uc;
if(S.fileB64){
if(S.fileMime==='application/pdf'){
uc=[{type:'document',source:{type:'base64',media_type:'application/pdf',data:S.fileB64}},{type:'text',text:'สร้างข้อสอบ 5 ข้อจากเอกสารนี้'}];
}else{
uc=[{type:'image',source:{type:'base64',media_type:S.fileMime,data:S.fileB64}},{type:'text',text:'สร้างข้อสอบ 5 ข้อจากรูปนี้'}];
}
}else{
uc=`เนื้อหา:\n${S.fileText}\n\nสร้างข้อสอบ 5 ข้อ`;
}
return callAI(sys,uc,1400);
}
async function callQuiz(t){
return callAI(
`สร้างโจทย์คณิตศาสตร์ 1 ข้อ ตอบ JSON: {"question":"โจทย์","answer":"เฉลย+วิธี","wrongExample":"ตัวอย่างผิด","difficulty":"easy|medium|hard","hint":"คำใบ้สั้น"}`,
`หัวข้อ: ${t.th} ระดับ ${t.lv}`
);
}
async function callSolution(){
return callAI(
`ตรวจคำตอบอย่างซื่อสัตย์ ตอบ JSON: {"isCorrect":false,"errorType":"","errorTypeThai":"","studentAnswer":"","studentMistake":"2 ประโยค","steps":[{"num":1,"title":"","math":"","explain":""}],"keyRule":"","commonTrap":"","severity":"minor|major|fundamental"}
ถ้าคำตอบถูกหรือสมมูล → isCorrect:true ถ้าผิด → isCorrect:false ห้ามผ่านถ้าผิดจริง`,
`หัวข้อ:${S.topic.th}\nโจทย์:${S.quiz.question}\nเฉลยถูก:${S.quiz.answer}\nคำตอบนักเรียน:${S.answer}`
);
}
async function callTB(){
return callAI(
`ตรวจ Teach-Back ตอบ JSON: {"passed":false,"score":1,"feedback":"2-3 ประโยค","conceptGap":null,"encouragement":"ประโยคสั้น"}
passed:true ต้องอธิบายถูกต้องและครบ (score 7-10) เท่านั้น`,
`หัวข้อ:${S.topic?.th} Error:${S.solution?.errorTypeThai} กฎ:${S.solution?.keyRule}\nคำอธิบาย:${S.teachBack}`
);
}
async function callFlashcards(context){
return callAI(
`สร้าง Flashcard ที่มีเนื้อหาอุดมสมบูรณ์ ตอบ JSON:
{"flashcards":[{"front":"คำถาม","back":"คำตอบเต็ม","rule":"กฎ","hint":"คำใบ้","example":"ตัวอย่างประยุกต์","difficulty":"easy|medium|hard","color":"accent|blue|purple|teal|gold"}],
"miniQuiz":[{"question":"โจทย์","answer":"เฉลย"}]}
6 flashcard เนื้อหาแน่น, 3 miniQuiz ทุกอย่างต้องถูกต้อง`,
context,1400
);
}
async function callWrongExplain(q){
return callAI(
`อธิบายเหตุผล ตอบ JSON: {"steps":[{"num":1,"title":"","math":"","explain":""}],"keyPoint":""}
2-3 steps`,
`คำถาม:${q.q}\nตัวเลือกถูก:${q.options[q.correct]}\nเหตุผล:${q.explain}`
);
}
/* ════════════════════════════════
FILE HANDLING
════════════════════════════════ */
function fileToB64(file){
return new Promise((res,rej)=>{const r=new FileReader();r.onload=()=>res(r.result.split(',')[1]);r.onerror=rej;r.readAsDataURL(file);});
}
async function parsePPTX(file){
const ab=await file.arrayBuffer();
const zip=await JSZip.loadAsync(ab);
const names=Object.keys(zip.files).filter(n=>/^ppt\/slides\/slide\d+\.xml$/.test(n))
.sort((a,b)=>+a.match(/\d+/)[0]-+b.match(/\d+/)[0]);
let out='';
for(const name of names.slice(0,18)){
const xml=await zip.files[name].async('text');
const txts=(xml.match(/<a:t[^>]*>([^<]*)<\/a:t>/g)||[]).map(x=>x.replace(/<[^>]+>/g,'').trim()).filter(Boolean);
if(txts.length)out+=`[Slide ${name.match(/\d+/)[0]}]: ${txts.join(' ')}\n`;
}
return out.substring(0,5000)||'(ไม่พบข้อความ)';
}
async function handleFile(file){
const ext=file.name.toLowerCase();
const isPPTX=ext.endsWith('.pptx')||ext.endsWith('.ppt');
const isPDF=file.type==='application/pdf';
const isImg=file.type.startsWith('image/');
if(!isPPTX&&!isPDF&&!isImg){alert('รองรับเฉพาะ PDF, PPTX, PNG, JPG');return;}
if(file.size>15*1024*1024){alert('ไฟล์ใหญ่เกิน 15MB');return;}
S.fileName=file.name;S.mode='file';nav('file_processing');
try{
if(isPPTX){S.fileText=await parsePPTX(file);S.fileB64=null;}
else{S.fileB64=await fileToB64(file);S.fileMime=file.type;S.fileText='';}
const result=await callAnalyze();
S.fileSummary=result;S.examQ=result.questions||[];
addHistory('file',{title:result.title||file.name,fileName:file.name,subject:result.subject});
nav('file_summary');
}catch(e){console.error(e);S.loading=false;nav('file_upload');}
}
/* ════════════════════════════════
CALENDAR INTEGRATION
════════════════════════════════ */
function makeICS(events){
const esc=s=>(s||'').replace(/[,;\\]/g,'\\$&').replace(/\n/g,'\\n');
const fmtDT=d=>{
const p=n=>String(n).padStart(2,'0');
return`${d.getFullYear()}${p(d.getMonth()+1)}${p(d.getDate())}T${p(d.getHours())}${p(d.getMinutes())}00`;
};
const uid=()=>Math.random().toString(36).substring(2,10).toUpperCase();
let ics='BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//FlashFix AI//TH\r\nCALSCALE:GREGORIAN\r\nMETHOD:PUBLISH\r\n';
events.forEach(ev=>{
const s=new Date(ev.start);const e=new Date(ev.start+ev.dur*60000);
ics+=`BEGIN:VEVENT\r\nUID:${uid()}@flashfix\r\nDTSTAMP:${fmtDT(new Date())}\r\nDTSTART:${fmtDT(s)}\r\nDTEND:${fmtDT(e)}\r\nSUMMARY:${esc(ev.title)}\r\nDESCRIPTION:${esc(ev.desc)}\r\nBEGIN:VALARM\r\nTRIGGER:-PT15M\r\nACTION:DISPLAY\r\nDESCRIPTION:ถึงเวลาทบทวน!\r\nEND:VALARM\r\nEND:VEVENT\r\n`;
});
ics+='END:VCALENDAR';
return ics;
}
function downloadICS(events,fname){
const blob=new Blob([makeICS(events)],{type:'text/calendar;charset=utf-8'});
const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=fname||'flashfix-review.ics';a.click();
}
function googleCalURL(ev){
const fmtG=d=>{const p=n=>String(n).padStart(2,'0');const dd=new Date(d);return`${dd.getFullYear()}${p(dd.getMonth()+1)}${p(dd.getDate())}T${p(dd.getHours())}${p(dd.getMinutes())}00`;}
const s=fmtG(ev.start);const e=fmtG(ev.start+ev.dur*60000);
return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${encodeURIComponent(ev.title)}&dates=${s}/${e}&details=${encodeURIComponent(ev.desc)}&sf=true`;
}
function buildReviewEvents(topic){
const now=new Date();const base=new Date(now.getFullYear(),now.getMonth(),now.getDate(),20,0,0).getTime();
const offsets=[0,1,4,11,25];
return offsets.map((d,i)=>({
title:`⚡ FlashFix ทบทวน: ${topic} (ครั้งที่${i+1})`,
desc:`Spaced Repetition ครั้งที่ ${i+1} สำหรับ ${topic}\nFlashFix AI Learning System`,
start:base+d*86400000,dur:20
}));
}
/* ════════════════════════════════
UI HELPERS
════════════════════════════════ */
const b=(t,c='var(--red)',bg='var(--redl)')=>`<span class="badge" style="color:${c};background:${bg}">${t}</span>`;
const loading=(msg='กำลังประมวลผล')=>`
<div style="padding:48px 0;text-align:center">
<div class="dot-load" style="display:flex;align-items:center;justify-content:center;gap:6px;margin-bottom:12px"><span></span><span></span><span></span></div>
<div style="font-size:12px;color:var(--t3)">${msg}</div>
</div>`;
function renderStepBar(){
const fS=['อัปโหลด','สรุป','ข้อสอบ','ผล','Flashcard','Mastery'];
const tS=['เลือก','โจทย์','เฉลย','Teach-Back','Flashcard','Mastery'];
const fP=['file_upload','file_summary','exam_mc','exam_result','flashcards','mastery'];
const tP=['topic_select','quiz','solution','teach_back','flashcards','mastery'];
const steps=S.mode==='file'?fS:tS;
const pages=S.mode==='file'?fP:tP;
const cur=pages.indexOf(S.page);
const bar=document.getElementById('step-bar');
if(cur<0){bar.innerHTML='';return;}
const isMob=window.innerWidth<600;
bar.innerHTML=steps.map((lbl,i)=>{
const done=i<cur,active=i===cur;
const ns=done?'background:var(--red);border-color:var(--red);color:#fff':
active?'background:#fff;border:2px solid var(--red);color:var(--red)':
'background:transparent;border:1.5px solid var(--b1);color:var(--t3)';
const conn=i<steps.length-1?`<div class="step-conn" style="background:${i<cur?'var(--red)':'var(--b1)'}"></div>`:'';
return`<div style="display:flex;flex-direction:column;align-items:center;gap:2px">
<div class="step-dot" style="${ns};transition:all .3s">${done?'✓':i+1}</div>
${active&&!isMob?`<span style="font-size:9px;color:var(--red);font-weight:700;white-space:nowrap">${lbl}</span>`:`<span style="font-size:8px;color:transparent">·</span>`}
</div>${conn}`;
}).join('');
}
function renderHdrRight(){
const el=document.getElementById('hdr-right');
const mb=document.getElementById('mode-badge');
const apiBtn=document.getElementById('btn-api-open');
if(S.page==='home'||!S.mode){if(mb)mb.style.display='none';el.innerHTML='';if(apiBtn)el.appendChild(apiBtn);return;}
if(mb){mb.style.display='inline-block';mb.innerHTML=b(S.mode==='file'?'📄 ไฟล์':'📚 หัวข้อ','var(--t2)','#F0EDE6');}
const tn=S.topic?S.topic.th:(S.fileSummary?.title||S.fileName||'').substring(0,12);
el.innerHTML=`<span style="font-size:12px;color:var(--t3)">${tn}</span>`;
if(apiBtn)el.appendChild(apiBtn);
}
/* ════════════════════════════════
NAVIGATION
════════════════════════════════ */
function nav(page,dir=1){
if(busy)return;
const el=document.getElementById('pg');if(!el)return;
busy=true;
el.style.animation=`${dir>0?'slideOutL':'slideOutR'} 0.17s ease forwards`;
setTimeout(()=>{
S.page=page;render();
el.style.animation=`${dir>0?'slideInR':'slideInL'} 0.22s ease forwards`;
setTimeout(()=>{el.style.animation='';busy=false;},220);
},170);
}
/* ════════════════════════════════
PAGE RENDERERS
════════════════════════════════ */
function pgHome(){return`
<div style="text-align:center;margin-bottom:30px">
<div class="serif" style="font-size:10px;letter-spacing:4px;color:var(--t3);margin-bottom:10px">学習修復システム · FlashFix AI</div>
<h1 class="serif" style="font-size:26px;font-weight:800;line-height:1.35">เปลี่ยนทุกข้อผิดพลาด<br>ให้กลายเป็นความเข้าใจ</h1>
<p style="color:var(--t2);font-size:13px;margin-top:10px;line-height:1.9">วิเคราะห์ error · เฉลยทีละขั้น · Teach-Back · Flashcard · Spaced Repetition</p>
</div>
<div class="g2" style="margin-bottom:16px">
<button id="btn-mode-file" class="card card-hover" style="text-align:left;cursor:pointer;padding:22px;font-family:'Noto Sans Thai',sans-serif">
<div style="font-size:28px;margin-bottom:10px">📄</div>
<div style="font-size:15px;font-weight:700;margin-bottom:5px">อัปโหลดไฟล์</div>
<div style="font-size:12px;color:var(--t2);line-height:1.7">PDF, PowerPoint, รูปภาพ<br>AI สรุป + สร้างข้อสอบจำลอง</div>
<div style="margin-top:12px;display:flex;gap:5px;flex-wrap:wrap">
${b('PDF','var(--red)','var(--redl)')} ${b('PPTX','var(--blue)','var(--bluel)')} ${b('Image','var(--ok)','var(--okl)')}
</div>
</button>
<button id="btn-mode-topic" class="card card-hover" style="text-align:left;cursor:pointer;padding:22px;font-family:'Noto Sans Thai',sans-serif">
<div style="font-size:28px;margin-bottom:10px">📐</div>
<div style="font-size:15px;font-weight:700;margin-bottom:5px">เลือกหัวข้อ</div>
<div style="font-size:12px;color:var(--t2);line-height:1.7">คณิตศาสตร์ ม.1–6<br>AI วิเคราะห์ error + เฉลยละเอียด</div>
<div style="margin-top:12px;display:flex;gap:5px;flex-wrap:wrap">
${b('∂ อนุพันธ์','var(--pur)','var(--purl)')} ${b('∫ อินทิกรัล','var(--gold)','var(--goldl)')} ${b('+6 อีก','var(--t2)','#F0EDE6')}
</div>
</button>
</div>
<div class="card" style="background:var(--goldl);border-color:var(--goldb)">
<div style="display:flex;gap:14px;align-items:center">
<div style="font-size:22px">🔬</div>
<div>
<div style="font-size:12px;font-weight:700;color:var(--gold);margin-bottom:3px">Learning Science ฝังอยู่ในระบบ</div>
<div style="font-size:12px;color:var(--t1)">Retrieval Practice +28% · Self-Explanation +35% · Spaced Repetition +40%</div>
</div>
</div>
</div>`;}
function pgFileUpload(){return`
<div style="margin-bottom:20px">
<div class="serif" style="font-size:10px;letter-spacing:3px;color:var(--t3);margin-bottom:8px">FILE UPLOAD · ファイル読込</div>
<h2 class="serif" style="font-size:22px;font-weight:800">อัปโหลดเอกสาร</h2>
<p style="font-size:13px;color:var(--t2);margin-top:5px">AI วิเคราะห์และสร้างข้อสอบภายใน ~3 วินาที</p>
</div>
<div id="drop-zone" class="drop-zone" style="margin-bottom:18px">
<div style="font-size:42px;margin-bottom:12px">📂</div>
<div style="font-size:15px;font-weight:600;color:var(--t1);margin-bottom:6px">ลากไฟล์มาวางที่นี่</div>
<div style="font-size:12px;color:var(--t3);margin-bottom:18px">หรือกดเพื่อเลือก · สูงสุด 15MB</div>
<div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap">
${['📄 PDF','📊 PowerPoint (.pptx)','🖼️ JPG/PNG'].map(x=>`<div style="background:#fff;border:1px solid var(--b1);border-radius:20px;padding:5px 12px;font-size:11px;color:var(--t2)">${x}</div>`).join('')}
</div>
<input type="file" id="file-input" accept=".pdf,.pptx,.ppt,image/*" style="display:none">
</div>
<div style="display:flex;justify-content:flex-start">
<button class="btn btn-g" id="btn-back-home">← กลับหน้าแรก</button>
</div>`;}
function pgFileProcessing(){
const steps=['📖 อ่านไฟล์...','🧠 วิเคราะห์เนื้อหา...','📝 สร้างข้อสอบ 5 ข้อ...'];
return`<div style="padding:8px 0">
<div style="text-align:center;margin-bottom:28px">
<div style="font-size:44px;margin-bottom:14px;display:inline-block;animation:pulse 1.2s ease infinite">⚙️</div>
<div class="serif" style="font-size:19px;font-weight:700;margin-bottom:6px">AI กำลังวิเคราะห์ไฟล์</div>
<div style="font-size:12px;color:var(--t2)">${S.fileName}</div>
</div>
${steps.map((l,i)=>`<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;padding:12px 16px;background:#FAFAF8;border-radius:8px;animation:fadeUp .3s ${i*.1}s both ease">
<div class="spin"></div>
<div style="font-size:13px;color:var(--t2)">${l}</div>
<div class="sk" style="flex:1;height:12px;margin:0"></div>
</div>`).join('')}
${loading('Claude AI กำลังประมวลผล...')}
</div>`;}
function pgFileSummary(){
const fs=S.fileSummary;
if(!fs)return loading('กำลังโหลด...');
return`
<div style="margin-bottom:18px">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:14px">
<div style="width:44px;height:44px;border-radius:12px;background:var(--bluel);border:1px solid var(--blueb);display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0">📄</div>
<div>
<div style="font-size:15px;font-weight:700">${fs.title||S.fileName}</div>
<div style="font-size:11px;color:var(--t3)">${fs.subject||''}</div>
</div>
</div>
<div style="display:flex;gap:5px;flex-wrap:wrap">${(fs.topics||[]).map(t=>`<span class="badge" style="color:var(--blue);background:var(--bluel)">${t}</span>`).join('')}</div>
</div>
<div class="card" style="margin-bottom:16px;background:#FAFAF8">
<div class="serif" style="font-size:10px;letter-spacing:2px;color:var(--t3);margin-bottom:8px">สรุปเนื้อหา</div>
<p style="font-size:13px;line-height:1.9">${fs.summary||''}</p>
</div>
<div class="card" style="margin-bottom:20px;background:var(--bluel);border-color:var(--blueb)">
<div style="display:flex;justify-content:space-between;align-items:center">
<div><div style="font-size:13px;font-weight:700;color:var(--blue)">ข้อสอบจำลอง</div>
<div style="font-size:12px;color:var(--blue);margin-top:2px">${(fs.questions||[]).length} คำถาม Multiple Choice</div></div>
<div style="font-size:30px">📝</div>
</div>
</div>
<div style="display:flex;gap:10px;justify-content:space-between">
<button class="btn btn-g" id="btn-back-upload">← อัปโหลดใหม่</button>
<button class="btn btn-p" id="btn-start-exam">เริ่มทำข้อสอบ →</button>
</div>`;}
function pgExamMC(){
if(!S.examQ.length)return loading('กำลังโหลด...');
const q=S.examQ[S.examIdx],total=S.examQ.length;
const allAns=Object.keys(S.examA).length===total;
return`
<div style="margin-bottom:18px">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:9px">
<div style="font-size:12px;color:var(--t3)">ข้อ ${S.examIdx+1}/${total}</div>
<div style="font-size:12px;font-weight:600;color:var(--red)">${Object.keys(S.examA).length}/${total} ตอบแล้ว</div>
</div>
<div class="prog-bar"><div class="prog-fill" style="--w:${Math.round(((S.examIdx+1)/total)*100)}%;background:var(--red)"></div></div>
<div style="display:flex;gap:4px;margin-top:8px">
${S.examQ.map((_,i)=>`<div class="q-dot" data-goto="${i}" style="flex:1;height:4px;border-radius:2px;cursor:pointer;transition:all .2s;background:${i===S.examIdx?'var(--red)':S.examA[i]!==undefined?'var(--ok)':'var(--b1)'}"></div>`).join('')}
</div>
</div>
<div class="card" style="margin-bottom:16px;background:#FAFAF8;animation:cardFlipIn .25s ease">
<p style="font-size:15px;font-weight:600;line-height:1.9">${q.q}</p>
</div>
<div style="display:flex;flex-direction:column;gap:9px;margin-bottom:20px">
${q.options.map((opt,i)=>{const sel=S.examA[S.examIdx]===i;return`<button class="opt ${sel?'selected':''}" data-oi="${i}" style="animation:fadeUp .15s ${i*.04}s both ease">
<div class="opt-lbl" style="${sel?'background:var(--red);color:#fff':'background:var(--redl);color:var(--red)'}">${'ABCD'[i]}</div>
<span style="font-size:13px;line-height:1.7">${opt}</span>
</button>`;}).join('')}
</div>
<div style="display:flex;justify-content:space-between;align-items:center">
<button class="btn btn-g" id="btn-exam-prev" ${S.examIdx===0?'disabled':''}>‹ ก่อนหน้า</button>
${allAns?`<button class="btn btn-p" id="btn-submit-exam">ส่งคำตอบ ✓</button>`:S.examIdx<total-1?`<button class="btn btn-p" id="btn-exam-next" ${S.examA[S.examIdx]===undefined?'disabled':''}>ถัดไป ›</button>`:''}
</div>`;}
function pgExamResult(){
if(!S.examResult)return loading();
const r=S.examResult,pct=Math.round(r.score/r.total*100),pass=pct>=60;
const grade=pct>=80?'A':pct>=70?'B':pct>=60?'C':pct>=50?'D':'F';
return`
<div style="text-align:center;margin-bottom:26px">
<div style="animation:countUp .5s var(--ease-spring) forwards">
<div class="serif" style="font-size:64px;font-weight:800;color:${pass?'var(--ok)':'var(--red)'};line-height:1">${r.score}/${r.total}</div>
<div style="font-size:14px;font-weight:700;color:${pass?'var(--ok)':'var(--red)'};margin-top:4px">${pct}% · Grade ${grade} · ${pass?'ผ่าน 🎉':'ต้องพัฒนา 💪'}</div>
</div>
<div class="prog-bar" style="max-width:200px;margin:14px auto 0;height:8px;border-radius:4px">
<div class="prog-fill" style="--w:${pct}%;background:${pass?'var(--ok)':'var(--red)'}"></div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:7px;margin-bottom:22px">
${S.examQ.map((q,i)=>{const ua=S.examA[i],correct=ua===q.correct;return`
<div class="card" style="padding:12px 16px;border-color:${correct?'var(--okb)':'var(--warnb)'};animation:fadeUp .2s ${i*.05}s both ease">
<div style="display:flex;justify-content:space-between;gap:10px">
<div style="flex:1">
<div style="font-size:12px;font-weight:600;color:${correct?'var(--ok)':'var(--warn)'}">ข้อ ${i+1} ${correct?'✓':'✗'}</div>
<div style="font-size:12px;color:var(--t2);margin-top:2px;line-height:1.6">${q.q.substring(0,70)}${q.q.length>70?'...':''}</div>
${!correct?`<div style="font-size:11px;margin-top:4px"><span style="color:var(--warn)">คุณตอบ: ${ua!==undefined?q.options[ua]:'ไม่ตอบ'}</span><br><span style="color:var(--ok)">เฉลย: ${q.options[q.correct]}</span></div>`:''}
</div>
<div style="font-size:22px">${correct?'✅':'❌'}</div>
</div>
</div>`;}).join('')}
</div>
${r.wrong.length?`<div style="display:flex;gap:10px;flex-wrap:wrap">
<button class="btn btn-b" id="btn-view-explains">ดูเฉลย (${r.wrong.length} ข้อ)</button>
<button class="btn btn-p" id="btn-fc-from-exam">สร้าง Flashcard →</button>
</div>`:`<div class="card" style="background:var(--okl);border-color:var(--okb);text-align:center;padding:20px">
<div style="font-size:28px;margin-bottom:6px">🏆</div>
<div style="font-weight:700;color:var(--ok);font-size:16px">สมบูรณ์แบบ!</div>
<button class="btn btn-p" style="margin-top:12px" id="btn-goto-mastery">ดู Mastery →</button>
</div>`}
<div style="margin-top:12px;text-align:center">
<button class="btn btn-g" id="btn-restart" style="font-size:12px">← กลับหน้าแรก</button>
</div>`;}
function pgWrongExplains(){
const wrongIs=S.examResult?.wrong||[],i=S.wrongIdx,qi=wrongIs[i],q=S.examQ[qi];
if(!q)return loading();
const ex=S.wrongExplains[qi];
return`
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px">
<div style="font-size:12px;color:var(--t3)">ข้อผิด ${i+1}/${wrongIs.length}</div>
<div style="display:flex;gap:5px">${wrongIs.map((_,j)=>`<div class="we-dot" data-wei="${j}" style="width:10px;height:10px;border-radius:50%;cursor:pointer;background:${j===i?'var(--red)':S.wrongExplains[wrongIs[j]]?'var(--ok)':'var(--b1)'}"></div>`).join('')}</div>
</div>
<div class="card" style="margin-bottom:14px;background:#FAFAF8"><p style="font-size:14px;font-weight:600;line-height:1.8">${q.q}</p></div>
<div style="display:flex;flex-direction:column;gap:6px;margin-bottom:14px">
${q.options.map((opt,oi)=>{const isUser=S.examA[qi]===oi,isRight=q.correct===oi;return`<div class="opt ${isRight?'correct':isUser?'wrong':''}" style="cursor:default">
<div class="opt-lbl" style="${isRight?'background:var(--ok);color:#fff':isUser?'background:var(--warn);color:#fff':'background:#f0ede8;color:var(--t3)'}">${'ABCD'[oi]}</div>
<div style="flex:1"><span style="font-size:13px">${opt}</span>${isRight?' <span style="font-size:11px;color:var(--ok)">✓ ถูกต้อง</span>':''}${isUser&&!isRight?' <span style="font-size:11px;color:var(--warn)">← คุณเลือก</span>':''}</div>
</div>`;}).join('')}
</div>
${ex?`<div class="card" style="background:var(--bluel);border-color:var(--blueb);margin-bottom:14px">
<div class="serif" style="font-size:10px;letter-spacing:2px;color:var(--blue);margin-bottom:10px">เฉลยละเอียด</div>
${ex.steps.map(s=>`<div style="display:flex;gap:10px;margin-bottom:10px">
<div style="width:22px;height:22px;border-radius:50%;background:var(--blue);color:#fff;font-size:11px;font-weight:700;display:flex;align-items:center;justify-content:center;flex-shrink:0;margin-top:1px">${s.num}</div>
<div><div style="font-size:12px;font-weight:600;margin-bottom:3px">${s.title}</div>
${s.math?`<pre style="font-size:12px;color:var(--blue);background:#fff;border:1px solid var(--blueb);border-radius:5px;padding:8px;white-space:pre-wrap;font-family:monospace;margin-bottom:4px">${s.math}</pre>`:''}
<div style="font-size:12px;color:var(--t2)">${s.explain}</div></div>
</div>`).join('')}
<div style="background:#fff;border-radius:6px;padding:10px 12px"><div style="font-size:11px;font-weight:700;color:var(--blue);margin-bottom:2px">จุดสำคัญ</div><div style="font-size:12px">${ex.keyPoint}</div></div>
</div>`:S.loading?loading('AI สร้างเฉลย...'):`<button class="btn btn-b" id="btn-load-explain" style="width:100%;margin-bottom:14px">📖 ดูเฉลยละเอียด</button>`}
<div style="display:flex;justify-content:space-between">
<button class="btn btn-g" id="btn-we-prev" ${i===0?'disabled':''}>‹</button>
${i<wrongIs.length-1?`<button class="btn btn-p" id="btn-we-next">ถัดไป ›</button>`:`<button class="btn btn-p" id="btn-fc-from-wrong">สร้าง Flashcard →</button>`}
</div>`;}
function pgTopicSelect(){return`
<div style="text-align:center;margin-bottom:24px">
<div class="serif" style="font-size:10px;letter-spacing:4px;color:var(--t3);margin-bottom:6px">TOPIC SELECT · 数学トピック</div>
<h2 class="serif" style="font-size:24px;font-weight:800">เลือกหัวข้อคณิตศาสตร์</h2>
</div>
<div class="g4" style="margin-bottom:18px">
${TOPICS.map((t,i)=>`<button class="topic-btn card card-hover" data-id="${t.id}"
style="text-align:left;cursor:pointer;padding:16px 14px;font-family:'Noto Sans Thai',sans-serif;animation:fadeUp .22s ${i*.04}s both ease">
<div class="serif" style="font-size:20px;color:var(--red);margin-bottom:8px">${t.sym}</div>
<div style="font-size:13px;font-weight:600">${t.th}</div>
<div style="font-size:10px;color:var(--t3);margin-top:2px">${t.lv}</div>
<div style="margin-top:10px"><div class="prog-bar"><div class="prog-fill" style="--w:${S.mastery[t.id]||0}%;background:${(S.mastery[t.id]||0)>=70?'var(--ok)':'var(--red)'}"></div></div></div>
</button>`).join('')}
</div>
<button class="btn btn-g" id="btn-back-home2">← กลับหน้าแรก</button>`;}
function pgQuiz(){
if(!S.quiz||S.loading)return loading('AI กำลังสร้างโจทย์...');
return`
<div style="display:flex;align-items:center;gap:8px;margin-bottom:18px;flex-wrap:wrap">
${b(S.topic.th)} <span style="font-size:11px;color:var(--t3)">${S.topic.jp} · ${S.topic.lv}</span>
${b(S.quiz.difficulty==='hard'?'🔴 ยาก':S.quiz.difficulty==='medium'?'🟡 ปานกลาง':'🟢 ง่าย','var(--t2)','#F0EDE6')}
</div>
<div class="card" style="margin-bottom:16px;background:#FAFAF8">
<div class="serif" style="font-size:10px;letter-spacing:2px;color:var(--t3);margin-bottom:10px">DIAGNOSTIC QUIZ</div>
<p style="font-size:16px;font-weight:600;line-height:1.9">${S.quiz.question}</p>
${S.quiz.hint?`<div style="margin-top:10px;font-size:12px;color:var(--t2);border-top:1px solid var(--b1);padding-top:8px">💡 ${S.quiz.hint}</div>`:''}
</div>
${S.showAnswer?`<div style="background:var(--goldl);border:1.5px solid var(--goldb);border-radius:10px;padding:14px 18px;margin-bottom:14px;animation:fadeUp .2s ease">
<div style="font-size:11px;font-weight:700;color:var(--gold);margin-bottom:7px">💡 เฉลย (ลองทำตามแล้วพิมพ์ด้านล่าง)</div>
<pre style="font-size:13px;color:var(--t1);white-space:pre-wrap;font-family:'Noto Sans Thai',sans-serif;line-height:1.9">${S.quiz.answer}</pre>
</div>`:''}
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:7px">
<label style="font-size:11px;color:var(--t2);font-weight:600">คำตอบ / วิธีทำ</label>
<button id="btn-toggle-ans" style="background:${S.showAnswer?'var(--goldl)':'transparent'};border:1.5px solid ${S.showAnswer?'var(--goldb)':'var(--b1)'};border-radius:6px;padding:5px 11px;font-size:11px;font-weight:600;cursor:pointer;color:${S.showAnswer?'var(--gold)':'var(--t3)'};transition:all .18s;font-family:'Noto Sans Thai',sans-serif">
${S.showAnswer?'🙈 ซ่อนเฉลย':'💡 ดูเฉลย'}
</button>
</div>
<textarea id="ans-ta" rows="5" placeholder="พิมพ์วิธีทำและคำตอบ..."
style="width:100%;padding:14px;border:1.5px solid var(--b1);border-radius:8px;font-size:13px;line-height:1.9;color:var(--t1);background:#fff;margin-bottom:16px;resize:vertical;transition:border-color .18s"
>${S.answer}</textarea>
<div style="display:flex;justify-content:space-between">
<button class="btn btn-g" id="btn-back-topic">← เปลี่ยนหัวข้อ</button>
<button class="btn btn-p" id="btn-submit-q" ${!S.answer.trim()?'disabled':''}>ส่งคำตอบ →</button>
</div>`;}
function pgSolution(){
if(S.loading||!S.solution)return loading('AI กำลังตรวจคำตอบ...');
const sol=S.solution;
if(sol.isCorrect)return`
<div style="background:var(--okl);border:1.5px solid var(--okb);border-radius:12px;padding:28px;text-align:center;margin-bottom:20px;animation:scaleIn .3s var(--ease-spring)">
<div style="font-size:40px;margin-bottom:10px">🎉</div>
<div style="font-size:20px;font-weight:700;color:var(--ok)">ถูกต้องสมบูรณ์!</div>
<p style="font-size:13px;color:var(--t2);margin-top:6px">AI ตรวจแล้ว — คำตอบของคุณถูกต้อง</p>
</div>
<div style="display:flex;justify-content:space-between">
<button class="btn btn-g" id="btn-back-quiz2">← ทำใหม่</button>
<button class="btn btn-p" id="btn-goto-mastery">ดู Mastery →</button>
</div>`;
const tabs=`<div style="display:flex;border-bottom:1px solid var(--b1);margin-bottom:18px;overflow-x:auto">
<button class="tab ${S.activeTab==='solution'?'on':''}" id="tab-sol">เฉลยทีละขั้น</button>
<button class="tab ${S.activeTab==='compare'?'on':''}" id="tab-cmp">เปรียบเทียบ</button>
<button class="tab ${S.activeTab==='keyrule'?'on':''}" id="tab-kr">กฎสำคัญ</button>
</div>`;
let body='';
if(S.activeTab==='solution'){
body=`<div style="background:var(--warnl);border:1px solid var(--warnb);border-radius:8px;padding:13px 16px;margin-bottom:14px">
<div style="font-weight:700;font-size:13px;color:var(--warn)">${sol.errorType||''} · ${sol.errorTypeThai||''}</div>
<p style="font-size:13px;margin-top:5px;line-height:1.8">${sol.studentMistake||''}</p>
</div>
${(sol.steps||[]).map((s,i)=>`<div style="display:flex;gap:12px;margin-bottom:10px;padding:12px 16px;background:#fff;border:1px solid var(--b1);border-radius:8px;animation:fadeUp .2s ${i*.06}s both ease">
<div style="width:26px;height:26px;border-radius:50%;background:var(--redl);color:var(--red);font-size:11px;font-weight:700;display:flex;align-items:center;justify-content:center;flex-shrink:0">${s.num}</div>
<div><div style="font-size:13px;font-weight:600;margin-bottom:4px">${s.title}</div>
${s.math?`<pre style="font-size:12px;color:var(--blue);background:var(--bluel);border:1px solid var(--blueb);border-radius:5px;padding:8px 12px;white-space:pre-wrap;font-family:monospace;line-height:1.7;margin-bottom:5px">${s.math}</pre>`:''}
<div style="font-size:12px;color:var(--t2)">${s.explain}</div></div>
</div>`).join('')}
${sol.commonTrap?`<div style="background:var(--goldl);border:1px solid var(--goldb);border-radius:6px;padding:11px 14px">
<span style="font-size:11px;font-weight:700;color:var(--gold)">⚠ กับดักพบบ่อย: </span><span style="font-size:12px">${sol.commonTrap}</span>
</div>`:''}`;
}else if(S.activeTab==='compare'){
body=`<div class="g2" style="gap:12px">
<div><div style="font-size:11px;font-weight:700;color:var(--warn);margin-bottom:7px">✕ คำตอบคุณ</div>
<div style="background:var(--warnl);border:1px solid var(--warnb);border-radius:8px;padding:12px"><pre style="font-size:12px;color:var(--warn);white-space:pre-wrap;font-family:monospace;line-height:1.6">${sol.studentAnswer||S.answer}</pre></div>
</div>
<div><div style="font-size:11px;font-weight:700;color:var(--ok);margin-bottom:7px">✓ เฉลยถูก</div>
<div style="background:var(--okl);border:1px solid var(--okb);border-radius:8px;padding:12px"><pre style="font-size:12px;color:var(--ok);white-space:pre-wrap;font-family:monospace;line-height:1.6">${S.quiz?.answer||''}</pre></div>
</div>
</div>`;
}else{
body=`<div class="card" style="background:var(--bluel);border-color:var(--blueb);margin-bottom:12px">
<div class="serif" style="font-size:10px;letter-spacing:2px;color:var(--blue);margin-bottom:7px">KEY RULE</div>
<p style="font-size:14px;font-weight:600;line-height:1.9">${sol.keyRule||''}</p>
</div>
${sol.severity?`<span class="badge" style="color:${sol.severity==='fundamental'?'var(--red)':sol.severity==='major'?'var(--warn)':'var(--ok)'};background:${sol.severity==='fundamental'?'var(--redl)':sol.severity==='major'?'var(--warnl)':'var(--okl)'}">Error Level: ${sol.severity}</span>`:''}`;
}
return`${tabs}${body}
<div class="divider"></div>
<div style="display:flex;justify-content:space-between">
<button class="btn btn-g" id="btn-back-quiz">← แก้ใหม่</button>
<button class="btn btn-p" id="btn-goto-tb">Teach-Back →</button>
</div>`;}
function pgTeachBack(){
if(S.tbResult){
const r=S.tbResult,pass=r.passed;
return`
<div style="text-align:center;margin-bottom:22px;animation:scaleIn .3s var(--ease-spring)">
<div style="font-size:48px;margin-bottom:10px">${pass?'🎓':'💪'}</div>
<div class="serif" style="font-size:24px;font-weight:800;color:${pass?'var(--ok)':'var(--warn)'}">${pass?'ผ่าน!':'ยังไม่ผ่าน'}</div>
<div style="font-size:36px;font-weight:700;color:${pass?'var(--ok)':'var(--warn)'}">${r.score}/10</div>
<div class="prog-bar" style="max-width:160px;margin:10px auto 0;height:8px;border-radius:4px"><div class="prog-fill" style="--w:${r.score*10}%;background:${pass?'var(--ok)':'var(--warn)'}"></div></div>
</div>
<div class="card" style="background:${pass?'var(--okl)':'var(--warnl)'};border-color:${pass?'var(--okb)':'var(--warnb)'};margin-bottom:16px">
<p style="font-size:13px;line-height:1.9">${r.feedback}</p>
${r.conceptGap?`<div style="margin-top:10px;padding:10px;background:#fff;border-radius:6px;font-size:12px;color:var(--warn)">⚠ ยังขาด: ${r.conceptGap}</div>`:''}
</div>
<p style="font-size:13px;color:var(--t2);text-align:center;margin-bottom:20px">${r.encouragement}</p>
<div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">
${!pass?`<button class="btn btn-g" id="btn-retry-tb">ลองใหม่</button>`:''}
<button class="btn btn-p" id="btn-goto-fc">สร้าง Flashcard →</button>
</div>`;}
if(S.loading)return loading('AI กำลังตรวจ Teach-Back...');
return`
<div style="margin-bottom:18px">
<div class="serif" style="font-size:10px;letter-spacing:3px;color:var(--t3);margin-bottom:7px">TEACH-BACK</div>
<h2 class="serif" style="font-size:20px;font-weight:800">อธิบายราวกับสอนเพื่อน</h2>
<p style="font-size:12px;color:var(--t2);margin-top:5px;line-height:1.8">อธิบาย error + กฎที่ถูกต้อง — AI จะตรวจอย่างตรงไปตรงมา</p>
</div>
<div class="card" style="margin-bottom:12px;background:var(--redl);border-color:var(--redm);padding:12px 16px">
<div style="font-size:11px;color:var(--red);font-weight:700;margin-bottom:2px">Error ที่เกิด</div>
<div style="font-size:13px">${S.solution?.errorTypeThai||''}</div>
</div>
<textarea id="tb-ta" rows="5" placeholder="อธิบายว่าเกิดอะไร กฎคืออะไร..."
style="width:100%;padding:14px;border:1.5px solid var(--b1);border-radius:8px;font-size:13px;line-height:1.8;background:#fff;margin-bottom:16px;resize:vertical;transition:border-color .18s"
>${S.teachBack}</textarea>
<div style="display:flex;justify-content:space-between">
<button class="btn btn-g" id="btn-back-sol">← กลับ</button>
<button class="btn btn-p" id="btn-submit-tb" ${S.teachBack.trim().length<15?'disabled':''}>ส่งให้ตรวจ →</button>
</div>`;}
/* ════ FLASHCARD (REDESIGNED) ════ */
function pgFlashcards(){
if(S.loading||!S.flashcards.length)return loading('AI กำลังสร้าง Flashcard...');
const idx=S.cardIdx,total=S.flashcards.length,card=S.flashcards[idx];
const done=Object.values(S.cardsDone).filter(Boolean).length;
const gradMap={accent:'fc-gradient-accent',blue:'fc-gradient-blue',purple:'fc-gradient-purple',teal:'fc-gradient-teal',gold:'fc-gradient-gold'};
const grad=gradMap[card.color]||'fc-gradient-accent';
const diffColor={easy:'var(--ok)',medium:'var(--gold)',hard:'var(--warn)'};
const dc=diffColor[card.difficulty]||'var(--t3)';
return`
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
<div style="font-size:12px;color:var(--t3)">การ์ด ${idx+1}/${total} · จำได้ ${done}/${total}</div>
<div style="font-size:10px;color:var(--t3)">⌨ ← → เลื่อน · Space พลิก</div>
</div>
<div style="display:flex;gap:4px;margin-bottom:16px">
${S.flashcards.map((_,i)=>`<div class="fc-dot" data-ci="${i}" style="flex:1;height:5px;border-radius:3px;cursor:pointer;transition:all .25s;background:${i===idx?'var(--red)':S.cardsDone[i]?'var(--ok)':'var(--b1)'}"></div>`).join('')}
</div>
<!-- Card -->
<div class="fc-scene" onclick="doFlip()" style="height:280px;margin-bottom:16px;position:relative">
<div class="fc-inner ${S.flipped?'flipped':''}" style="animation:${S.flipped?'none':'cardFlipIn .3s ease'}">
<!-- FRONT -->
<div class="fc-face ${grad}" style="padding:0">
<!-- Header bar -->
<div style="padding:14px 20px 10px;display:flex;justify-content:space-between;align-items:center">
<span style="font-size:10px;font-weight:700;color:rgba(255,255,255,.7);letter-spacing:1.5px;text-transform:uppercase">${card.rule||'CONCEPT'}</span>
<div style="display:flex;gap:6px;align-items:center">
${card.difficulty?`<span style="font-size:10px;background:rgba(0,0,0,.2);color:#fff;padding:2px 8px;border-radius:10px;font-weight:600">${card.difficulty==='easy'?'ง่าย':card.difficulty==='medium'?'ปานกลาง':'ยาก'}</span>`:''}
<span style="font-size:16px;color:rgba(255,255,255,.5)">↻</span>
</div>
</div>
<!-- Question -->
<div style="flex:1;display:flex;align-items:center;justify-content:center;padding:10px 22px">
<p style="font-size:18px;font-weight:700;color:#fff;line-height:1.7;text-align:center;text-shadow:0 1px 3px rgba(0,0,0,.2)">${card.front}</p>
</div>
<!-- Hint -->
${card.hint?`<div style="padding:10px 20px 16px;font-size:11px;color:rgba(255,255,255,.65);text-align:center">💡 ${card.hint}</div>`:`<div style="padding:10px 20px 16px;font-size:11px;color:rgba(255,255,255,.45);text-align:center">แตะเพื่อดูคำตอบ</div>`}
</div>
<!-- BACK -->
<div class="fc-face fc-back" style="background:#fff;border:1.5px solid var(--b1);padding:0;overflow-y:auto">
<!-- Header -->
<div style="padding:12px 18px 10px;border-bottom:1px solid var(--b1);display:flex;justify-content:space-between;align-items:center;flex-shrink:0">
<span style="font-size:10px;font-weight:700;color:var(--t3);letter-spacing:1px">คำตอบ</span>
<span style="font-size:10px;color:var(--t3)">${card.rule||''}</span>
</div>
<!-- Answer -->
<div style="padding:14px 18px;flex:1">
<pre style="font-size:15px;font-weight:700;color:var(--red);white-space:pre-wrap;font-family:'Noto Sans Thai',sans-serif;line-height:1.8;margin-bottom:12px">${card.back}</pre>
${card.example?`<div style="background:var(--bluel);border:1px solid var(--blueb);border-radius:8px;padding:10px 12px;margin-bottom:10px">
<div style="font-size:10px;font-weight:700;color:var(--blue);margin-bottom:4px">ตัวอย่างประยุกต์</div>
<div style="font-size:12px;color:var(--t1);line-height:1.8">${card.example}</div>
</div>`:''}
</div>
</div>
</div>
</div>
<!-- Controls -->
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px">
<button class="btn btn-o" id="btn-fc-prev" ${idx===0?'disabled':''} style="min-width:40px">‹</button>
<div style="display:flex;gap:8px">
${S.flipped?`
<button class="btn" id="btn-fc-done" style="background:var(--okl);color:var(--ok);border-color:var(--okb);font-size:13px">✓ จำได้</button>
<button class="btn btn-o" id="btn-fc-again" style="font-size:13px">🔄 ทบทวน</button>`:''}
</div>
<button class="btn btn-o" id="btn-fc-next" ${idx===total-1?'disabled':''} style="min-width:40px">›</button>
</div>
<!-- Progress ring visualization -->
<div style="display:flex;align-items:center;gap:14px;background:#FAFAF8;border-radius:10px;padding:12px 16px;margin-bottom:18px">
<div style="position:relative;width:48px;height:48px;flex-shrink:0">
<svg viewBox="0 0 36 36" style="width:48px;height:48px;transform:rotate(-90deg)">
<circle cx="18" cy="18" r="15.9" fill="none" stroke="#EDE8E0" stroke-width="3"/>
<circle cx="18" cy="18" r="15.9" fill="none" stroke="var(--ok)" stroke-width="3" stroke-dasharray="${done/total*100} ${100-done/total*100}" stroke-dashoffset="0" stroke-linecap="round" style="transition:stroke-dasharray .5s ease"/>
</svg>
<div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--ok)">${Math.round(done/total*100)}%</div>
</div>
<div><div style="font-size:12px;font-weight:600">ความคืบหน้า</div><div style="font-size:11px;color:var(--t3);margin-top:2px">จำได้ ${done} จาก ${total} การ์ด</div></div>
</div>
${S.remMiniQuiz.length?`
<div class="divider"></div>
<div style="font-size:11px;color:var(--t2);letter-spacing:.6px;margin-bottom:12px;font-weight:600">REMEDIAL QUIZ · 確認テスト</div>
${S.remMiniQuiz.map((q,i)=>`<div class="card" style="margin-bottom:9px;padding:14px 16px;animation:fadeUp .2s ${i*.08}s both ease">
<p style="font-size:13px;font-weight:500;margin-bottom:9px">${i+1}. ${q.question}</p>
${S.quizReveal[i]?`<div style="background:var(--okl);border-radius:6px;padding:9px 12px;font-size:13px;color:var(--ok)">✓ ${q.answer}</div>`
:`<button class="btn btn-o btn-reveal" data-qi="${i}">ดูเฉลย</button>`}
</div>`).join('')}`:''}
<div style="display:flex;justify-content:space-between;margin-top:20px">
<button class="btn btn-g" id="btn-back-home3">← กลับหน้าแรก</button>
<button class="btn btn-p" id="btn-goto-spr">ตั้งตารางทบทวน →</button>
</div>`;}
/* ════ SPACED REPETITION + CALENDAR ════ */
function pgSpacedRep(){
const topic=S.topic?.th||S.fileSummary?.title?.substring(0,20)||'เนื้อหานี้';
const evs=buildReviewEvents(topic);
const fmt=ts=>{const d=new Date(ts);return`${d.getDate()}/${d.getMonth()+1}/${d.getFullYear()} เวลา 20:00`;}
const labels=['วันนี้ ก่อนนอน','พรุ่งนี้','4 วันหลังจากนี้','11 วันหลังจากนี้','25 วันหลังจากนี้'];
const notes=['Encoding ก่อนลืม','Sleep consolidation','Spacing effect','Long-term memory','Mastery check'];
return`
<div style="text-align:center;margin-bottom:24px">
<div class="serif" style="font-size:10px;letter-spacing:4px;color:var(--t3);margin-bottom:7px">SPACED REPETITION · 間隔反復法</div>
<h2 class="serif" style="font-size:22px">ตารางทบทวนอัตโนมัติ</h2>
<p style="font-size:13px;color:var(--t2);margin-top:5px"><strong>${topic}</strong> · 5 ช่วงเวลา optimal</p>
</div>
<!-- Calendar Add Buttons -->
<div style="background:var(--bluel);border:1px solid var(--blueb);border-radius:12px;padding:16px 18px;margin-bottom:20px">
<div style="font-size:13px;font-weight:700;color:var(--blue);margin-bottom:12px">📅 เพิ่มลงปฏิทินจริง</div>
<div style="display:flex;gap:10px;flex-wrap:wrap">
<button id="btn-gcal" class="btn-cal" style="background:#fff;color:#1a73e8;border-color:#d2e3fc">
<svg width="16" height="16" viewBox="0 0 24 24"><path fill="#1a73e8" d="M19 3H5C3.89 3 3 3.89 3 5v14c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm-7 14l-5-5 1.41-1.41L12 14.17l7.59-7.59L21 8l-9 9z"/></svg>
Google Calendar
</button>
<button id="btn-apple-cal" class="btn-cal" style="background:#fff;color:#555;border-color:#ddd">
<svg width="16" height="16" viewBox="0 0 24 24"><path fill="#555" d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.8-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"/></svg>
Apple / iCal (.ics)
</button>
</div>
<div style="font-size:11px;color:var(--blue);margin-top:10px">🔔 แต่ละนัดจะมีแจ้งเตือนล่วงหน้า 15 นาที</div>
</div>