File size: 88,399 Bytes
4bea261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
---
import AdminLayout from '../../../layouts/AdminLayout.astro';
import { getServers, getLocalMovies } from '../../../lib/localDb.js';

const localMovies = await getLocalMovies();
const servers = await getServers();

const movieData = {
  movie: {
    name: '',
    origin_name: '',
    slug: '',
    type: 'series',
    status: 'ongoing',
    year: new Date().getFullYear(),
    quality: 'FHD',
    lang: 'Vietsub',
    poster_url: '',
    thumb_url: '',
    category: '',
    country: '',
    director: '',
    actor: '',
    content: '',
    isLocal: true
  },
  episodes: []
};

const isEditMode = false;
const categoryValue = '';
const countryValue = '';
const directorValue = '';
const actorValue = '';
---

<AdminLayout title="Thêm phim mới">
  <div class="mb-10 flex flex-col gap-4 md:flex-row md:items-center md:justify-between border-b border-white/5 pb-8">
     <div>
        <div class="flex items-center gap-2 text-xs text-gray-500 mb-2">
           <a href="/admin/phim" class="hover:text-primary transition-colors">Quản lý phim</a>
           <i class="fas fa-chevron-right text-[8px]"></i>
           <span class="text-white">Thêm phim mới</span>
        </div>
        <h1 class="text-3xl font-black tracking-tighter text-white">Thêm phim mới</h1>
     </div>
     <div class="flex gap-4">
        <button id="save-movie-btn" class="flex items-center gap-2 rounded-2xl bg-primary px-6 py-4 text-xs font-black uppercase tracking-widest text-dark hover:scale-105 transition-all shadow-[0_0_20px_var(--primary)] active:scale-95">
           <i class="fas fa-save"></i>
           Lưu phim & Tập
        </button>
     </div>
  </div>

  <div class="grid grid-cols-1 gap-10 lg:grid-cols-3">
     <!-- Cột Trái: Nhập nhanh + Thông tin chung + Tập phim (70%) -->
     <div class="lg:col-span-2 space-y-10">
        <!-- NHẬP NHANH DỮ LIỆU TỰ ĐỘNG -->
        <div class="glass rounded-[40px] p-8 md:p-10 border border-white/5 space-y-6 relative overflow-hidden group">
           <div class="absolute -inset-px bg-gradient-to-r from-primary/10 to-blue-500/10 rounded-[40px] opacity-30 blur-lg group-hover:opacity-50 transition-opacity"></div>
           <div class="relative z-10 space-y-4">
              <h2 class="text-lg font-black uppercase tracking-wider text-white flex items-center gap-2">
                 <i class="fas fa-magic text-primary"></i> Nhập nhanh dữ liệu phim
              </h2>
              <p class="text-xs text-gray-400">Dán đường dẫn chi tiết phim từ <strong>KKPhim/OPhim</strong> hoặc link <strong>Youtube</strong> để hệ thống tự động tải và điền toàn bộ thông tin phim + danh sách tập phim.</p>
              
              <div class="flex flex-col gap-4 sm:flex-row">
                 <div class="relative flex-1">
                    <input 
                       type="text" 
                       id="quick-url-input" 
                       placeholder="Dán link phim (ví dụ: https://kkphim.vip/phim/tay-du-ky) hoặc link Youtube..." 
                       class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all pl-12"
                    />
                    <i class="fas fa-link absolute left-5 top-1/2 -translate-y-1/2 text-gray-500"></i>
                 </div>
                 <button 
                    id="btn-quick-import" 
                    class="flex items-center justify-center gap-2 rounded-2xl bg-primary px-8 py-4 text-xs font-black uppercase tracking-widest text-dark hover:scale-105 active:scale-95 transition-all shadow-[0_0_20px_var(--primary)] cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed disabled:scale-100"
                    data-txatooltip="Nhấn để tự động tải thông tin phim"
                 >
                    <i class="fas fa-cloud-download-alt"></i> Lấy dữ liệu
                 </button>
              </div>
           </div>
        </div>

        <!-- 1. Thông tin chung -->
        <div class="glass rounded-[40px] p-8 md:p-10 border border-white/5 space-y-6">
           <h2 class="text-lg font-black uppercase tracking-wider text-white border-b border-white/5 pb-4">Thông tin cơ bản</h2>
           
           <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Tên phim</label>
                 <input type="text" id="mv-name" value={movieData.movie.name} placeholder="Ví dụ: TPHIMX VIP" class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
              </div>
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Tên gốc (Tiếng Anh/Gốc)</label>
                 <input type="text" id="mv-origin-name" value={movieData.movie.origin_name} placeholder="Ví dụ: TPHIMX Premium" class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
              </div>
           </div>

           <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Đường dẫn tĩnh (Slug)</label>
                 <input type="text" id="mv-slug" value={movieData.movie.slug} placeholder="vi-du-tphimx-vip" class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all read-only:opacity-50" />
              </div>
              <div class="grid grid-cols-2 gap-4">
                 <div>
                    <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Loại phim</label>
                    <select id="mv-type" class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all">
                       <option value="series" selected={movieData.movie.type === 'series'}>Phim Bộ</option>
                       <option value="single" selected={movieData.movie.type === 'single'}>Phim Lẻ</option>
                       <option value="hoathinh" selected={movieData.movie.type === 'hoathinh'}>Hoạt Hình</option>
                       <option value="tvshows" selected={movieData.movie.type === 'tvshows'}>TV Shows</option>
                    </select>
                 </div>
                 <div>
                    <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Trạng thái</label>
                    <select id="mv-status" class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all">
                       <option value="ongoing" selected={movieData.movie.status === 'ongoing'}>Đang chiếu</option>
                       <option value="completed" selected={movieData.movie.status === 'completed'}>Hoàn thành</option>
                        <option value="trailer" selected={movieData.movie.status === 'trailer'}>Sắp chiếu</option>
                    </select>
                 </div>
              </div>
           </div>

           <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Poster đứng (URL)</label>
                 <input type="text" id="mv-poster" value={movieData.movie.poster_url} placeholder="Nhập liên kết ảnh đứng..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
              </div>
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Thumb ngang (URL)</label>
                                   <input type="text" id="mv-thumb" value={movieData.movie.thumb_url} placeholder="Nhập liên kết ảnh ngang..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
               </div>
            </div>

            <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
               <div>
                  <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Trailer URL (Youtube hoặc liên kết khác)</label>
                  <input type="text" id="mv-trailer" value="" placeholder="Ví dụ: https://www.youtube.com/watch?v=..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
               </div>
               <div class="flex flex-col gap-4 pt-6 pl-2">
                  <label class="relative inline-flex items-center cursor-pointer select-none">
                     <input type="checkbox" id="mv-only-login" class="sr-only peer" />
                     <div class="w-11 h-6 bg-white/10 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                     <span class="ml-3 text-xs font-black uppercase tracking-widest text-gray-300">Yêu cầu Đăng nhập để xem</span>
                  </label>
                  <label class="relative inline-flex items-center cursor-pointer select-none">
                     <input type="checkbox" id="mv-is-slider" class="sr-only peer" />
                     <div class="w-11 h-6 bg-white/10 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                     <span class="ml-3 text-xs font-black uppercase tracking-widest text-gray-300">Ghim lên Slider trang chủ</span>
                  </label>
               </div>
            </div>

           <div class="grid grid-cols-1 gap-6 sm:grid-cols-3">
              <div class="relative">
                  <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Thể loại (Ngăn cách dấu phẩy)</label>
                  <input type="text" id="mv-category" value={categoryValue} placeholder="Hành Động, Cổ Trang..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" autocomplete="off" />
                  <!-- Custom Glassmorphic Category Dropdown -->
                  <div id="category-dropdown" class="hidden absolute left-0 right-0 mt-2 z-50 max-h-60 overflow-y-auto rounded-2xl border border-white/10 bg-[#1a1c24]/95 backdrop-blur-xl p-4 shadow-2xl space-y-3">
                     <span class="text-[9px] font-black uppercase tracking-widest text-gray-500 block border-b border-white/5 pb-2">Chọn nhanh thể loại có sẵn (hoặc tự gõ thêm)</span>
                     <div class="grid grid-cols-2 gap-2 sm:grid-cols-3" id="category-options-grid">
                        <!-- Options generated dynamically -->
                     </div>
                  </div>
               </div>
               <div class="relative">
                  <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Quốc gia</label>
                  <input type="text" id="mv-country" value={countryValue} placeholder="Trung Quốc, Mỹ..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" autocomplete="off" />
                  <!-- Custom Glassmorphic Country Dropdown -->
                  <div id="country-dropdown" class="hidden absolute left-0 right-0 mt-2 z-50 max-h-60 overflow-y-auto rounded-2xl border border-white/10 bg-[#1a1c24]/95 backdrop-blur-xl p-4 shadow-2xl space-y-3">
                     <span class="text-[9px] font-black uppercase tracking-widest text-gray-500 block border-b border-white/5 pb-2">Chọn quốc gia có sẵn (hoặc tự gõ thêm)</span>
                     <div class="grid grid-cols-2 gap-2" id="country-options-grid">
                        <!-- Options generated dynamically -->
                     </div>
                  </div>
               </div>
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Năm phát hành</label>
                 <input type="number" id="mv-year" value={movieData.movie.year} class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
              </div>
           </div>

           <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Đạo diễn</label>
                 <input type="text" id="mv-director" value={directorValue} placeholder="Tên các đạo diễn..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
              </div>
              <div>
                 <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Diễn viên</label>
                 <input type="text" id="mv-actor" value={actorValue} placeholder="Tên các diễn viên..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
              </div>
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Tóm tắt nội dung</label>
              <textarea id="mv-content" rows="5" placeholder="Nhập tóm tắt giới thiệu nội dung phim..." class="w-full bg-[#12141d] border border-white/5 rounded-2xl px-5 py-4 text-sm text-white focus:outline-none focus:border-primary/50 transition-all resize-none">{movieData.movie.content}</textarea>
           </div>
        </div>

        <!-- 2. Quản lý các Server & Tập Phim -->
        <div class="glass rounded-[40px] p-8 md:p-10 border border-white/5 space-y-6">
           <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between border-b border-white/5 pb-4">
              <h2 class="text-lg font-black uppercase tracking-wider text-white">Danh sách Server & Tập phim</h2>
              <div class="flex flex-wrap gap-2">
                 <button id="add-server-btn" class="flex items-center gap-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/5 px-4 py-2.5 text-xs font-black uppercase tracking-widest text-white transition-all active:scale-95 cursor-pointer">
                    <i class="fas fa-server"></i> Thêm Server mới
                 </button>
              </div>
           </div>

           <!-- Server Container -->
           <div id="servers-wrapper" class="space-y-10">
              <!-- Các server sẽ được render động bằng Javascript tại đây -->
           </div>
        </div>
     </div>

     <!-- Cột Phải: Trạng thái, Lưu & Bộ đổi giây nhanh (30%) -->
     <div class="space-y-8 lg:sticky lg:top-28">
        <!-- Panel chất lượng & ngôn ngữ -->
        <div class="glass rounded-[32px] p-6 border border-white/5 space-y-5">
           <h3 class="text-sm font-black uppercase tracking-widest text-white border-b border-white/5 pb-3">Phân loại chất lượng</h3>
           
           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Chất lượng hiển thị</label>
              <input type="text" id="mv-quality" value={movieData.movie.quality} placeholder="Ví dụ: FHD, 4K, HD" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3.5 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Ngôn ngữ / Phụ đề</label>
              <input type="text" id="mv-lang" value={movieData.movie.lang} placeholder="Ví dụ: Vietsub, Thuyết Minh" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3.5 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
           </div>
           
           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Tập hiện tại hiển thị</label>
              <input type="text" id="mv-episode-current" value={movieData.movie.episode_current || 'Tập 1'} placeholder="Ví dụ: Tập 12/12, FHD Vietsub" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3.5 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Tổng số tập dự kiến</label>
              <input type="number" id="mv-episode-total" value={movieData.movie.episode_total || ''} placeholder="Ví dụ: 50, 24, 1" min="1" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3.5 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
           </div>
        </div>

        <!-- Đặt lịch chiếu tập tiếp theo -->
        <div class="glass rounded-[32px] p-6 border border-white/5 space-y-5">
           <h3 class="text-sm font-black uppercase tracking-widest text-white border-b border-white/5 pb-3">
              <i class="fas fa-calendar-alt text-primary mr-1"></i> Lịch chiếu tập tiếp
           </h3>

           <!-- Cảnh báo phim hoàn thành -->
           <div id="schedule-completed-warn" class="hidden rounded-xl bg-yellow-500/10 border border-yellow-500/20 p-4 text-xs text-yellow-400 font-bold">
              <i class="fas fa-exclamation-triangle mr-1"></i> Phim đã ở trạng thái <strong>"Hoàn thành"</strong>. Lịch chiếu tập tiếp theo thường không cần thiết cho phim đã hoàn thành.
           </div>

           <p class="text-xs text-gray-500" id="schedule-desc">Đặt ngày giờ phát sóng tập tiếp theo. Thông tin này sẽ hiển thị banner thông báo trên trang chi tiết và xem phim.</p>
           
           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Ngày chiếu</label>
              <input type="date" id="mv-next-ep-date" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Giờ chiếu</label>
              <input type="time" id="mv-next-ep-time" value="20:00" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Tên tập sắp chiếu (tuỳ chọn)</label>
              <input type="text" id="mv-next-ep-name" placeholder="Ví dụ: Tập 13, Tập cuối..." class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary/50 transition-all" />
           </div>

           <!-- Preview countdown -->
           <div id="schedule-preview" class="bg-[#12141d]/85 rounded-2xl p-4 border border-white/5 text-center hidden">
              <span class="text-[9px] font-black uppercase tracking-widest text-gray-500 block">Tập tiếp theo</span>
              <span class="text-sm font-bold text-white block mt-1" id="schedule-ep-label">---</span>
              <div class="flex items-center justify-center gap-3 mt-3">
                 <div class="text-center">
                    <span class="text-2xl font-black text-primary block" id="cd-days">00</span>
                    <span class="text-[8px] font-bold uppercase tracking-widest text-gray-500">Ngày</span>
                 </div>
                 <span class="text-gray-600 text-lg font-bold">:</span>
                 <div class="text-center">
                    <span class="text-2xl font-black text-primary block" id="cd-hours">00</span>
                    <span class="text-[8px] font-bold uppercase tracking-widest text-gray-500">Giờ</span>
                 </div>
                 <span class="text-gray-600 text-lg font-bold">:</span>
                 <div class="text-center">
                    <span class="text-2xl font-black text-primary block" id="cd-mins">00</span>
                    <span class="text-[8px] font-bold uppercase tracking-widest text-gray-500">Phút</span>
                 </div>
                 <span class="text-gray-600 text-lg font-bold">:</span>
                 <div class="text-center">
                    <span class="text-2xl font-black text-primary block" id="cd-secs">00</span>
                    <span class="text-[8px] font-bold uppercase tracking-widest text-gray-500">Giây</span>
                 </div>
              </div>
           </div>

           <button id="clear-schedule-btn" class="w-full flex items-center justify-center gap-2 rounded-xl bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 py-3 text-xs font-black uppercase tracking-widest text-red-400 hover:text-red-300 transition-all active:scale-95 cursor-pointer hidden">
              <i class="fas fa-trash-alt"></i> Xoá lịch chiếu
           </button>
        </div>

        <!-- Máy chuyển đổi giây nhanh Sidebar Widget -->
        <div class="glass rounded-[32px] p-6 border border-white/5 space-y-4">
           <h3 class="text-sm font-black uppercase tracking-widest text-white border-b border-white/5 pb-3">
              <i class="fas fa-calculator text-primary mr-1"></i> Máy đổi giây nhanh
           </h3>
           <p class="text-xs text-gray-500">Nhập giờ, phút, giây để tính nhanh tổng số giây.</p>
           
           <div class="grid grid-cols-3 gap-2">
              <div>
                 <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-1 text-center">Giờ</label>
                 <input type="number" id="calc-h" value="0" min="0" class="w-full bg-[#12141d] border border-white/5 rounded-xl py-2 text-center text-sm text-white focus:outline-none focus:border-primary/50" />
              </div>
              <div>
                 <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-1 text-center">Phút</label>
                 <input type="number" id="calc-m" value="0" min="0" max="59" class="w-full bg-[#12141d] border border-white/5 rounded-xl py-2 text-center text-sm text-white focus:outline-none focus:border-primary/50" />
              </div>
              <div>
                 <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-1 text-center">Giây</label>
                 <input type="number" id="calc-s" value="0" min="0" max="59" class="w-full bg-[#12141d] border border-white/5 rounded-xl py-2 text-center text-sm text-white focus:outline-none focus:border-primary/50" />
              </div>
           </div>

           <div class="bg-[#12141d]/85 rounded-2xl p-4 border border-white/5 text-center">
              <span class="text-[9px] font-black uppercase tracking-widest text-gray-500 block">Kết quả</span>
              <span class="text-2xl font-black text-primary mt-1 block" id="calc-result">0 giây</span>
           </div>

           <button id="calc-copy-btn" class="w-full flex items-center justify-center gap-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/5 py-3 text-xs font-black uppercase tracking-widest text-white transition-all active:scale-95">
              <i class="fas fa-copy"></i> Sao chép số giây
           </button>
        </div>
     </div>
  </div>

  <!-- FLOATING EPISODE FORM (DRAWER) -->
  <div id="ep-drawer" class="fixed inset-y-0 right-0 z-[150] w-full max-w-lg bg-[#12141d]/98 border-l border-white/10 shadow-[0_0_50px_rgba(0,0,0,0.8)] backdrop-blur-2xl p-8 flex flex-col justify-between transform translate-x-full transition-transform duration-300 pointer-events-none">
     <div class="flex-1 overflow-y-auto space-y-6">
        <div class="flex items-center justify-between border-b border-white/5 pb-4">
           <h3 class="text-lg font-black uppercase tracking-wider text-white flex items-center gap-2">
              <i class="fas fa-play-circle text-primary"></i> 
              <span id="ep-drawer-title">Cấu hình Tập phim</span>
           </h3>
           <button id="ep-drawer-close" class="h-10 w-10 rounded-xl bg-white/5 hover:bg-white/10 flex items-center justify-center text-gray-400 hover:text-white transition-all">
              <i class="fas fa-times"></i>
           </button>
        </div>

        <div class="space-y-5">
           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Tên hiển thị tập (Ví dụ: 1, 2, Full, Thuyết Minh)</label>
              <input type="text" id="ep-name" class="w-full bg-[#1e2130] border border-white/5 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary/50" />
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Đường dẫn tập (Slug - thường tự tạo)</label>
              <input type="text" id="ep-slug" class="w-full bg-[#1e2130] border border-white/5 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary/50" />
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Link HLS (M3U8) - Trình phát Stream</label>
              <input type="text" id="ep-link-m3u8" placeholder="https://domain.com/path/index.m3u8" class="w-full bg-[#1e2130] border border-white/5 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary/50" />
           </div>

           <div>
              <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-2">Link Embed (Nguồn Nhúng Iframe)</label>
              <input type="text" id="ep-link-embed" placeholder="https://domain.com/embed/..." class="w-full bg-[#1e2130] border border-white/5 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-primary/50" />
           </div>

           <!-- Intro & Outro skipping times -->
           <div class="border-t border-white/5 pt-4">
              <h4 class="text-xs font-black uppercase tracking-widest text-white mb-4">Cấu hình bỏ qua đoạn phim (giây)</h4>
              
              <div class="grid grid-cols-2 gap-4">
                 <div>
                    <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-2">Intro - Bắt đầu (giây)</label>
                    <div class="flex gap-2">
                       <input type="number" id="ep-intro-start" value="0" min="0" class="w-20 bg-[#1e2130] border border-white/5 rounded-xl px-3 text-sm text-white focus:outline-none text-center" />
                       <button class="modal-calc-trigger px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/5 text-[10px] font-bold text-gray-400 hover:text-white" data-target="ep-intro-start">
                          <i class="fas fa-calculator"></i>
                       </button>
                    </div>
                 </div>
                 <div>
                    <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-2">Intro - Kết thúc (giây)</label>
                    <div class="flex gap-2">
                       <input type="number" id="ep-intro-end" value="0" min="0" class="w-20 bg-[#1e2130] border border-white/5 rounded-xl px-3 text-sm text-white focus:outline-none text-center" />
                       <button class="modal-calc-trigger px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/5 text-[10px] font-bold text-gray-400 hover:text-white" data-target="ep-intro-end">
                          <i class="fas fa-calculator"></i>
                       </button>
                    </div>
                 </div>
              </div>

              <div class="grid grid-cols-2 gap-4 mt-4">
                 <div>
                    <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-2">Outro - Bắt đầu (giây)</label>
                    <div class="flex gap-2">
                       <input type="number" id="ep-outro-start" value="0" min="0" class="w-20 bg-[#1e2130] border border-white/5 rounded-xl px-3 text-sm text-white focus:outline-none text-center" />
                       <button class="modal-calc-trigger px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/5 text-[10px] font-bold text-gray-400 hover:text-white" data-target="ep-outro-start">
                          <i class="fas fa-calculator"></i>
                       </button>
                    </div>
                 </div>
                 <div>
                    <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-2">Outro - Kết thúc (giây)</label>
                    <div class="flex gap-2">
                       <input type="number" id="ep-outro-end" value="0" min="0" class="w-20 bg-[#1e2130] border border-white/5 rounded-xl px-3 text-sm text-white focus:outline-none text-center" />
                       <button class="modal-calc-trigger px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/5 text-[10px] font-bold text-gray-400 hover:text-white" data-target="ep-outro-end">
                          <i class="fas fa-calculator"></i>
                       </button>
                    </div>
                 </div>
              </div>
           </div>
        </div>
     </div>
     <div class="border-t border-white/5 pt-6 flex gap-4 mt-6">
        <button id="ep-drawer-save" class="flex-1 py-4 rounded-xl bg-primary text-dark text-xs font-black uppercase tracking-widest transition-all hover:scale-[1.02]">Cập nhật tập</button>
     </div>
  </div>

  <!-- MODAL ĐỔI GIÂY NHANH TRỰC TIẾP QUA TXAMODAL -->
  <div id="txa-calc-modal-content" class="hidden text-left space-y-4">
     <p class="text-xs text-gray-400">Nhập giờ, phút, giây để đổi sang số giây và điền trực tiếp vào ô input.</p>
     <div class="grid grid-cols-3 gap-3">
        <div>
           <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-1 text-center">Giờ</label>
           <input type="number" id="modal-calc-h" value="0" min="0" class="w-full bg-[#12141d] border border-white/5 rounded-xl py-3 text-center text-sm text-white focus:outline-none focus:border-primary/50" />
        </div>
        <div>
           <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-1 text-center">Phút</label>
           <input type="number" id="modal-calc-m" value="0" min="0" max="59" class="w-full bg-[#12141d] border border-white/5 rounded-xl py-3 text-center text-sm text-white focus:outline-none focus:border-primary/50" />
        </div>
        <div>
           <label class="block text-[9px] font-black uppercase tracking-widest text-gray-500 mb-1 text-center">Giây</label>
           <input type="number" id="modal-calc-s" value="0" min="0" max="59" class="w-full bg-[#12141d] border border-white/5 rounded-xl py-3 text-center text-sm text-white focus:outline-none focus:border-primary/50" />
        </div>
     </div>
     <div class="bg-[#12141d] rounded-2xl p-4 border border-white/5 text-center">
        <span class="text-[9px] font-black uppercase tracking-widest text-gray-500 block">Số giây quy đổi</span>
        <span class="text-3xl font-black text-primary mt-1 block" id="modal-calc-result">0 giây</span>
     </div>
  </div>
