-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndex.html
More file actions
1679 lines (1495 loc) · 103 KB
/
Copy pathIndex.html
File metadata and controls
1679 lines (1495 loc) · 103 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.0">
<title>Admission Tracker + AI Assistant</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@300;400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: 'Sarabun', sans-serif;
}
/* Custom Scrollbar */
.custom-scrollbar::-webkit-scrollbar {
width: 8px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: #c084fc;
border-radius: 4px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: #a855f7;
}
.dashed-box {
background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='8' ry='8' stroke='%23CBD5E1FF' stroke-width='2' stroke-dasharray='10%2c 10' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
transition: all 0.3s ease;
}
.dashed-box:hover {
background-color: #F8FAFC;
border-color: #94A3B8;
}
.swal2-popup {
font-family: 'Sarabun', sans-serif;
border-radius: 15px;
}
/* --- New Typography Styles for AI Output --- */
.prose-custom h1,
.prose-custom h2,
.prose-custom h3 {
color: #4338ca;
/* Indigo-700 */
font-weight: 700;
margin-top: 1.2em;
margin-bottom: 0.5em;
}
.prose-custom h3 {
font-size: 1.1em;
border-left: 4px solid #facc15;
padding-left: 8px;
}
.prose-custom p {
margin-bottom: 1em;
line-height: 1.7;
color: #374151;
}
.prose-custom ul {
list-style-type: disc;
padding-left: 1.5em;
margin-bottom: 1em;
}
.prose-custom ol {
list-style-type: decimal;
padding-left: 1.5em;
margin-bottom: 1em;
}
.prose-custom li {
margin-bottom: 0.5em;
}
.prose-custom strong {
color: #7e22ce;
font-weight: 700;
}
/* Purple emphasis */
.prose-custom blockquote {
border-left: 4px solid #e5e7eb;
padding-left: 1em;
color: #6b7280;
font-style: italic;
margin-bottom: 1em;
}
</style>
</head>
<body class="bg-gray-100 min-h-screen p-2 md:p-6">
<!-- Navbar -->
<div
class="max-w-7xl mx-auto bg-blue-600 text-white p-4 rounded-xl shadow-lg mb-6 flex flex-col md:flex-row justify-between items-center">
<div class="flex items-center gap-3">
<div class="bg-white/20 p-2 rounded-full"><i class="fas fa-user-graduate text-2xl"></i></div>
<div>
<h1 class="text-xl md:text-2xl font-bold">Admission Tracker</h1>
<p class="text-blue-100 text-sm">GPAX: <span id="displayGpax"
class="font-bold text-yellow-300">-.-</span></p>
</div>
</div>
<div class="mt-3 md:mt-0 text-right flex flex-col items-end">
<div class="flex items-center gap-2 bg-blue-700 px-3 py-1 rounded-lg">
<i class="fas fa-bullseye text-yellow-400"></i>
<span class="text-sm font-semibold">เป้าหมาย: <span id="headerTargetCount">5</span> มหาลัย</span>
<span id="uniCountBadge"
class="bg-white text-blue-700 text-xs font-bold px-2 py-0.5 rounded-full ml-1">0/5</span>
</div>
<div class="flex gap-2 mt-2">
<button onclick="openBudgetPlanner()"
class="bg-white/10 hover:bg-white/20 border border-white/20 text-white text-sm font-medium px-4 py-1.5 rounded-lg transition flex items-center gap-2 shadow-sm backdrop-blur-sm group">
<i class="fas fa-coins text-yellow-300 group-hover:scale-110 transition"></i> งบประมาณ
</button>
<button onclick="openSettings()"
class="bg-black/20 hover:bg-black/30 border border-transparent text-blue-100 text-sm font-medium px-4 py-1.5 rounded-lg transition flex items-center gap-2 shadow-sm">
<i class="fas fa-cog group-hover:rotate-90 transition"></i> ตั้งค่า
</button>
</div>
</div>
</div>
<div class="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-6 items-start h-full">
<!-- ================= LEFT COLUMN: AI ASSISTANT ================= -->
<div
class="bg-white rounded-xl shadow-md border border-purple-100 overflow-hidden flex flex-col lg:sticky lg:top-4">
<div
class="bg-gradient-to-r from-purple-100 to-indigo-50 p-4 border-b border-purple-200 flex items-center gap-2">
<i class="fas fa-robot text-purple-600 text-xl"></i>
<div>
<h2 class="font-bold text-purple-800">AI Assistant</h2>
<p class="text-xs text-purple-600">วิเคราะห์เชิงลึก & จิตวิทยา</p>
</div>
</div>
<div class="p-4 space-y-6 flex-grow overflow-y-auto custom-scrollbar"
style="max-height: calc(100vh - 150px);">
<!-- Feature 1: Question Generator -->
<div class="bg-purple-50 p-4 rounded-lg border border-purple-100 shadow-sm">
<h3 class="font-bold text-gray-700 mb-2 text-sm flex items-center">
<i class="fas fa-comment-dots text-purple-500 mr-2"></i>1. สถานการณ์ตอนนี้คือ?
</h3>
<textarea id="situationInput" rows="2"
class="w-full p-3 border border-purple-200 rounded-lg bg-white text-sm focus:outline-none focus:ring-2 focus:ring-purple-400 shadow-sm"
placeholder="เช่น น้องเอาแต่เล่นเกม บอกว่าทำเสร็จแล้วแต่ไม่ให้ดู..."></textarea>
<!-- Quick Chips -->
<div class="flex flex-wrap gap-2 mt-2 mb-3">
<button onclick="setSituation('น้องกำลังเล่นเกม ไม่สนใจทำพอร์ต')"
class="text-xs bg-white border border-purple-200 text-purple-600 px-2 py-1 rounded-full hover:bg-purple-100 transition shadow-sm">🎮
ติดเกม</button>
<button onclick="setSituation('น้องอ้างว่ามหาลัยเลื่อนกำหนดส่ง')"
class="text-xs bg-white border border-purple-200 text-purple-600 px-2 py-1 rounded-full hover:bg-purple-100 transition shadow-sm">📅
อ้างเลื่อนส่ง</button>
<button onclick="setSituation('น้องเงียบ ถามแล้วไม่ตอบ')"
class="text-xs bg-white border border-purple-200 text-purple-600 px-2 py-1 rounded-full hover:bg-purple-100 transition shadow-sm">🤐
ถามไม่ตอบ</button>
<button onclick="setSituation('น้องบอกว่าทำเสร็จแล้วแต่ไม่ให้ดู')"
class="text-xs bg-white border border-purple-200 text-purple-600 px-2 py-1 rounded-full hover:bg-purple-100 transition shadow-sm">🔒
ไม่ให้ดูงาน</button>
</div>
<button onclick="generateQuestion()"
class="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-2.5 px-4 rounded-lg transition text-sm flex justify-center items-center shadow-md">
<i class="fas fa-wand-magic-sparkles mr-2"></i> ขอคำแนะนำแบบละเอียด
</button>
</div>
<!-- Feature 2: Excuse Buster -->
<div class="bg-indigo-50 p-4 rounded-lg border border-indigo-100 shadow-sm">
<h3 class="font-bold text-gray-700 mb-2 text-sm flex items-center">
<i class="fas fa-search-plus text-indigo-500 mr-2"></i>2. น้องพูดแบบนี้จริงไหม? (จับเท็จ)
</h3>
<textarea id="siblingQuote" rows="2"
class="w-full p-3 border border-indigo-200 rounded-lg bg-white text-sm mb-3 focus:outline-none focus:ring-2 focus:ring-indigo-400 shadow-sm"
placeholder="พิมพ์สิ่งที่น้องพูดมา... เช่น 'เว็บล่ม สมัครไม่ได้เลย'"></textarea>
<button onclick="analyzeQuote()"
class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2.5 px-4 rounded-lg transition text-sm flex justify-center items-center shadow-md">
<i class="fas fa-microscope mr-2"></i> วิเคราะห์เจาะลึก
</button>
</div>
<!-- AI Output Area -->
<div id="aiResultContainer" class="hidden animate-fade-in-up">
<div class="bg-white rounded-lg shadow-lg border border-gray-200 overflow-hidden">
<div
class="bg-gray-100 px-4 py-3 flex justify-between items-center border-b text-sm font-bold text-gray-700">
<span><i class="fas fa-lightbulb text-yellow-500 mr-2"></i>คำแนะนำจาก AI</span>
<button onclick="closeResult()" class="text-gray-400 hover:text-red-500 transition"><i
class="fas fa-times fa-lg"></i></button>
</div>
<div id="aiOutputContent" class="p-5 prose-custom text-sm"></div>
</div>
</div>
</div>
</div>
<!-- ================= RIGHT COLUMN: UNIVERSITY DATA ================= -->
<div class="space-y-4">
<div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-bold text-gray-700 flex items-center gap-2">
<i class="fas fa-list-ul"></i> รายชื่อมหาวิทยาลัย
</h2>
<div class="flex gap-2">
<button id="toggleCalBtn" onclick="toggleCalendarView()"
class="bg-indigo-100 text-indigo-700 px-3 py-1.5 rounded-lg text-sm font-bold hover:bg-indigo-200 transition shadow-sm border border-indigo-200 flex items-center">
<i class="fas fa-calendar-alt mr-1"></i> ปฏิทิน
</button>
<div id="uniCountBadge"
class="bg-white text-blue-700 text-xs font-bold px-3 py-1.5 rounded-full shadow-sm border border-blue-100 flex items-center">
0/5
</div>
</div>
</div>
<div id="universityList" class="space-y-4 animate-fade-in-up">
<!-- Cards Injected Here -->
</div>
<!-- Calendar View Container -->
<div id="calendarViewContainer" class="hidden animate-fade-in-up">
<div class="bg-white rounded-xl shadow-lg border border-gray-100 min-h-[500px] p-4 relative">
<div
class="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-blue-400 via-indigo-500 to-purple-500 rounded-t-xl">
</div>
<h3 class="text-xl font-bold text-gray-800 mb-6 text-center mt-2">📅 ปฏิทิน Admission (ตามกำหนดการ)
</h3>
<div id="calendarViewContent" class="space-y-4">
<!-- Events Injected Here -->
</div>
</div>
</div>
</div>
<!-- Settings Modal -->
<div id="settingsModal"
class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex justify-center items-center">
<div class="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 overflow-hidden animate-fade-in-up">
<div class="bg-gray-100 px-4 py-3 border-b flex justify-between items-center">
<h3 class="font-bold text-gray-700"><i class="fas fa-cog text-gray-500 mr-2"></i>ตั้งค่าระบบ</h3>
<button onclick="closeSettings()" class="text-gray-400 hover:text-red-500"><i
class="fas fa-times"></i></button>
</div>
<div class="p-6 space-y-6">
<!-- API Key Section -->
<!-- General Settings Section -->
<div>
<label class="block text-sm font-bold text-gray-700 mb-2">ข้อมูลส่วนตัว & API</label>
<div class="space-y-3">
<div>
<label class="text-xs text-gray-500">GPAX (เกรดเฉลี่ย)</label>
<input type="number" step="0.01" id="gpaxInput" placeholder="0.00"
class="w-full p-2 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<div>
<label class="text-xs text-gray-500">เป้าหมายกี่มหาลัย?</label>
<input type="number" id="targetCountInput" value="5" min="1" max="20"
class="w-full p-2 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<div>
<label class="text-xs text-gray-500">Gemini API Key</label>
<input type="password" id="apiKeyInput" placeholder="วาง API Key ที่นี่..."
class="w-full p-2 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<button onclick="saveSettings()"
class="w-full bg-blue-600 text-white px-3 py-2 rounded text-sm hover:bg-blue-700 font-bold">บันทึกการตั้งค่า</button>
</div>
</div>
<hr>
<!-- Data Management Section -->
<div>
<label class="block text-sm font-bold text-gray-700 mb-2">จัดการข้อมูล (Backup/Restore)</label>
<div class="flex gap-2">
<button onclick="exportData()"
class="flex-1 bg-green-50 text-green-700 border border-green-200 hover:bg-green-100 px-4 py-2 rounded text-sm font-semibold">
<i class="fas fa-download mr-1"></i> เก็บข้อมูล (Export)
</button>
<button onclick="document.getElementById('importFile').click()"
class="flex-1 bg-orange-50 text-orange-700 border border-orange-200 hover:bg-orange-100 px-4 py-2 rounded text-sm font-semibold">
<i class="fas fa-upload mr-1"></i> กู้คืน (Import)
</button>
<input type="file" id="importFile" class="hidden" accept=".json"
onchange="importData(this)">
</div>
</div>
<hr>
<!-- Reset Section -->
<div>
<button onclick="resetData()"
class="w-full text-red-500 text-sm hover:bg-red-50 p-2 rounded transition">
ล้างข้อมูลทั้งหมด (Reset Factory)
</button>
</div>
</div>
</div>
</div>
<!-- Javascript Logic -->
<script>
// --- DATA MANAGEMENT (Same as before) ---
// --- DATA MANAGEMENT & MULTI-ROUND SUPPORT ---
const defaultUniversities = [
{
id: 1,
name: "มหาวิทยาลัยตัวอย่าง",
faculty: "คณะตัวอย่าง",
rounds: {
'1': { targetDate: "2025-12-31", officialDate: "2026-01-01", status: "Not Started", remark: "", qualifications: "", conditions: "" },
'2': { targetDate: "", officialDate: "", status: "Not Started", remark: "", qualifications: "", conditions: "" },
'3': { targetDate: "", officialDate: "", status: "Not Started", remark: "", qualifications: "", scoreCalc: "" },
'4': { targetDate: "", officialDate: "", status: "Not Started", remark: "" }
},
appFee: 0, tuitionFee: 0, dormFee: 0, livingCost: 0
}
];
let universities = [];
let geminiApiKey = "";
let userGpax = "-.-";
let targetUniCount = 5;
let currentGlobalRound = '1';
// --- SUBJECT CONSTANTS ---
const admissionSubjects = [
{ id: 'TGAT1', name: 'TGAT1 91 การสื่อสารภาษาอังกฤษ' },
{ id: 'TGAT2', name: 'TGAT2 92 การคิดอย่างมีเหตุผล' },
{ id: 'TGAT3', name: 'TGAT3 93 สมรรถนะการทำงาน' },
{ id: 'TPAT2', name: 'TPAT2 20 ความถนัดศิลปกรรมศาสตร์' },
{ id: 'TPAT3', name: 'TPAT3 30 ความถนัดวิทย์-เทคโนโลยี' },
{ id: 'TPAT4', name: 'TPAT4 40 ความถนัดสถาปัตยกรรม' },
{ id: 'TPAT5', name: 'TPAT5 50 ความถนัดครุศาสตร์' },
{ id: 'A-61', name: 'A-Level 61 Math1 คณิตศาสตร์ 1' },
{ id: 'A-62', name: 'A-Level 62 Math2 คณิตศาสตร์ 2' },
{ id: 'A-63', name: 'A-Level 63 Sci วิทย์ประยุกต์' },
{ id: 'A-64', name: 'A-Level 64 Phy ฟิสิกส์' },
{ id: 'A-65', name: 'A-Level 65 Chem เคมี' },
{ id: 'A-66', name: 'A-Level 66 Bio ชีววิทยา' },
{ id: 'A-70', name: 'A-Level 70 Soc สังคมศึกษา' },
{ id: 'A-81', name: 'A-Level 81 Thai ภาษาไทย' },
{ id: 'A-82', name: 'A-Level 82 Eng ภาษาอังกฤษ' },
{ id: 'A-83', name: 'A-Level 83 Fra ฝรั่งเศส' },
{ id: 'A-84', name: 'A-Level 84 Deu เยอรมัน' },
{ id: 'A-85', name: 'A-Level 85 Jpn ญี่ปุ่น' },
{ id: 'A-86', name: 'A-Level 86 Kor เกาหลี' },
{ id: 'A-87', name: 'A-Level 87 Chn จีน' },
{ id: 'A-88', name: 'A-Level 88 Bal บาลี' },
{ id: 'A-89', name: 'A-Level 89 Esp สเปน' }
];
function init() {
// Load Data
const savedData = localStorage.getItem('admission_tracker_data');
if (savedData) {
universities = JSON.parse(savedData);
migrateData(); // Ensure old data format is updated to new format
} else {
universities = JSON.parse(JSON.stringify(defaultUniversities));
}
// Load API Key
geminiApiKey = localStorage.getItem('gemini_api_key') || "";
if (geminiApiKey) {
document.getElementById('apiKeyInput').value = geminiApiKey;
}
// Load GPAX
userGpax = localStorage.getItem('admission_tracker_gpax') || "-.-";
document.getElementById('displayGpax').innerText = userGpax;
document.getElementById('gpaxInput').value = userGpax === "-.-" ? "" : userGpax;
// Load Target Count
const savedTarget = localStorage.getItem('admission_target_count');
targetUniCount = savedTarget ? parseInt(savedTarget) : 5;
document.getElementById('targetCountInput').value = targetUniCount;
renderUniversities();
setTimeout(showWelcomeModal, 800);
}
function migrateData() {
let hasChanges = false;
universities.forEach(uni => {
// If 'rounds' doesn't exist, migrate from flat structure
if (!uni.rounds) {
uni.rounds = {
'1': {
targetDate: uni.targetDate || "",
officialDate: uni.officialDate || "",
status: uni.status || "Not Started",
remark: uni.remark || "",
qualifications: "", conditions: ""
},
'2': { targetDate: "", officialDate: "", status: "Not Started", remark: "", qualifications: "", conditions: "" },
'3': { targetDate: "", officialDate: "", status: "Not Started", remark: "", qualifications: "", scoreCalc: "" },
'4': { targetDate: "", officialDate: "", status: "Not Started", remark: "" }
};
delete uni.targetDate; delete uni.officialDate; delete uni.status; delete uni.remark; delete uni.activeRound;
hasChanges = true;
} else {
// Ensure new fields exist if migrating from previous version
if (uni.rounds['1'] && !uni.rounds['1'].qualifications) { uni.rounds['1'].qualifications = ""; uni.rounds['1'].conditions = ""; hasChanges = true; }
if (uni.rounds['2'] && !uni.rounds['2'].qualifications) { uni.rounds['2'].qualifications = ""; uni.rounds['2'].conditions = ""; hasChanges = true; }
if (uni.rounds['3'] && !uni.rounds['3'].qualifications) { uni.rounds['3'].qualifications = ""; uni.rounds['3'].scoreCalc = ""; hasChanges = true; }
// Update check
if (uni.rounds['1'] && !uni.rounds['1'].schedule) { uni.rounds['1'].schedule = []; hasChanges = true; }
if (uni.rounds['2'] && !uni.rounds['2'].schedule) { uni.rounds['2'].schedule = []; hasChanges = true; }
if (uni.rounds['3'] && !uni.rounds['3'].schedule) { uni.rounds['3'].schedule = []; hasChanges = true; }
if (uni.rounds['4'] && !uni.rounds['4'].schedule) { uni.rounds['4'].schedule = []; hasChanges = true; }
}
});
if (hasChanges) saveToLocal();
}
function saveToLocal() {
localStorage.setItem('admission_tracker_data', JSON.stringify(universities));
renderUniversities();
}
// --- SETTINGS & DATA MANAGEMENT ---
function openSettings() { document.getElementById('settingsModal').classList.remove('hidden'); }
function closeSettings() { document.getElementById('settingsModal').classList.add('hidden'); }
function saveSettings() {
// Save API Key
const key = document.getElementById('apiKeyInput').value.trim();
localStorage.setItem('gemini_api_key', key);
geminiApiKey = key;
// Save GPAX
const gpax = document.getElementById('gpaxInput').value.trim();
userGpax = gpax || "-.-";
localStorage.setItem('admission_tracker_gpax', userGpax);
document.getElementById('displayGpax').innerText = userGpax;
// Save Target Count
const targetVal = document.getElementById('targetCountInput').value;
targetUniCount = targetVal ? parseInt(targetVal) : 5;
localStorage.setItem('admission_target_count', targetUniCount);
renderUniversities();
Swal.fire('Success', 'บันทึกการตั้งค่าเรียบร้อย!', 'success');
}
function exportData() {
// Bundle data + API Key + GPAX + Target
const exportObj = {
universities: universities,
apiKey: geminiApiKey || "",
gpax: userGpax,
targetCount: targetUniCount
};
const dataStr = JSON.stringify(exportObj, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `admission_backup_${new Date().toISOString().slice(0, 10)}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
Swal.fire('Downloaded', 'ดาวน์โหลดไฟล์ Backup (รวมการตั้งค่าทั้งหมด) เรียบร้อย', 'success');
}
function importData(input) {
const file = input.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (e) {
try {
const data = JSON.parse(e.target.result);
// Support old format (array only) and new format (object with apiKey)
if (Array.isArray(data)) {
// Old format: just universities
universities = data;
saveToLocal();
Swal.fire('Success', 'กู้คืนข้อมูลมหาวิทยาลัยเรียบร้อย (ไม่พบ API Key ในไฟล์)', 'success');
} else if (data.universities && Array.isArray(data.universities)) {
// New format: universities + apiKey + gpax + targetCount
universities = data.universities;
saveToLocal();
// Restore API Key
if (data.apiKey) {
localStorage.setItem('gemini_api_key', data.apiKey);
geminiApiKey = data.apiKey;
document.getElementById('apiKeyInput').value = geminiApiKey;
}
// Restore GPAX
if (data.gpax) {
localStorage.setItem('admission_tracker_gpax', data.gpax);
userGpax = data.gpax;
document.getElementById('displayGpax').innerText = userGpax;
document.getElementById('gpaxInput').value = userGpax === "-.-" ? "" : userGpax;
}
// Restore Target Count
if (data.targetCount) {
localStorage.setItem('admission_target_count', data.targetCount);
targetUniCount = data.targetCount;
document.getElementById('targetCountInput').value = targetUniCount;
}
Swal.fire('Success', 'กู้คืนข้อมูลครบถ้วน!', 'success');
} else {
throw new Error('Invalid format');
}
closeSettings();
} catch (err) {
console.error(err);
Swal.fire('Error', 'ไฟล์ไม่ถูกต้อง', 'error');
}
};
reader.readAsText(file);
input.value = ''; // Reset input
}
function resetData() {
Swal.fire({
title: 'ล้างข้อมูล?',
text: "ข้อมูลทั้งหมดจะหายไปและกู้คืนไม่ได้!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
confirmButtonText: 'ใช่, ล้างข้อมูล'
}).then((result) => {
if (result.isConfirmed) {
localStorage.removeItem('admission_tracker_data');
localStorage.removeItem('gemini_api_key');
location.reload();
}
})
}
function getDaysLeft(dateStr) {
if (!dateStr) return null;
const target = new Date(dateStr);
const today = new Date();
today.setHours(0, 0, 0, 0);
target.setHours(0, 0, 0, 0);
return Math.ceil((target - today) / (1000 * 60 * 60 * 24));
}
function formatDate(dateStr) {
if (!dateStr) return "-";
return new Date(dateStr).toLocaleDateString('th-TH', { day: 'numeric', month: 'short', year: '2-digit' });
}
function setGlobalRound(round) {
currentGlobalRound = round;
renderUniversities();
}
function renderUniversities() {
const list = document.getElementById('universityList');
const countBadge = document.getElementById('uniCountBadge');
list.innerHTML = '';
// --- Global Round Tabs ---
const roundColors = {
'1': 'bg-yellow-400 border-yellow-500 text-yellow-900', // Portfolio
'2': 'bg-orange-400 border-orange-500 text-white', // Quota
'3': 'bg-teal-500 border-teal-600 text-white', // Admission
'4': 'bg-blue-600 border-blue-700 text-white' // Direct
};
const inactiveClass = 'bg-gray-100 text-gray-400 border-gray-200 hover:bg-gray-200';
let tabsHtml = `<div class="flex rounded-lg overflow-hidden border border-gray-200 mb-6 shadow-sm">`;
const rounds = [
{ id: '1', name: 'รอบ 1 Portfolio', icon: 'fa-folder-open' },
{ id: '2', name: 'รอบ 2 Quota', icon: 'fa-user-friends' },
{ id: '3', name: 'รอบ 3 Admission', icon: 'fa-graduation-cap' },
{ id: '4', name: 'รอบ 4 Direct', icon: 'fa-door-open' },
];
rounds.forEach(r => {
const isActive = currentGlobalRound === r.id;
const activeStyle = roundColors[r.id];
const style = isActive ? `${activeStyle} font-bold shadow-inner` : inactiveClass;
tabsHtml += `
<button onclick="setGlobalRound('${r.id}')" class="flex-1 py-3 text-sm transition ${style} relative">
${isActive ? '<span class="absolute top-1 right-2 text-[10px] opacity-50"><i class="fas fa-check-circle"></i></span>' : ''}
<i class="fas ${r.icon} mr-1"></i> ${r.name}
</button>
`;
});
tabsHtml += `</div>`;
// list.insertAdjacentHTML('beforeend', tabsHtml); // Remove tabs from inside the list container if they are meant to be outside or handle differently.
// Wait, previously tabs were INSIDE the list. If I want them above the list but list is now space-y-4, that's fine.
// But the USER wants "เรียงลงเหมือนของเดิม" (Vertical).
// If I inject tabs inside 'universityList', they become the first item in the stack. Correct.
list.insertAdjacentHTML('beforeend', tabsHtml);
// -------------------------
const filledCount = universities.length;
// document.getElementById('headerTargetCount').innerText = targetUniCount; // This ID might not exist anymore due to recent changes
if (countBadge) {
countBadge.innerText = `${filledCount}/${targetUniCount}`;
countBadge.className = filledCount >= targetUniCount ? "bg-green-500 text-white text-xs font-bold px-3 py-1.5 rounded-full shadow-sm ml-1 flex items-center" : "bg-white text-blue-700 text-xs font-bold px-3 py-1.5 rounded-full shadow-sm border border-blue-100 ml-1 flex items-center";
}
universities.forEach((uni, index) => {
const roundData = uni.rounds[currentGlobalRound] || {};
// Target Date Logic
const daysLeft = getDaysLeft(roundData.targetDate);
let daysText = "", daysClass = "";
if (daysLeft === null) { daysText = "ไม่ระบุวัน"; daysClass = "text-gray-400"; }
else if (daysLeft < 0) { daysText = `เลยมาแล้ว ${Math.abs(daysLeft)} วัน`; daysClass = "text-red-600 font-bold"; }
else if (daysLeft === 0) { daysText = "ส่งวันนี้!"; daysClass = "text-red-600 font-bold animate-pulse"; }
else { daysText = `เหลืออีก ${daysLeft} วัน`; daysClass = daysLeft <= 5 ? "text-red-500 font-bold" : "text-green-600 font-bold"; }
// Official Deadline Logic
const offDaysLeft = getDaysLeft(roundData.officialDate);
let offDaysText = "", offDaysClass = "";
if (offDaysLeft === null) { offDaysText = "ยังมึนๆ (ไม่ระบุ)"; offDaysClass = "text-red-300"; }
else if (offDaysLeft < 0) { offDaysText = `ปิดรับแล้ว (${Math.abs(offDaysLeft)} วันที่แล้ว)`; offDaysClass = "text-gray-400 font-bold"; }
else if (offDaysLeft === 0) { offDaysText = "วันสุดท้าย!"; offDaysClass = "text-red-700 font-extrabold animate-pulse"; }
else { offDaysText = `เหลืออีก ${offDaysLeft} วัน`; offDaysClass = offDaysLeft <= 7 ? "text-red-600 font-bold" : "text-red-400 font-medium"; }
const isStarted = roundData.status === "In Progress" || roundData.status === "Done";
const borderClass = isStarted ? "border-l-4 border-yellow-400" : "border border-gray-200 opacity-90";
// Score Calculation Summary (Round 3)
let scoreSummaryHtml = '';
if (currentGlobalRound === '3' && roundData.scoreDetails && roundData.scoreDetails.length > 0) {
let totalScore = 0;
let subjectsHtml = '';
roundData.scoreDetails.forEach(item => {
const weight = parseFloat(item.weight) || 0;
const score = parseFloat(item.score) || 0;
const calcScore = (weight * score) / 100;
totalScore += calcScore;
subjectsHtml += `
<div class="mb-1.5">
<div class="flex justify-between text-[10px] text-gray-600 mb-0.5">
<span class="font-semibold">${item.subject}</span>
<span class="font-bold text-teal-600">${weight}%</span>
</div>
<div class="w-full bg-gray-100 rounded-full h-1.5 overflow-hidden">
<div class="bg-teal-400 h-1.5 rounded-full" style="width: ${Math.min(weight, 100)}%"></div>
</div>
</div>
`;
});
scoreSummaryHtml = `
<div class="mt-3 bg-gray-50/50 border border-gray-100 rounded-lg p-3">
<div class="text-[10px] font-bold text-gray-400 mb-2 uppercase tracking-wider">เกณฑ์คะแนน (Weights)</div>
${subjectsHtml}
<div class="mt-2 pt-2 border-t border-gray-200 flex justify-between items-center text-teal-800">
<span class="text-xs font-bold"><i class="fas fa-calculator mr-1"></i>คะแนนที่ทำได้:</span>
<span class="font-extrabold text-sm ml-2 bg-teal-100 px-2 py-0.5 rounded text-teal-700">${totalScore.toFixed(2)}</span>
</div>
</div>`;
}
const html = `
<div class="bg-white p-4 rounded-xl shadow-sm ${borderClass} relative group hover:shadow-md transition">
<div class="flex justify-between items-start gap-4">
<div class="flex-1 min-w-0">
<div class="flex flex-wrap items-center gap-x-2 gap-y-1">
<h3 class="font-bold text-lg text-gray-800 break-words">${index + 1}. ${uni.name}</h3>
<span class="text-[10px] px-2 py-0.5 rounded-full whitespace-nowrap ${getStatusColor(roundData.status)}">${roundData.status}</span>
</div>
<p class="text-sm text-gray-600 mb-2 truncate">${uni.faculty || "ยังไม่ระบุคณะ"}</p>
<!-- Detailed Info Preview -->
${roundData.qualifications ? `<div class="text-xs text-gray-500 mt-2 bg-gray-50 p-2 rounded border border-gray-100"><strong class="text-gray-700">คุณสมบัติ:</strong> ${roundData.qualifications}</div>` : ''}
${scoreSummaryHtml}
<!-- Schedule Preview (Next Event) -->
${getSchedulePreview(roundData.schedule)}
${roundData.remark ? `<p class="text-xs text-gray-400 italic mt-2"><i class="fas fa-comment-alt mr-1"></i>${roundData.remark}</p>` : ''}
<!-- Financial (Shared) -->
<div class="flex flex-wrap gap-2 text-[10px] mt-2 border-t pt-2 border-gray-100">
${uni.appFee ? `<span class="bg-blue-50 text-blue-700 px-2 py-1 rounded border border-blue-100"><i class="fas fa-tag mr-1"></i>ค่าสมัคร: ${parseInt(uni.appFee).toLocaleString()}</span>` : ''}
${uni.tuitionFee ? `<span class="bg-orange-50 text-orange-700 px-2 py-1 rounded border border-orange-100"><i class="fas fa-university mr-1"></i>ค่าเทอม: ${parseInt(uni.tuitionFee).toLocaleString()}</span>` : ''}
</div>
</div>
<button onclick="openEditModal(${index})" class="flex-shrink-0 text-gray-400 hover:text-blue-600 transition p-2 bg-gray-50 rounded-lg hover:bg-blue-50"><i class="fas fa-edit"></i></button>
</div>
<div class="flex gap-3 mt-3">
<div class="flex-1 bg-gradient-to-br from-blue-50 to-blue-100/50 p-2 rounded-lg border border-blue-100 text-center cursor-pointer hover:border-blue-300 transition" onclick="openEditModal(${index})">
<p class="text-[10px] uppercase text-blue-500 font-bold tracking-wide">เป้าหมายน้อง</p>
<p class="text-lg font-bold text-blue-700 leading-tight mt-1">${formatDate(roundData.targetDate)}</p>
<p class="text-[10px] mt-1 ${daysClass}">${daysText}</p>
</div>
<div class="flex-1 bg-gradient-to-br from-red-50 to-red-100/50 p-2 rounded-lg border border-red-100 text-center cursor-pointer hover:border-red-300 transition group/official" onclick="openEditModal(${index})">
<p class="text-[10px] uppercase text-red-500 font-bold tracking-wide group-hover/official:text-red-700">Official Deadline</p>
<p class="text-lg font-bold text-red-700 leading-tight mt-1">${formatDate(roundData.officialDate)}</p>
<p class="text-[10px] mt-1 ${offDaysClass}">${offDaysText}</p>
</div>
</div>
</div>`;
list.insertAdjacentHTML('beforeend', html);
});
for (let i = universities.length; i < targetUniCount; i++) {
const html = `
<div onclick="openAddModal()" class="dashed-box p-4 rounded-xl flex flex-col items-center justify-center text-center h-32 cursor-pointer group">
<div class="bg-white p-3 rounded-full shadow-sm mb-2 group-hover:scale-110 transition group-hover:bg-blue-50"><i class="fas fa-plus text-gray-400 text-xl group-hover:text-blue-500"></i></div>
<h4 class="text-gray-500 font-bold text-sm group-hover:text-blue-600">เพิ่มมหาลัยลำดับที่ ${i + 1}</h4>
<p class="text-xs text-red-400 font-light">ยังว่าง! (ต้องหาแผนสำรอง)</p>
</div>`;
list.insertAdjacentHTML('beforeend', html);
}
}
function getStatusColor(status) {
if (status === 'In Progress') return 'bg-yellow-100 text-yellow-800 border border-yellow-200';
if (status === 'Done') return 'bg-green-100 text-green-800 border border-green-200';
return 'bg-gray-200 text-gray-600';
}
// --- SCHEDULE & CALENDAR LOGIC ---
function getSchedulePreview(schedule) {
if (!schedule || schedule.length === 0) return '';
// Find next upcoming event
const today = new Date().toISOString().split('T')[0];
const upcoming = schedule
.filter(s => s.dateStart >= today)
.sort((a, b) => a.dateStart.localeCompare(b.dateStart))[0];
if (!upcoming) return '';
return `
<div class="mt-2 flex items-center gap-2 text-xs bg-indigo-50 text-indigo-800 p-2 rounded border border-indigo-100">
<i class="fas fa-calendar-alt"></i>
<span class="font-bold truncate">${upcoming.type}:</span>
<span>${formatDate(upcoming.dateStart)}</span>
</div>`;
}
window.toggleCalendarView = function () {
const list = document.getElementById('universityList');
const cal = document.getElementById('calendarViewContainer');
const btn = document.getElementById('toggleCalBtn');
if (cal.classList.contains('hidden')) {
list.classList.add('hidden');
cal.classList.remove('hidden');
btn.innerHTML = '<i class="fas fa-list mr-1"></i> มุมมองรายการ';
btn.classList.replace('bg-indigo-100', 'bg-blue-100');
btn.classList.replace('text-indigo-700', 'text-blue-700');
renderCalendar();
} else {
list.classList.remove('hidden');
cal.classList.add('hidden');
btn.innerHTML = '<i class="fas fa-calendar-alt mr-1"></i> ปฏิทิน';
btn.classList.replace('bg-blue-100', 'bg-indigo-100');
btn.classList.replace('text-blue-700', 'text-indigo-700');
}
}
function renderCalendar() {
const container = document.getElementById('calendarViewContent');
if (!container) return;
container.innerHTML = '';
// Gather all events
let events = [];
universities.forEach(uni => {
const rData = uni.rounds[currentGlobalRound];
if (rData && rData.schedule) {
rData.schedule.forEach(ev => {
events.push({
uniName: uni.name,
faculty: uni.faculty,
...ev
});
});
}
// Add Target & Official if exists (convert to generic event)
if (rData && rData.targetDate) events.push({ uniName: uni.name, faculty: uni.faculty, type: 'Target', dateStart: rData.targetDate, note: 'เป้าหมายส่วนตัว' });
if (rData && rData.officialDate) events.push({ uniName: uni.name, faculty: uni.faculty, type: 'Official Deadline', dateStart: rData.officialDate, note: 'วันปิดรับสมัคร' });
});
// Sort
events.sort((a, b) => a.dateStart.localeCompare(b.dateStart));
// Group by Month
let lastMonth = '';
events.forEach(ev => {
const date = new Date(ev.dateStart);
const monthStr = date.toLocaleDateString('th-TH', { month: 'long', year: 'numeric' });
if (monthStr !== lastMonth) {
container.insertAdjacentHTML('beforeend', `<div class="sticky top-0 bg-white/95 backdrop-blur py-2 px-4 shadow-sm z-10 font-bold text-gray-700 border-b border-gray-100 mt-4 text-lg">${monthStr}</div>`);
lastMonth = monthStr;
}
let colorClass = "bg-gray-50 border-gray-200";
if (ev.type.includes("รับสมัคร") || ev.type.includes("Application")) colorClass = "bg-green-50 border-green-200 text-green-800";
if (ev.type.includes("สอบ") || ev.type.includes("Interview")) colorClass = "bg-yellow-50 border-yellow-200 text-yellow-800";
if (ev.type.includes("ประกาศ") || ev.type.includes("Announcement")) colorClass = "bg-blue-50 border-blue-200 text-blue-800";
if (ev.type.includes("ยืนยัน") || ev.type.includes("Confirm")) colorClass = "bg-teal-50 border-teal-200 text-teal-800";
if (ev.type === "Official Deadline") colorClass = "bg-red-50 border-red-200 text-red-800";
const html = `
<div class="flex gap-4 p-3 mx-4 my-2 rounded-lg border ${colorClass} items-start">
<div class="text-center w-16 flex-shrink-0">
<div class="text-2xl font-bold leading-none">${date.getDate()}</div>
<div class="text-[10px] uppercase opacity-70">${date.toLocaleDateString('en-US', { weekday: 'short' })}</div>
</div>
<div class="flex-1">
<div class="flex justify-between items-start">
<h4 class="font-bold text-sm">${ev.type}</h4>
${ev.dateEnd ? `<span class="text-[10px] bg-white/50 px-1.5 rounded border border-black/5">ถึง ${formatDate(ev.dateEnd)}</span>` : ''}
</div>
<p class="text-sm font-medium mt-0.5 line-clamp-1">${ev.uniName} <span class="font-normal opacity-80">- ${ev.faculty}</span></p>
${ev.note ? `<p class="text-xs opacity-70 mt-1"><i class="fas fa-info-circle mr-1"></i>${ev.note}</p>` : ''}
</div>
</div>`;
container.insertAdjacentHTML('beforeend', html);
});
if (events.length === 0) {
container.innerHTML = `<div class="text-center py-10 text-gray-400">ยังไม่มีกำหนดการในรอบนี้</div>`;
}
}
window.addScheduleRow = function () {
const type = document.getElementById('new-sched-type').value;
const start = document.getElementById('new-sched-start').value;
const end = document.getElementById('new-sched-end').value;
const note = document.getElementById('new-sched-note').value;
if (!start) return;
const container = document.getElementById('schedule-rows-container');
const rowHtml = `
<div class="sched-row flex gap-2 mb-2 items-center bg-white p-2 border border-gray-100 rounded shadow-sm">
<div class="w-24 flex-shrink-0">
<input type="text" class="sched-input-type w-full p-1 text-xs border rounded bg-gray-50 font-bold text-indigo-700" value="${type}" readonly>
</div>
<div class="flex-1 flex gap-1 items-center">
<input type="date" class="sched-input-start p-1 text-[10px] border rounded text-center w-20" value="${start}" readonly>
${end ? `<span class="text-gray-400">-</span><input type="date" class="sched-input-end p-1 text-[10px] border rounded text-center w-20" value="${end}" readonly>` : '<input type="hidden" class="sched-input-end" value="">'}
</div>
<input type="hidden" class="sched-input-note" value="${note}">
<button type="button" onclick="removeSchedRow(this)" class="text-red-400 hover:text-red-600 w-6"><i class="fas fa-times"></i></button>
</div>`;
container.insertAdjacentHTML('beforeend', rowHtml);
// clear
document.getElementById('new-sched-start').value = '';
document.getElementById('new-sched-end').value = '';
document.getElementById('new-sched-note').value = '';
}
window.removeSchedRow = function (btn) { btn.closest('.sched-row').remove(); }
// --- EDIT MODAL WITH TABS ---
window.switchEditTab = function (round) {
// Update Tab Buttons
document.querySelectorAll('.edit-tab-btn').forEach(btn => {
let activeColor = "";
if (round === '1') activeColor = "bg-yellow-100 text-yellow-800 border-yellow-300";
if (round === '2') activeColor = "bg-orange-100 text-orange-800 border-orange-300";
if (round === '3') activeColor = "bg-teal-100 text-teal-800 border-teal-300";
if (round === '4') activeColor = "bg-blue-100 text-blue-800 border-blue-300";
if (btn.dataset.round === round) {
btn.className = `edit-tab-btn flex-1 py-2 px-3 rounded-lg text-xs font-bold border transition whitespace-nowrap shadow-sm ${activeColor}`;
} else {
btn.className = `edit-tab-btn flex-1 py-2 px-3 rounded-lg text-xs font-bold border border-transparent text-gray-400 hover:text-gray-600 hover:bg-gray-50 transition whitespace-nowrap`;
}
});
// Update Content
document.querySelectorAll('.edit-tab-content').forEach(content => {
if (content.id === `edit-content-${round}`) {
content.classList.remove('hidden');
} else {
content.classList.add('hidden');
}
});
}
// --- SCORE CALCULATOR HELPERS ---
window.addScoreRow = function () {
const subjectId = document.getElementById('new-score-subject').value;
const subjectName = document.getElementById('new-score-subject').options[document.getElementById('new-score-subject').selectedIndex].text;
const weight = document.getElementById('new-score-weight').value;
const score = document.getElementById('new-score-val').value;
if (!subjectId) return;
const container = document.getElementById('score-rows-container');
const rowHtml = `
<div class="score-row flex gap-2 mb-2 items-center bg-white p-2 border border-gray-100 rounded shadow-sm">
<input type="hidden" class="score-input-id" value="${subjectId}">
<div class="flex-1 text-xs text-gray-700 truncate font-semibold" title="${subjectName}">
<span class="bg-gray-100 text-gray-500 text-[9px] px-1 py-0.5 rounded mr-1">${subjectId}</span>
${subjectName.replace(subjectId, '')}
</div>
<div class="w-16 relative">
<span class="absolute right-6 top-1.5 text-[9px] text-gray-400">%</span>
<input type="number" class="score-input-weight w-full p-1 border rounded text-xs text-center outline-none focus:border-teal-400" value="${weight}" onchange="updateScoreTotal()" placeholder="0">
</div>
<div class="w-16">
<input type="number" class="score-input-val w-full p-1 border rounded text-xs text-center outline-none focus:border-teal-400" value="${score}" onchange="updateScoreTotal()" placeholder="0">
</div>
<button type="button" onclick="removeScoreRow(this)" class="text-red-400 hover:text-red-600 w-6"><i class="fas fa-times"></i></button>
</div>
`;
container.insertAdjacentHTML('beforeend', rowHtml);
// Reset inputs
document.getElementById('new-score-weight').value = '';
document.getElementById('new-score-val').value = '';
document.getElementById('new-score-subject').selectedIndex = 0;
updateScoreTotal();
}
window.removeScoreRow = function (btn) {
btn.closest('.score-row').remove();
updateScoreTotal();
}
window.updateScoreTotal = function () {
let total = 0;
document.querySelectorAll('.score-row').forEach(row => {
const w = parseFloat(row.querySelector('.score-input-weight').value) || 0;
const s = parseFloat(row.querySelector('.score-input-val').value) || 0;
total += (w * s) / 100;
});
const display = document.getElementById('score-total-display');
if (display) display.innerText = total.toFixed(2);
}
async function openEditModal(index) {
const uni = universities[index];
const activeRound = currentGlobalRound;
const { value: formValues } = await Swal.fire({
title: `<span class="text-2xl font-bold text-gray-700">✏️ แก้ไขข้อมูลมหาลัย</span>`,
html: generateModalHtml(uni),
width: '700px',
showCancelButton: true,
confirmButtonText: '<i class="fas fa-save mr-1"></i> บันทึก',
confirmButtonColor: '#2563EB',
cancelButtonText: '<i class="fas fa-trash-alt mr-1"></i> ลบมหาลัยนี้',
cancelButtonColor: '#EF4444',
focusConfirm: false,
customClass: { popup: 'rounded-2xl', container: 'font-sarabun' },
didOpen: () => {
// Activate the current round tab by default
window.switchEditTab(activeRound);
},
preConfirm: () => getModalValues()
});
if (formValues) {
universities[index] = { ...universities[index], ...formValues };
saveToLocal();
} else if (Swal.getDismissReason() === Swal.DismissReason.cancel) {
if (confirm('ยืนยันลบมหาลัยนี้?')) { universities.splice(index, 1); saveToLocal(); }
}
}
async function openAddModal() {
// Default empty structure