</AdminLayout>

<!-- Gắn dữ liệu ban đầu cho Client-side Script -->
<script define:vars={{ initialMovieData: movieData, initialServers: servers, localMovieSlugs: Object.keys(localMovies) }} is:inline>
  window.movieData = initialMovieData;
  window.initialServers = initialServers || [];
  window.localMovieSlugs = localMovieSlugs || [];
</script>

<script>
  let activeServerIndex = 0;
  let activeEpisodeIndex = 0;

  function init() {
     const { txamodal, txatoast, initTxaTooltips } = (window as any);
     if (!txatoast || !window.movieData) return;

     if (initTxaTooltips) initTxaTooltips();

     // Helper trích xuất slug
     const extractSlug = (input: string) => {
        if (!input) return null;
        const trimmed = input.trim();
        if (!trimmed) return null;
        
        try {
          if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
            const url = new URL(trimmed);
            const pathname = url.pathname;
            const parts = pathname.split('/').filter(Boolean);
            if (parts.length > 0) {
              return parts[parts.length - 1];
            }
          }
        } catch (e) {}
        
        const parts = trimmed.split('/').filter(Boolean);
        if (parts.length > 0) {
          return parts[parts.length - 1];
        }
        return trimmed;
     };

     // Hỗ trợ Nhập nhanh (Quick Auto-Import) cho KKPhim và Youtube
     const btnQuickImport = document.getElementById('btn-quick-import') as HTMLButtonElement;
     const quickUrlInput = document.getElementById('quick-url-input') as HTMLInputElement;

     if (btnQuickImport && quickUrlInput) {
        btnQuickImport.onclick = async () => {
           const inputVal = quickUrlInput.value.trim();
           if (!inputVal) {
              txatoast.error('Vui lòng nhập đường dẫn hoặc slug phim!');
              return;
           }

           // TH1: Xử lý link Youtube
           if (inputVal.includes('youtube.com') || inputVal.includes('youtu.be')) {
              let videoId = '';
              try {
                 if (inputVal.includes('youtu.be/')) {
                    videoId = inputVal.split('youtu.be/')[1].split(/[?#]/)[0];
                 } else if (inputVal.includes('youtube.com/embed/')) {
                    videoId = inputVal.split('youtube.com/embed/')[1].split(/[?#]/)[0];
                 } else {
                    const urlParams = new URLSearchParams(new URL(inputVal).search);
                    videoId = urlParams.get('v') || '';
                 }
              } catch(e){}

              if (videoId) {
                 txatoast.success('Phát hiện liên kết Youtube! Đã tự động điền các thông tin cơ bản.');
                 
                 // Tự tạo các thông tin cơ bản
                 (document.getElementById('mv-name') as HTMLInputElement).value = 'Video Youtube';
                 (document.getElementById('mv-origin-name') as HTMLInputElement).value = 'Youtube Stream';
                 (document.getElementById('mv-slug') as HTMLInputElement).value = `youtube-${videoId}`;
                 (document.getElementById('mv-poster') as HTMLInputElement).value = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`;
                 (document.getElementById('mv-thumb') as HTMLInputElement).value = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`;
                 (document.getElementById('mv-content') as HTMLTextAreaElement).value = 'Video phát từ Youtube.';
                 (document.getElementById('mv-type') as HTMLSelectElement).value = 'single';
                 (document.getElementById('mv-quality') as HTMLInputElement).value = 'FHD';
                 (document.getElementById('mv-lang') as HTMLInputElement).value = 'Vietsub';
                 (document.getElementById('mv-episode-current') as HTMLInputElement).value = 'Full';
                 (document.getElementById('mv-episode-total') as HTMLInputElement).value = '1';

                 // Tự động thêm server Youtube phát
                 window.movieData.episodes = [{
                    server_name: 'Youtube',
                    server_data: [{
                       name: 'Full',
                       slug: 'full',
                       filename: '',
                       link_m3u8: '',
                       link_embed: `https://www.youtube.com/embed/${videoId}`,
                       time_intro_start: 0,
                       time_intro_end: 0,
                       time_outro_start: 0,
                       time_outro_end: 0
                    }]
                 }];
                 renderServers();
              } else {
                 txatoast.error('Không trích xuất được Video ID từ link Youtube!');
              }
              return;
           }

           // TH2: Xử lý link hoặc slug KKPhim / OPhim
           const slug = extractSlug(inputVal);
           if (!slug) {
              txatoast.error('Đường dẫn hoặc slug phim không hợp lệ!');
              return;
           }

           btnQuickImport.disabled = true;
           const originalText = btnQuickImport.innerHTML;
           btnQuickImport.innerHTML = `<i class="fas fa-spinner animate-spin"></i> Đang tải dữ liệu...`;

           try {
              txatoast.info('Đang gửi truy vấn lấy thông tin phim từ API...');
              const res = await fetch(`https://phimapi.com/phim/${slug}`);
              if (!res.ok) {
                 throw new Error('Phim không tồn tại trên hệ thống dữ liệu API!');
              }
              const data = await res.json();
              if (!data.status || !data.movie) {
                 throw new Error('Dữ liệu trả về không đúng định dạng!');
              }

              const m = data.movie;

              // Tự động điền các input trường cơ bản
              (document.getElementById('mv-name') as HTMLInputElement).value = m.name || '';
              (document.getElementById('mv-origin-name') as HTMLInputElement).value = m.origin_name || '';
              (document.getElementById('mv-slug') as HTMLInputElement).value = m.slug || '';
              (document.getElementById('mv-poster') as HTMLInputElement).value = m.poster_url || '';
              (document.getElementById('mv-thumb') as HTMLInputElement).value = m.thumb_url || '';
              (document.getElementById('mv-year') as HTMLInputElement).value = m.year || new Date().getFullYear();
              (document.getElementById('mv-content') as HTMLTextAreaElement).value = m.content || '';
              (document.getElementById('mv-quality') as HTMLInputElement).value = m.quality || 'FHD';
              (document.getElementById('mv-lang') as HTMLInputElement).value = m.lang || 'Vietsub';
              (document.getElementById('mv-episode-current') as HTMLInputElement).value = m.episode_current || 'Tập 1';
              (document.getElementById('mv-episode-total') as HTMLInputElement).value = m.episode_total || '';

              // Thể loại, quốc gia, diễn viên, đạo diễn
              if (m.category) {
                 (document.getElementById('mv-category') as HTMLInputElement).value = m.category.map((c: any) => c.name).join(', ');
              }
              if (m.country) {
                 (document.getElementById('mv-country') as HTMLInputElement).value = m.country.map((c: any) => c.name).join(', ');
              }
              if (m.director) {
                 (document.getElementById('mv-director') as HTMLInputElement).value = m.director.join(', ');
              }
              if (m.actor) {
                 (document.getElementById('mv-actor') as HTMLInputElement).value = m.actor.join(', ');
              }

              // Set select values
              if (m.type) (document.getElementById('mv-type') as HTMLSelectElement).value = m.type;
              if (m.status) (document.getElementById('mv-status') as HTMLSelectElement).value = m.status;

              // Sync list servers & episodes
              if (data.episodes && data.episodes.length > 0) {
                 window.movieData.episodes = data.episodes;
                 renderServers();
              }

              txatoast.success(`Đã cào nhanh toàn bộ thông tin phim "${m.name}"!`);
           } catch(err: any) {
              txatoast.error(`Không thể cào dữ liệu phim: ${err.message}`);
           } finally {
              btnQuickImport.disabled = false;
              btnQuickImport.innerHTML = originalText;
           }
        };
     }

     // 1. Sidebar Calculator Logic
     const calcH = document.getElementById('calc-h') as HTMLInputElement;
     const calcM = document.getElementById('calc-m') as HTMLInputElement;
     const calcS = document.getElementById('calc-s') as HTMLInputElement;
     const calcResult = document.getElementById('calc-result');
     const calcCopyBtn = document.getElementById('calc-copy-btn');

     const updateCalcResult = () => {
        const h = parseInt(calcH.value || '0');
        const m = parseInt(calcM.value || '0');
        const s = parseInt(calcS.value || '0');
        const total = (h * 3600) + (m * 60) + s;
        if (calcResult) calcResult.innerText = `${total} giây`;
        return total;
     };

     if (calcH && calcM && calcS) {
        calcH.oninput = updateCalcResult;
        calcM.oninput = updateCalcResult;
        calcS.oninput = updateCalcResult;
     }

     if (calcCopyBtn) {
        calcCopyBtn.onclick = () => {
           const total = updateCalcResult();
           navigator.clipboard.writeText(String(total));
           txatoast.success(`Đã sao chép: ${total} giây!`);
        };
     }

     // 2. Slug Auto Generation on Name Input
     const mvName = document.getElementById('mv-name') as HTMLInputElement;
     const mvSlug = document.getElementById('mv-slug') as HTMLInputElement;

     if (mvName && mvSlug) {
        mvName.oninput = () => {
           const slug = mvName.value
              .toLowerCase()
              .normalize('NFD')
              .replace(/[\u0300-\u036f]/g, '')
              .replace(/[đĐ]/g, 'd')
              .replace(/[^a-z0-9\s-]/g, '')
              .replace(/\s+/g, '-')
              .replace(/-+/g, '-');
           mvSlug.value = slug;
        };
     }

     // 3. Render Servers & Episodes list
     const serversWrapper = document.getElementById('servers-wrapper');
     
     const renderServers = () => {
        if (!serversWrapper) return;
        serversWrapper.innerHTML = '';

        if (window.movieData.episodes.length === 0) {
           serversWrapper.innerHTML = `
              <div class="py-12 text-center text-gray-500 border border-dashed border-white/10 rounded-3xl">
                 <i class="fas fa-server text-3xl mb-3 block opacity-30"></i>
                 Chưa có Server và tập phim nào. Hãy dán link cào nhanh ở trên hoặc bấm thêm Server!
              </div>
           `;
           return;
        }

        window.movieData.episodes.forEach((server: any, sIdx: number) => {
           const serverDiv = document.createElement('div');
           serverDiv.className = "glass rounded-3xl p-6 md:p-8 border border-white/5 space-y-6 relative group";
           serverDiv.innerHTML = `
              <!-- Header Server -->
              <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between border-b border-white/5 pb-4">
                 <div class="flex items-center gap-4 flex-1">
                    <div class="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary text-xs font-black">
                       <i class="fas fa-server"></i>
                    </div>
                    <div class="flex-1 max-w-xs flex items-center">
                       <span class="text-sm font-black text-white tracking-wide uppercase bg-white/5 px-4 py-2.5 rounded-xl border border-white/5">${server.server_name}</span>
                    </div>
                 </div>
                 <div class="flex items-center gap-3">
                    <button class="delete-server-btn px-4 py-2 rounded-xl bg-red-500/10 hover:bg-red-500 text-red-400 hover:text-white border border-red-500/20 text-xs font-black uppercase tracking-widest transition-all active:scale-95" data-idx="${sIdx}">
                       Xóa Server
                    </button>
                 </div>
              </div>

              <!-- Bulk Action Section -->
              <div class="bg-white/[0.01] border border-white/5 rounded-2xl p-4 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                 <div class="flex items-center gap-2.5">
                    <input type="checkbox" id="chk-all-${sIdx}" class="chk-server-all h-4 w-4 rounded border-white/10 bg-white/5 text-primary focus:ring-primary focus:ring-offset-0 cursor-pointer" data-idx="${sIdx}" />
                    <label for="chk-all-${sIdx}" class="text-xs text-gray-400 font-bold select-none cursor-pointer">Chọn toàn bộ tập của server</label>
                 </div>
                 <div class="flex items-center gap-3">
                    <select class="bulk-ep-action bg-[#12141d] border border-white/5 rounded-xl px-3 py-2 text-xs font-bold text-gray-400 focus:outline-none" data-idx="${sIdx}">
                       <option value="">-- Bulk Action trên tập đã chọn --</option>
                       <option value="intro">Cập nhật nhanh Intro (giây)</option>
                       <option value="outro">Cập nhật nhanh Outro (giây)</option>
                       <option value="domain">Thay tên miền video hàng loạt</option>
                       <option value="delete">Xóa hàng loạt tập</option>
                    </select>
                    <button class="apply-bulk-ep-btn px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/5 text-xs font-black uppercase tracking-widest text-white transition-all active:scale-95" data-idx="${sIdx}">Áp dụng</button>
                 </div>
              </div>

              <!-- Grid Tập phim -->
              <div class="grid grid-cols-2 gap-4 sm:grid-cols-4 md:grid-cols-6 lg:grid-cols-8" id="ep-grid-${sIdx}">
                 <!-- Các tập sẽ render ở đây -->
              </div>

              <!-- Thêm Tập mới -->
              <button class="add-ep-btn w-full py-4 rounded-2xl border border-dashed border-white/10 hover:border-primary/30 flex items-center justify-center gap-2 text-xs font-black uppercase tracking-widest text-gray-500 hover:text-primary transition-all active:scale-98" data-idx="${sIdx}">
                 <i class="fas fa-plus"></i> Thêm tập mới vào Server này
              </button>
           `;

           const epGrid = serverDiv.querySelector(`#ep-grid-${sIdx}`);
           if (epGrid) {
              if (server.server_data.length === 0) {
                 epGrid.innerHTML = `<div class="col-span-full text-center text-xs text-gray-600 py-4">Chưa có tập nào</div>`;
              } else {
                 server.server_data.forEach((ep: any, epIdx: number) => {
                    const hasM3u8 = !!ep.link_m3u8;
                    const hasEmbed = !!ep.link_embed;
                    const hasSkips = (ep.time_intro_start > 0 || ep.time_intro_end > 0 || ep.time_outro_start > 0 || ep.time_outro_end > 0);

                    const epCard = document.createElement('div');
                    epCard.className = "relative group/ep border border-white/5 bg-[#12141d]/50 rounded-2xl p-4 flex flex-col items-center text-center justify-between min-h-[120px] hover:border-primary/30 transition-all";
                    epCard.innerHTML = `
                       <div class="absolute top-2.5 left-2.5">
                          <input type="checkbox" class="chk-ep h-3.5 w-3.5 rounded border-white/10 bg-white/5 text-primary focus:ring-primary focus:ring-offset-0 cursor-pointer" data-sidx="${sIdx}" data-epidx="${epIdx}" />
                       </div>
                       
                       <div class="flex items-center gap-1.5 absolute top-2.5 right-2.5">
                          ${hasM3u8 ? `<span class="h-2 w-2 rounded-full bg-emerald-500" data-txatooltip="Có luồng HLS/M3U8"></span>` : ''}
                          ${hasEmbed ? `<span class="h-2 w-2 rounded-full bg-blue-500" data-txatooltip="Có nguồn Nhúng/Embed"></span>` : ''}
                          ${hasSkips ? `<span class="h-2 w-2 rounded-full bg-amber-500" data-txatooltip="Có cấu hình skip Intro/Outro"></span>` : ''}
                       </div>

                       <span class="text-sm font-black text-white mt-5 group-hover/ep:text-primary transition-colors block">Tập ${ep.name}</span>
                       
                       <div class="flex gap-1.5 mt-3 w-full">
                          <button class="edit-ep-btn flex-1 py-1.5 rounded-lg bg-white/5 hover:bg-white/10 text-[9px] font-black uppercase text-gray-400 hover:text-white transition-colors" data-sidx="${sIdx}" data-epidx="${epIdx}">Sửa</button>
                          <button class="delete-ep-btn h-6 w-6 rounded-lg bg-red-500/10 hover:bg-red-500 flex items-center justify-center text-red-400 hover:text-white transition-colors" data-sidx="${sIdx}" data-epidx="${epIdx}"><i class="fas fa-trash text-[9px]"></i></button>
                       </div>
                    `;
                    epGrid.appendChild(epCard);
                 });
              }
           }

           serversWrapper.appendChild(serverDiv);
        });

        // Gắn sự kiện cho các nút
        bindEvents();
        if (initTxaTooltips) initTxaTooltips();
     };

     const bindEvents = () => {
        // Xóa Server
        document.querySelectorAll('.delete-server-btn').forEach(btn => {
           const b = btn as HTMLButtonElement;
           b.onclick = () => {
              const idx = parseInt(b.getAttribute('data-idx') || '0');
              txamodal.show({
                 title: 'Xóa Server phát',
                 message: `Bạn muốn xóa toàn bộ server <strong>${window.movieData.episodes[idx].server_name}</strong> và các tập kèm theo? Thao tác này không thể hoàn tác.`,
                 type: 'danger',
                 confirmText: 'Xóa hoàn toàn',
                 onConfirm: () => {
                    window.movieData.episodes.splice(idx, 1);
                    renderServers();
                    txatoast.success('Đã xóa Server!');
                    return true;
                 }
              });
           };
        });

        // Thêm Tập mới thủ công thông minh
        document.querySelectorAll('.add-ep-btn').forEach(btn => {
           const b = btn as HTMLButtonElement;
           b.onclick = () => {
              const sIdx = parseInt(b.getAttribute('data-idx') || '0');
              const currentCount = window.movieData.episodes[sIdx].server_data.length;
              const nextNum = currentCount + 1;

              txamodal.show({
                 title: 'Thêm tập phim thủ công',
                 message: `
                    <div class="space-y-4 text-left">
                       <div>
                          <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-1">Tên tập phim</label>
                          <input type="text" id="manual-ep-name" value="${nextNum}" placeholder="Ví dụ: ${nextNum}, Full..." class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none" />
                       </div>
                       <div>
                          <label class="block text-[10px] font-black uppercase tracking-widest text-gray-500 mb-1">URL nguồn tập phim (Link phát)</label>
                          <input type="text" id="manual-ep-url" placeholder="Dán link .m3u8, embed, hoặc link KKPhim..." class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none" />
                       </div>
                    </div>
                 `,
                 type: 'success',
                 confirmText: 'Xác nhận thêm',
                 onConfirm: async () => {
                    const nameVal = (document.getElementById('manual-ep-name') as HTMLInputElement)?.value.trim();
                    const urlVal = (document.getElementById('manual-ep-url') as HTMLInputElement)?.value.trim() || '';

                    if (!nameVal) {
                       txatoast.error('Không được để trống Tên tập!');
                       return false;
                    }

                    let linkM3u8 = '';
                    let linkEmbed = '';

                    txatoast.info('Đang xử lý phân tích link...');

                    if (urlVal.includes('.m3u8')) {
                       linkM3u8 = urlVal;
                    } else if (urlVal.includes('embed') || urlVal.includes('iframe') || urlVal.includes('player')) {
                       linkEmbed = urlVal;
                    } else {
                       linkM3u8 = urlVal;
                    }

                    const newEp = {
                       name: nameVal,
                       slug: `tap-${nameVal.toLowerCase().replace(/\s+/g, '-')}`,
                       filename: '',
                       link_m3u8: linkM3u8,
                       link_embed: linkEmbed,
                       time_intro_start: 0,
                       time_intro_end: 0,
                       time_outro_start: 0,
                       time_outro_end: 0
                    };

                    window.movieData.episodes[sIdx].server_data.push(newEp);
                    renderServers();
                    txatoast.success(`Đã thêm Tập ${nameVal}!`);
                    return true;
                 }
              });
           };
        });

        // Tick chọn toàn bộ
        document.querySelectorAll('.chk-server-all').forEach(chk => {
           const c = chk as HTMLInputElement;
           c.onchange = () => {
              const sIdx = parseInt(c.getAttribute('data-idx') || '0');
              const grid = document.getElementById(`ep-grid-${sIdx}`);
              if (grid) {
                 grid.querySelectorAll('.chk-ep').forEach(item => {
                    (item as HTMLInputElement).checked = c.checked;
                 });
              }
           };
        });

        // Xóa Tập đơn lẻ
        document.querySelectorAll('.delete-ep-btn').forEach(btn => {
           const b = btn as HTMLButtonElement;
           b.onclick = () => {
              const sIdx = parseInt(b.getAttribute('data-sidx') || '0');
              const epIdx = parseInt(b.getAttribute('data-epidx') || '0');
              const epName = window.movieData.episodes[sIdx].server_data[epIdx].name;

              txamodal.show({
                 title: 'Xóa tập phim',
                 message: `Bạn muốn xóa <strong>Tập ${epName}</strong>?`,
                 type: 'danger',
                 confirmText: 'Xóa',
                 onConfirm: () => {
                    window.movieData.episodes[sIdx].server_data.splice(epIdx, 1);
                    renderServers();
                    txatoast.success('Đã xóa tập phim!');
                    return true;
                 }
              });
           };
        });

        // Sửa Tập (Mở Drawer chỉnh sửa)
        document.querySelectorAll('.edit-ep-btn').forEach(btn => {
           const b = btn as HTMLButtonElement;
           b.onclick = () => {
              activeServerIndex = parseInt(b.getAttribute('data-sidx') || '0');
              activeEpisodeIndex = parseInt(b.getAttribute('data-epidx') || '0');
              openEpisodeDrawer();
           };
        });

        // Áp dụng Bulk Actions trên tập phim
        document.querySelectorAll('.apply-bulk-ep-btn').forEach(btn => {
           const b = btn as HTMLButtonElement;
           b.onclick = () => {
              const sIdx = parseInt(b.getAttribute('data-idx') || '0');
              const selectEl = document.querySelector(`.bulk-ep-action[data-idx="${sIdx}"]`) as HTMLSelectElement;
              const action = selectEl?.value;
              
              if (!action) {
                 txatoast.error('Vui lòng chọn một hành động!');
                 return;
              }

              const grid = document.getElementById(`ep-grid-${sIdx}`);
              if (!grid) return;
              
              const checkedBoxes = Array.from(grid.querySelectorAll('.chk-ep:checked')) as HTMLInputElement[];
              if (checkedBoxes.length === 0) {
                 txatoast.error('Chưa tick chọn tập phim nào để áp dụng!');
                 return;
              }

              const selectedIndices = checkedBoxes.map(chk => parseInt(chk.getAttribute('data-epidx') || '0'));

              if (action === 'delete') {
                 txamodal.show({
                    title: 'Xóa hàng loạt tập phim',
                    message: `Bạn chắc chắn muốn xóa <strong>${selectedIndices.length}</strong> tập đã chọn?`,
                    type: 'danger',
                    confirmText: 'Xóa',
                    onConfirm: () => {
                       selectedIndices.sort((a, b) => b - a).forEach(idx => {
                          window.movieData.episodes[sIdx].server_data.splice(idx, 1);
                       });
                       renderServers();
                       txatoast.success('Đã xóa hàng loạt tập!');
                       return true;
                    }
                 });
              } else if (action === 'intro') {
                 txamodal.show({
                    title: 'Cập nhật hàng loạt Intro',
                    message: `Nhập khoảng thời gian Intro áp dụng cho <strong>${selectedIndices.length}</strong> tập đã chọn (đơn vị: giây):
                       <div class="grid grid-cols-2 gap-3 mt-4 text-left">
                          <div>
                             <label class="block text-[10px] font-black uppercase text-gray-500 mb-1">Giây bắt đầu</label>
                             <input type="number" id="bulk-start" value="0" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white" />
                          </div>
                          <div>
                             <label class="block text-[10px] font-black uppercase text-gray-500 mb-1">Giây kết thúc</label>
                             <input type="number" id="bulk-end" value="0" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white" />
                          </div>
                       </div>`,
                    type: 'warning',
                    confirmText: 'Cập nhật',
                    onConfirm: () => {
                       const startVal = parseInt((document.getElementById('bulk-start') as HTMLInputElement)?.value || '0');
                       const endVal = parseInt((document.getElementById('bulk-end') as HTMLInputElement)?.value || '0');
                       selectedIndices.forEach(idx => {
                          window.movieData.episodes[sIdx].server_data[idx].time_intro_start = startVal;
                          window.movieData.episodes[sIdx].server_data[idx].time_intro_end = endVal;
                       });
                       renderServers();
                       txatoast.success('Đã cập nhật hàng loạt Intro!');
                       return true;
                    }
                 });
              } else if (action === 'outro') {
                 txamodal.show({
                    title: 'Cập nhật hàng loạt Outro',
                    message: `Nhập khoảng thời gian Outro áp dụng cho <strong>${selectedIndices.length}</strong> tập đã chọn (đơn vị: giây):
                       <div class="grid grid-cols-2 gap-3 mt-4 text-left">
                          <div>
                             <label class="block text-[10px] font-black uppercase text-gray-500 mb-1">Giây bắt đầu</label>
                             <input type="number" id="bulk-start" value="0" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white" />
                          </div>
                          <div>
                             <label class="block text-[10px] font-black uppercase text-gray-500 mb-1">Giây kết thúc</label>
                             <input type="number" id="bulk-end" value="0" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white" />
                          </div>
                       </div>`,
                    type: 'warning',
                    confirmText: 'Cập nhật',
                    onConfirm: () => {
                       const startVal = parseInt((document.getElementById('bulk-start') as HTMLInputElement)?.value || '0');
                       const endVal = parseInt((document.getElementById('bulk-end') as HTMLInputElement)?.value || '0');
                       selectedIndices.forEach(idx => {
                          window.movieData.episodes[sIdx].server_data[idx].time_outro_start = startVal;
                          window.movieData.episodes[sIdx].server_data[idx].time_outro_end = endVal;
                       });
                       renderServers();
                       txatoast.success('Đã cập nhật hàng loạt Outro!');
                       return true;
                    }
                 });
              } else if (action === 'domain') {
                 txamodal.show({
                    title: 'Thay thế tên miền hàng loạt',
                    message: `Nhập tên miền cũ và tên miền mới cần thay thế trong link M3U8 của <strong>${selectedIndices.length}</strong> tập:
                       <div class="space-y-3 mt-4 text-left">
                          <div>
                             <label class="block text-[10px] font-black uppercase text-gray-500 mb-1">Tên miền cũ (Ví dụ: sv1.iphim.com)</label>
                             <input type="text" id="domain-old" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white" />
                          </div>
                          <div>
                             <label class="block text-[10px] font-black uppercase text-gray-500 mb-1">Tên miền mới (Ví dụ: sv2.rophim.com)</label>
                             <input type="text" id="domain-new" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-2.5 text-sm text-white" />
                          </div>
                       </div>`,
                    type: 'warning',
                    confirmText: 'Thay thế',
                    onConfirm: () => {
                       const oldDomain = (document.getElementById('domain-old') as HTMLInputElement)?.value.trim();
                       const newDomain = (document.getElementById('domain-new') as HTMLInputElement)?.value.trim();
                       
                       if (!oldDomain || !newDomain) {
                          txatoast.error('Không được để trống tên miền!');
                          return false;
                       }

                       selectedIndices.forEach(idx => {
                          const ep = window.movieData.episodes[sIdx].server_data[idx];
                          if (ep.link_m3u8) ep.link_m3u8 = ep.link_m3u8.replace(oldDomain, newDomain);
                          if (ep.link_embed) ep.link_embed = ep.link_embed.replace(oldDomain, newDomain);
                       });

                       renderServers();
                       txatoast.success('Đã thay thế hàng loạt tên miền!');
                       return true;
                    }
                 });
              }
           };
        });
     };

     // 4. Episode Drawer Editing Control
     const drawer = document.getElementById('ep-drawer');
     const drTitle = document.getElementById('ep-drawer-title');
     const drClose = document.getElementById('ep-drawer-close');
     const drSave = document.getElementById('ep-drawer-save');

     const epNameInput = document.getElementById('ep-name') as HTMLInputElement;
     const epSlugInput = document.getElementById('ep-slug') as HTMLInputElement;
     const epM3u8Input = document.getElementById('ep-link-m3u8') as HTMLInputElement;
     const epEmbedInput = document.getElementById('ep-link-embed') as HTMLInputElement;

     const epIntroStart = document.getElementById('ep-intro-start') as HTMLInputElement;
     const epIntroEnd = document.getElementById('ep-intro-end') as HTMLInputElement;
     const epOutroStart = document.getElementById('ep-outro-start') as HTMLInputElement;
     const epOutroEnd = document.getElementById('ep-outro-end') as HTMLInputElement;

     const openEpisodeDrawer = () => {
        if (!drawer) return;
        const server = window.movieData.episodes[activeServerIndex];
        const ep = server.server_data[activeEpisodeIndex];

        if (drTitle) drTitle.innerText = `Sửa: Server ${server.server_name} - Tập ${ep.name}`;
        
        epNameInput.value = ep.name;
        epSlugInput.value = ep.slug;
        epM3u8Input.value = ep.link_m3u8 || '';
        epEmbedInput.value = ep.link_embed || '';
        epIntroStart.value = String(ep.time_intro_start || 0);
        epIntroEnd.value = String(ep.time_intro_end || 0);
        epOutroStart.value = String(ep.time_outro_start || 0);
        epOutroEnd.value = String(ep.time_outro_end || 0);

        drawer.classList.remove('translate-x-full', 'pointer-events-none');
        drawer.classList.add('translate-x-0', 'pointer-events-auto');
     };

     const closeEpisodeDrawer = () => {
        if (drawer) {
           drawer.classList.add('translate-x-full', 'pointer-events-none');
           drawer.classList.remove('translate-x-0', 'pointer-events-auto');
        }
     };

     if (drClose) drClose.onclick = closeEpisodeDrawer;

     // Save Episode edits
     if (drSave) {
        drSave.onclick = () => {
           const server = window.movieData.episodes[activeServerIndex];
           const ep = server.server_data[activeEpisodeIndex];

           ep.name = epNameInput.value.trim() || ep.name;
           ep.slug = epSlugInput.value.trim() || ep.slug;
           ep.link_m3u8 = epM3u8Input.value.trim();
           ep.link_embed = epEmbedInput.value.trim();
           ep.time_intro_start = parseInt(epIntroStart.value || '0');
           ep.time_intro_end = parseInt(epIntroEnd.value || '0');
           ep.time_outro_start = parseInt(epOutroStart.value || '0');
           ep.time_outro_end = parseInt(epOutroEnd.value || '0');

           closeEpisodeDrawer();
           renderServers();
           txatoast.success(`Đã cập nhật tập ${ep.name}!`);
        };
     }

     // Direct Modal converter trigger
     document.addEventListener('click', (e) => {
        const target = e.target as HTMLElement;
        const btn = target.closest('.modal-calc-trigger');
        if (!btn) return;

        const inputId = btn.getAttribute('data-target') || '';
        const targetInput = document.getElementById(inputId) as HTMLInputElement;
        if (!targetInput) return;

        const modalContent = document.getElementById('txa-calc-modal-content');
        if (!modalContent) return;

        const mCalcH = document.getElementById('modal-calc-h') as HTMLInputElement;
        const mCalcM = document.getElementById('modal-calc-m') as HTMLInputElement;
        const mCalcS = document.getElementById('modal-calc-s') as HTMLInputElement;
        const mCalcResult = document.getElementById('modal-calc-result');

        const updateModalCalc = () => {
           const h = parseInt(mCalcH.value || '0');
           const m = parseInt(mCalcM.value || '0');
           const s = parseInt(mCalcS.value || '0');
           const total = (h * 3600) + (m * 60) + s;
           if (mCalcResult) mCalcResult.innerText = `${total} giây`;
           return total;
        };

        if (mCalcH && mCalcM && mCalcS) {
           mCalcH.value = '0';
           mCalcM.value = '0';
           mCalcS.value = '0';
           mCalcH.oninput = updateModalCalc;
           mCalcM.oninput = updateModalCalc;
           mCalcS.oninput = updateModalCalc;
           updateModalCalc();
        }

        txamodal.show({
           title: 'Công cụ tính số giây',
           message: modalContent.innerHTML,
           type: 'warning',
           confirmText: 'Áp dụng số giây',
           onConfirm: () => {
              const activeH = document.getElementById('modal-calc-h') as HTMLInputElement;
              const activeM = document.getElementById('modal-calc-m') as HTMLInputElement;
              const activeS = document.getElementById('modal-calc-s') as HTMLInputElement;

              const h = parseInt(activeH?.value || '0');
              const m = parseInt(activeM?.value || '0');
              const s = parseInt(activeS?.value || '0');
              const total = (h * 3600) + (m * 60) + s;

              targetInput.value = String(total);
              txatoast.success(`Đã áp dụng: ${total} giây!`);
              return true;
           }
        });
     });

     // Add Server control
     const addServerBtn = document.getElementById('add-server-btn');
     if (addServerBtn) {
        addServerBtn.onclick = () => {
            const serversList = (window as any).initialServers || [];
            if (serversList.length === 0) {
               txamodal.show({
                  title: 'Thêm Server mới',
                  message: `<p class="text-sm text-gray-400">Không có máy chủ nào được cấu hình sẵn trong hệ thống!</p>
                            <p class="text-xs text-gray-500 mt-2">Vui lòng truy cập trang Quản lý Server để thêm máy chủ mới trước.</p>`,
                  type: 'warning',
                  confirmText: 'Đi tới Quản lý Server',
                  onConfirm: () => {
                     window.location.href = '/admin/server';
                     return true;
                  }
               });
               return;
            }

            const serverOptions = serversList.map((s: any) => `<option value="${s.name}">${s.name}</option>`).join('');
            txamodal.show({
               title: 'Thêm Server mới',
               message: `Chọn máy chủ phát:
                  <select id="new-sv-name" class="w-full bg-[#12141d] border border-white/5 rounded-xl px-4 py-3.5 mt-2 text-sm text-white focus:outline-none focus:border-primary/50">
                     ${serverOptions}
                  </select>`,
               type: 'success',
               confirmText: 'Thêm Server',
               onConfirm: () => {
                  const nameVal = (document.getElementById('new-sv-name') as HTMLSelectElement)?.value || 'Server';
                  const exists = window.movieData.episodes.some((s: any) => s.server_name === nameVal);
                  if (exists) {
                     txatoast.warning(`Phim này đã có Server ${nameVal}!`);
                     return false;
                  }
                  window.movieData.episodes.push({
                     server_name: nameVal,
                     server_data: []
                  });
                  renderServers();
                  txatoast.success(`Đã thêm Server ${nameVal}!`);
                  return true;
               }
            });
         };
     }

     // Save Movie Action
     const saveMovieBtn = document.getElementById('save-movie-btn');
     if (saveMovieBtn) {
        saveMovieBtn.onclick = async () => {
           const name = (document.getElementById('mv-name') as HTMLInputElement)?.value.trim();
           const origin_name = (document.getElementById('mv-origin-name') as HTMLInputElement)?.value.trim();
           const slug = (document.getElementById('mv-slug') as HTMLInputElement)?.value.trim();
           
           if (!name || !slug) {
              txatoast.error('Không được để trống Tên phim và Slug!');
              return;
           }

           const localSlugs = (window as any).localMovieSlugs || [];
           if (localSlugs.includes(slug)) {
              txatoast.error('Đường dẫn (Slug) này đã tồn tại trong hệ thống!');
              return;
           }

           window.movieData.movie.name = name;
           window.movieData.movie.origin_name = origin_name;
           window.movieData.movie.slug = slug;
           window.movieData.movie.type = (document.getElementById('mv-type') as HTMLSelectElement).value;
           window.movieData.movie.status = (document.getElementById('mv-status') as HTMLSelectElement).value;
           window.movieData.movie.poster_url = (document.getElementById('mv-poster') as HTMLInputElement).value.trim();
           window.movieData.movie.thumb_url = (document.getElementById('mv-thumb') as HTMLInputElement).value.trim();
           const slugify = (text: string) => {
               return text.toString().toLowerCase().trim()
                  .normalize('NFD')
                  .replace(/[\u0300-\u036f]/g, '')
                  .replace(/[đĐ]/g, 'd')
                  .replace(/[^a-z0-9 -]/g, '')
                  .replace(/\s+/g, '-')
                  .replace(/-+/g, '-');
            };

            const rawCat = (document.getElementById('mv-category') as HTMLInputElement).value.trim();
            window.movieData.movie.category = rawCat.split(',')
               .map(v => v.trim())
               .filter(Boolean)
               .map(name => ({
                  name,
                  slug: slugify(name)
               }));

            const rawCountry = (document.getElementById('mv-country') as HTMLInputElement).value.trim();
            window.movieData.movie.country = rawCountry.split(',')
               .map(v => v.trim())
               .filter(Boolean)
               .map(name => ({
                  name,
                  slug: slugify(name)
               }));
           window.movieData.movie.year = parseInt((document.getElementById('mv-year') as HTMLInputElement).value || '2026');
           window.movieData.movie.director = (document.getElementById('mv-director') as HTMLInputElement).value.trim();
           window.movieData.movie.actor = (document.getElementById('mv-actor') as HTMLInputElement).value.trim();
           window.movieData.movie.content = (document.getElementById('mv-content') as HTMLTextAreaElement).value.trim();
           window.movieData.movie.quality = (document.getElementById('mv-quality') as HTMLInputElement).value.trim();
           window.movieData.movie.lang = (document.getElementById('mv-lang') as HTMLInputElement).value.trim();
           window.movieData.movie.episode_current = (document.getElementById('mv-episode-current') as HTMLInputElement).value.trim();
           window.movieData.movie.episode_total = parseInt((document.getElementById('mv-episode-total') as HTMLInputElement).value) || null;
            window.movieData.movie.trailer_url = (document.getElementById('mv-trailer') as HTMLInputElement).value.trim() || '';
            window.movieData.movie.only_login = (document.getElementById('mv-only-login') as HTMLInputElement).checked;
             window.movieData.movie.is_slider = (document.getElementById('mv-is-slider') as HTMLInputElement).checked;
            window.movieData.movie.require_login = (document.getElementById('mv-only-login') as HTMLInputElement).checked;

           // Schedule next episode
           const schedDate = (document.getElementById('mv-next-ep-date') as HTMLInputElement).value;
           const schedTime = (document.getElementById('mv-next-ep-time') as HTMLInputElement).value || '20:00';
           const schedName = (document.getElementById('mv-next-ep-name') as HTMLInputElement).value.trim();
           if (schedDate) {
              window.movieData.movie.next_episode_time = new Date(`${schedDate}T${schedTime}:00`).toISOString();
              window.movieData.movie.next_episode_name = schedName || '';
           } else {
              window.movieData.movie.next_episode_time = null;
              window.movieData.movie.next_episode_name = '';
           }

           txatoast.info('Đang lưu thông tin phim...');

           try {
              const res = await fetch('/api/admin/movie/save', {
                 method: 'POST',
                 body: JSON.stringify({
                    slug: window.movieData.movie.slug,
                    movie: window.movieData.movie,
                    episodes: window.movieData.episodes
                 })
              });
              const data = await res.json();
              if (res.ok) {
                 txatoast.success(data.message);
                 setTimeout(() => {
                    window.location.href = '/admin/phim';
                 }, 1500);
              } else {
                 txatoast.error(data.error);
              }
           } catch (e) {
              txatoast.error('Lỗi kết nối khi lưu phim!');
           }
        };
     }

     // Initial Render
     renderServers();

     // === STATUS → SCHEDULE WARNING LOGIC ===
     const statusSelect = document.getElementById('mv-status') as HTMLSelectElement;
     const completedWarn = document.getElementById('schedule-completed-warn');
     function checkStatusForSchedule() {
       if (statusSelect?.value === 'completed') {
         completedWarn?.classList.remove('hidden');
       } else {
         completedWarn?.classList.add('hidden');
       }
     }
     statusSelect?.addEventListener('change', checkStatusForSchedule);
     checkStatusForSchedule();

     // === SCHEDULE COUNTDOWN LOGIC ===
     const schedDateInput = document.getElementById('mv-next-ep-date') as HTMLInputElement;
     const schedTimeInput = document.getElementById('mv-next-ep-time') as HTMLInputElement;
     const schedNameInput = document.getElementById('mv-next-ep-name') as HTMLInputElement;
     const schedPreview = document.getElementById('schedule-preview');
     const schedLabel = document.getElementById('schedule-ep-label');
     const clearSchedBtn = document.getElementById('clear-schedule-btn');
     let countdownInterval: any = null;

     function updateCountdown() {
       const dateVal = schedDateInput?.value;
       const timeVal = schedTimeInput?.value || '20:00';
       if (!dateVal) {
         schedPreview?.classList.add('hidden');
         clearSchedBtn?.classList.add('hidden');
         if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
         return;
       }

       const target = new Date(`${dateVal}T${timeVal}:00`);
       if (isNaN(target.getTime())) return;

       const epName = schedNameInput?.value || 'Chưa đặt tên';
       if (schedLabel) schedLabel.textContent = epName;
       schedPreview?.classList.remove('hidden');
       clearSchedBtn?.classList.remove('hidden');

       function tick() {
         const now = new Date();
         const diff = target.getTime() - now.getTime();
         if (diff <= 0) {
           document.getElementById('cd-days')!.textContent = '00';
           document.getElementById('cd-hours')!.textContent = '00';
           document.getElementById('cd-mins')!.textContent = '00';
           document.getElementById('cd-secs')!.textContent = '00';
           return;
         }
         const days = Math.floor(diff / 86400000);
         const hours = Math.floor((diff % 86400000) / 3600000);
         const mins = Math.floor((diff % 3600000) / 60000);
         const secs = Math.floor((diff % 60000) / 1000);
         document.getElementById('cd-days')!.textContent = String(days).padStart(2, '0');
         document.getElementById('cd-hours')!.textContent = String(hours).padStart(2, '0');
         document.getElementById('cd-mins')!.textContent = String(mins).padStart(2, '0');
         document.getElementById('cd-secs')!.textContent = String(secs).padStart(2, '0');
       }
       tick();
       if (countdownInterval) clearInterval(countdownInterval);
       countdownInterval = setInterval(tick, 1000);
     }

     schedDateInput?.addEventListener('change', updateCountdown);
     schedTimeInput?.addEventListener('change', updateCountdown);
     schedNameInput?.addEventListener('input', () => {
       if (schedLabel) schedLabel.textContent = schedNameInput.value || 'Chưa đặt tên';
     });

     clearSchedBtn?.addEventListener('click', () => {
       schedDateInput.value = '';
       schedTimeInput.value = '20:00';
       schedNameInput.value = '';
       schedPreview?.classList.add('hidden');
       clearSchedBtn?.classList.add('hidden');
       if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
       txatoast.success('Đã xoá lịch chiếu tập tiếp theo!');
     });

     updateCountdown();

      // === DYNAMIC PRESET CATEGORIES & COUNTRIES DROPDOWNS ===
      const PRESETS_CATEGORIES = [
        "Hành Động", "Cổ Trang", "Chiến Tranh", "Viễn Tưởng", "Kinh Dị",
        "Hài Hước", "Tình Cảm", "Tâm Lý", "Hình Sự", "Võ Thuật",
        "Phiêu Lưu", "Khoa Học", "Thần Thoại", "Chính Kịch", "Gia Đình",
        "Học Đường", "Thể Thao", "Âm Nhạc", "Bí Ẩn", "Hoạt Hinh", "Tài Liệu"
      ];
      
      const PRESETS_COUNTRIES = [
        "Trung Quốc", "Mỹ", "Hàn Quốc", "Nhật Bản", "Hồng Kông", 
        "Đài Loan", "Thái Lan", "Việt Nam", "Ấn Độ", "Pháp", 
        "Anh", "Đức", "Tây Ban Nha", "Canada", "Nga", "Úc"
      ];

      const inputCategory = document.getElementById('mv-category') as HTMLInputElement;
      const dropdownCategory = document.getElementById('category-dropdown');
      const gridCategory = document.getElementById('category-options-grid');

      const inputCountry = document.getElementById('mv-country') as HTMLInputElement;
      const dropdownCountry = document.getElementById('country-dropdown');
      const gridCountry = document.getElementById('country-options-grid');

      const renderCategoryOptions = () => {
         if (!gridCategory || !inputCategory) return;
         
         const currentVals = inputCategory.value.split(',')
            .map(v => v.trim())
            .filter(Boolean);
            
         gridCategory.innerHTML = '';
         PRESETS_CATEGORIES.forEach(cat => {
            const isSelected = currentVals.includes(cat);
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = `flex items-center justify-between px-3 py-2.5 rounded-xl text-[11px] font-bold transition-all border text-left ${
               isSelected 
               ? 'bg-primary/20 text-primary border-primary/30 shadow-[0_0_10px_rgba(124,58,237,0.1)]' 
               : 'bg-white/5 text-gray-300 border-white/5 hover:bg-white/10 hover:text-white'
            }`;
            btn.innerHTML = `
               <span class="truncate">${cat}</span>
               ${isSelected ? '<i class="fas fa-check text-[9px] shrink-0 ml-1 text-primary"></i>' : ''}
            `;
            
            btn.onclick = (e) => {
               e.preventDefault();
               e.stopPropagation();
               
               let vals = inputCategory.value.split(',')
                  .map(v => v.trim())
                  .filter(Boolean);
                  
               if (vals.includes(cat)) {
                  vals = vals.filter(v => v !== cat);
               } else {
                  vals.push(cat);
               }
               
               inputCategory.value = vals.join(', ');
               renderCategoryOptions();
               inputCategory.dispatchEvent(new Event('input'));
            };
            gridCategory.appendChild(btn);
         });
      };

      if (inputCategory && dropdownCategory) {
         inputCategory.addEventListener('focus', () => {
            dropdownCategory.classList.remove('hidden');
            if (dropdownCountry) dropdownCountry.classList.add('hidden');
            renderCategoryOptions();
         });
         inputCategory.addEventListener('input', renderCategoryOptions);
      }

      const renderCountryOptions = () => {
         if (!gridCountry || !inputCountry) return;
         
         const currentVal = inputCountry.value.trim();
         
         gridCountry.innerHTML = '';
         PRESETS_COUNTRIES.forEach(country => {
            const isSelected = currentVal === country;
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = `flex items-center justify-between px-3 py-2.5 rounded-xl text-[11px] font-bold transition-all border text-left ${
               isSelected 
               ? 'bg-primary/20 text-primary border-primary/30 shadow-[0_0_10px_rgba(124,58,237,0.1)]' 
               : 'bg-white/5 text-gray-300 border-white/5 hover:bg-white/10 hover:text-white'
            }`;
            btn.innerHTML = `
               <span class="truncate">${country}</span>
               ${isSelected ? '<i class="fas fa-check text-[9px] shrink-0 ml-1 text-primary"></i>' : ''}
            `;
            
            btn.onclick = (e) => {
               e.preventDefault();
               e.stopPropagation();
               
               inputCountry.value = country;
               renderCountryOptions();
               dropdownCountry?.classList.add('hidden');
               inputCountry.dispatchEvent(new Event('input'));
            };
            gridCountry.appendChild(btn);
         });
      };

      if (inputCountry && dropdownCountry) {
         inputCountry.addEventListener('focus', () => {
            dropdownCountry.classList.remove('hidden');
            if (dropdownCategory) dropdownCategory.classList.add('hidden');
            renderCountryOptions();
         });
         inputCountry.addEventListener('input', renderCountryOptions);
      }

      document.addEventListener('click', (e) => {
         const target = e.target;
         if (inputCategory && dropdownCategory && !inputCategory.contains(target) && !dropdownCategory.contains(target)) {
            dropdownCategory.classList.add('hidden');
         }
         if (inputCountry && dropdownCountry && !inputCountry.contains(target) && !dropdownCountry.contains(target)) {
            dropdownCountry.classList.add('hidden');
         }
      });
  }

  document.addEventListener('astro:page-load', init);
</script>

<style>
  .glass {
    background: rgba(18, 20, 29, 0.4);
    backdrop-filter: blur(40px) saturate(200%);
  }
</style>