File size: 117,762 Bytes
07f63a8
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
36dde81
07f63a8
 
 
 
36dde81
07f63a8
36dde81
 
07f63a8
 
36dde81
 
 
07f63a8
 
 
36dde81
 
 
 
 
07f63a8
 
36dde81
 
 
07f63a8
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
07f63a8
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
36dde81
07f63a8
36dde81
 
07f63a8
36dde81
 
07f63a8
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
36dde81
 
07f63a8
36dde81
 
07f63a8
 
36dde81
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
36dde81
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e18b74
 
 
 
 
 
 
 
07f63a8
 
b0d3e32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
 
 
 
 
 
 
 
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
 
 
 
36dde81
 
 
 
c12bb0b
 
 
 
36dde81
c12bb0b
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c12bb0b
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
36dde81
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
36dde81
 
 
07f63a8
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
c12bb0b
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
07f63a8
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
36dde81
 
 
 
 
07f63a8
36dde81
 
 
 
 
 
 
07f63a8
36dde81
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
36dde81
 
07f63a8
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
36dde81
 
 
 
 
 
07f63a8
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
36dde81
07f63a8
 
 
36dde81
07f63a8
36dde81
07f63a8
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
36dde81
07f63a8
 
b0d3e32
 
07f63a8
 
 
36dde81
 
 
 
 
 
 
07f63a8
36dde81
07f63a8
c12bb0b
 
36dde81
 
 
 
 
07f63a8
36dde81
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
07f63a8
 
 
c12bb0b
36dde81
 
 
 
07f63a8
c12bb0b
36dde81
07f63a8
 
 
 
 
36dde81
07f63a8
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
36dde81
07f63a8
 
 
36dde81
 
07f63a8
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
07f63a8
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
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
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
{% extends "base.html" %}
{% block title %}Settings β€” TG Stremio{% endblock %}

{% block content %}

<style>
/* ── Backup & Restore ────────────────────────────────────────────────────── */
.bk-desc { color: var(--text-sec); font-size: 0.85rem; margin-bottom: 1rem; }
.bk-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; }
@media (max-width: 520px) { .bk-actions { grid-template-columns: 1fr; } }
.bk-btn { display: flex; align-items: center; gap: 0.85rem; padding: 0.9rem 1.1rem; border-radius: var(--radius-sm); cursor: pointer;
          text-decoration: none; text-align: left; transition: all .15s;
          border: 1px solid var(--border); background: var(--bg); }
.bk-btn:hover { transform: translateY(-1px); border-color: var(--primary); }
.bk-btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
.bk-ic { width: 2.5rem; height: 2.5rem; border-radius: 0.7rem; display: flex; align-items: center; justify-content: center; font-size: 1.05rem; flex-shrink: 0; }
.bk-export .bk-ic { background: color-mix(in srgb, var(--primary) 18%, transparent); color: var(--primary); }
.bk-import .bk-ic { background: color-mix(in srgb, var(--ok) 13%, transparent); color: var(--ok); }
.bk-txt { display: flex; flex-direction: column; line-height: 1.25; }
.bk-txt b { font-size: 0.95rem; color: var(--text); }
.bk-chips { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 0.9rem; }
.bk-chip { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.72rem; font-weight: 600; padding: 0.35rem 0.75rem; border-radius: 9999px; color: var(--text-sec); border: 1px solid var(--border); background: var(--bg); }
.bk-txt small { font-size: 0.75rem; color: var(--text-sec); }
.bk-status { margin-top: 0.9rem; font-size: 0.85rem; color: var(--text-sec); display: flex; align-items: center; gap: 0.5rem; }
.bk-warn { color: var(--text-sec); font-size: 0.78rem; margin-top: 0.85rem; }
.bk-warn i { color: var(--warning, var(--warn)); }

/* ── Toggle switch ───────────────────────────────────────────────────────── */
.toggle-wrap { display: flex; align-items: center; gap: 0.75rem; cursor: pointer; }
.toggle-input { position: absolute; opacity: 0; width: 0; height: 0; }
.toggle-track {
    display: inline-block; width: 3rem; height: 1.625rem;
    border-radius: 9999px; background: var(--card-high); border: 1px solid var(--border); box-sizing: border-box;
    position: relative; transition: background 0.2s ease; flex-shrink: 0;
}
.toggle-track::after {
    content: ''; position: absolute;
    top: 2px; left: 2px;
    width: 20px; height: 20px;
    border-radius: 50%; background: var(--text-sec);
    transition: transform .25s var(--spring), background-color .2s var(--ease);
}
.toggle-input:checked + .toggle-track { background: var(--primary); }
.toggle-input:checked + .toggle-track { border-color: var(--primary); }
.toggle-input:checked + .toggle-track::after { transform: translateX(1.375rem); background: var(--on-primary); }
.toggle-input:focus-visible + .toggle-track { outline: 2px solid var(--primary); outline-offset: 2px; }
.toggle-label { font-size: 0.9rem; color: var(--text); user-select: none; }

/* ── Section cards ───────────────────────────────────────────────────────── */
.settings-card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 1.35rem 1.5rem; }
.settings-card h2 { font-size: 1.05rem; font-weight: 600; color: var(--text); margin-bottom: 1rem; display: flex; align-items: center; gap: .55rem; }

.settings-card h2 i { color: var(--primary); font-size: .95rem; }
@media (max-width: 640px) { .settings-card { padding: 1.1rem 1rem; } }

/* ── Inputs ──────────────────────────────────────────────────────────────── */
.s-input { width: 100%; background: var(--bg); border: 1px solid var(--border); color: var(--text); border-radius: var(--radius-sm); padding: .65rem 1rem; font-size: .9rem; outline: none; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
.s-input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
.s-label { display: block; font-size: .72rem; font-weight: 500; color: var(--text-sec); text-transform: uppercase; letter-spacing: .1em; margin-bottom: .45rem; }

/* ── Multi-value list ────────────────────────────────────────────────────── */
.multi-list-items { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.6rem; }
.multi-item {
    display: flex; align-items: center; gap: 0.5rem;
}
.multi-item .s-input { flex: 1; }
.channel-chip { flex: 1; min-width: 0; padding: .6rem .9rem; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-sm); font-size: .88rem; font-weight: 500; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; user-select: none; cursor: default; }
.s-input[readonly] {
    opacity: 0.9;
    background: color-mix(in srgb, var(--primary) 8%, transparent);
    cursor: default;
}
.remove-btn { width: 2.25rem; height: 2.25rem; flex-shrink: 0; background: transparent; border: 1px solid var(--border); color: var(--danger); border-radius: 9999px; font-size: .9rem; line-height: 1; cursor: pointer; transition: background-color .15s var(--ease); display: flex; align-items: center; justify-content: center; }
.remove-btn:hover { background: color-mix(in srgb, var(--danger) 25%, transparent); }
.add-row { display: flex; gap: 0.5rem; }
.add-btn { flex-shrink: 0; padding: .6rem 1.05rem; background: transparent; border: 1px solid var(--border); color: var(--text); border-radius: 9999px; font-size: .86rem; font-weight: 500; cursor: pointer; transition: background-color .15s var(--ease); white-space: nowrap; }
.add-btn:hover { background: var(--card-high); }

/* ── Anime channel checkbox ──────────────────────────────────────────────── */
.auth-item .s-input { min-width: 0; }
.anime-check {
    display: inline-flex; align-items: center; gap: 0.35rem; flex-shrink: 0;
    cursor: pointer; user-select: none; white-space: nowrap;
    padding: 0.4rem 0.6rem; border-radius: 0.6rem;
    border: 1px solid var(--border); background: transparent;
    font-size: 0.7rem; font-weight: 600; text-transform: uppercase;
    letter-spacing: 0.03em; color: var(--text-sec); transition: all 0.15s;
}
.anime-check input { width: 0.95rem; height: 0.95rem; accent-color: var(--primary); cursor: pointer; margin: 0; }
.anime-check:hover { border-color: color-mix(in srgb, var(--primary) 35%, transparent); }
.anime-check.is-anime {
    color: var(--primary);
    border-color: color-mix(in srgb, var(--primary) 45%, transparent);
    background: color-mix(in srgb, var(--primary) 12%, transparent);
}

/* ── Grid helpers ────────────────────────────────────────────────────────── */
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
@media (max-width: 640px) { .grid-2 { grid-template-columns: 1fr; } }
.divider { border: none; border-top: 1px solid var(--border); margin: 1.25rem 0; }

/* ── Stats grid ──────────────────────────────────────────────────────────── */
.stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px,1fr)); gap: 0.75rem; }
.stat-box {
    background: var(--bg);
    border: 1px solid var(--border); border-radius: 0.9rem;
    padding: 0.75rem 0.9rem;
}
.stat-box .v { font-size: 1.3rem; font-weight: 600; }
.stat-box .l { font-size: .8rem; color: var(--text-sec); }
.hint { font-size: 0.78rem; color: var(--text-sec); }
</style>

<!-- Page header -->
<div class="page-head">
    <div>
        <h1 class="page-title">Settings</h1>
        <p class="page-sub">Stored in the database. Most changes apply without a restart.</p>
    </div>
    <button id="save-btn" data-shortcut-save onclick="saveSettings()"
        class="btn-primary px-5 py-2.5 text-sm hidden md:inline-flex">
        <i class="fa-solid fa-floppy-disk"></i>
        <span id="save-label">Save Settings</span>
    </button>
</div>

<div class="space-y-6" id="settings-root">

    <!-- ── System & Maintenance ─────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-server"></i> System &amp; Maintenance</h2>

        <!-- DB & system stats -->
        <div class="flex items-center justify-between mb-3 flex-wrap gap-2">
            <label class="s-label" style="margin-bottom:0">Database &amp; System Stats</label>
            <button class="add-btn" type="button" onclick="loadDbStats(this)">
                <i class="fa-solid fa-rotate"></i> Refresh
            </button>
        </div>
        <div class="stat-grid" id="stats-grid">
            <div class="hint" style="grid-column:1/-1"><i class="fa-solid fa-spinner fa-spin"></i> Loading stats…</div>
        </div>

        <hr class="divider">

        <!-- Live logs -->
        <div class="flex items-center justify-between mb-3 flex-wrap gap-2">
            <label class="s-label" style="margin-bottom:0">Logs</label>
            <div class="flex items-center gap-3 flex-wrap">
                <label class="anime-check" title="Auto-refresh the log every 2s">
                    <input type="checkbox" id="log-live-toggle" onchange="toggleLiveLogs()">
                    <span>Live</span>
                </label>
                <button class="add-btn" type="button" onclick="loadLogs(this)">
                    <i class="fa-solid fa-rotate"></i> Refresh
                </button>
                <button class="add-btn" type="button" onclick="window.open('/api/admin/logs/download','_blank')">
                    <i class="fa-solid fa-download"></i> Download
                </button>
            </div>
        </div>
        <pre id="log-view" style="background:color-mix(in srgb,var(--bg) 80%,#000);border:1px solid var(--border);
            border-radius:0.75rem;padding:1rem;font-family:'JetBrains Mono',monospace;font-size:0.75rem;
            line-height:1.5;color:var(--text);max-height:340px;overflow:auto;white-space:pre-wrap;
            word-break:break-word;margin:0">Loading logs…</pre>

        <hr class="divider">

        <!-- Restart -->
        <label class="s-label">Restart App</label>
        <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
            Pulls the latest code from the upstream repo/branch above and restarts the server.
            The web app becomes unreachable for a few seconds β€” this page will reconnect
            automatically once it's back online.
        </p>
        <button id="restart-btn" onclick="restartApp()"
            class="btn-danger px-6 py-2.5 text-sm">
            <i class="fa-solid fa-power-off"></i>
            <span>Restart Now</span>
        </button>
    </div>

    <!-- ── General ─────────────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-sliders"></i> General</h2>
        <div class="space-y-4">
            <label class="toggle-wrap">
                <input type="checkbox" class="toggle-input" id="replace_mode"
                    {% if settings.replace_mode %}checked{% endif %} onchange="toggleDuplicateProtection()">
                <span class="toggle-track"></span>
                <span class="toggle-label">
                    <strong>Replace Mode</strong>
                    <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                        Overwrite existing media entries on re-index
                    </span>
                </span>
            </label>
            <label class="toggle-wrap" id="dup-protect-wrap">
                <input type="checkbox" class="toggle-input" id="duplicate_protection"
                    {% if settings.duplicate_protection %}checked{% endif %}>
                <span class="toggle-track"></span>
                <span class="toggle-label">
                    <strong>Duplicate Protection</strong>
                    <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                        Skip re-indexing a file that already exists (same name &amp; size). Only active when Replace Mode is off.
                    </span>
                </span>
            </label>
            <label class="toggle-wrap">
                <input type="checkbox" class="toggle-input" id="hide_catalog"
                    {% if settings.hide_catalog %}checked{% endif %}>
                <span class="toggle-track"></span>
                <span class="toggle-label">
                    <strong>Hide Catalog</strong>
                    <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                        Hide the public Stremio catalog from unauthenticated users
                    </span>
                </span>
            </label>
        </div>
    </div>

    <!-- ── Authentication ──────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-shield-halved"></i> Admin Authentication</h2>
        <div class="grid-2">
            <div>
                <label class="s-label" for="admin_username">Admin Username</label>
                <input type="text" id="admin_username" class="s-input"
                    value="{{ settings.admin_username }}" autocomplete="off">
            </div>
            <div>
                <label class="s-label" for="admin_password">Admin Password</label>
                <div style="position:relative">
                    <input type="password" id="admin_password" class="s-input"
                        placeholder="Leave blank to keep current password"
                        style="padding-right:2.5rem" autocomplete="new-password">
                    <button type="button" onclick="togglePwdVisibility()"
                        style="position:absolute;right:0.75rem;top:50%;transform:translateY(-50%);
                               background:none;border:none;color:var(--text-sec);cursor:pointer">
                        <i class="fa-solid fa-eye" id="eye-icon"></i>
                    </button>
                </div>
                <p style="font-size:0.75rem;color:var(--text-sec);margin-top:0.3rem">
                    {% if settings.admin_password_set is defined and settings.admin_password_set %}
                        <i class="fa-solid fa-circle-check" style="color:var(--ok)"></i> Password is set
                    {% endif %}
                </p>
            </div>
        </div>

        <div style="margin-top:1rem">
            <label class="s-label" for="session_secret">Session Secret</label>
            <div style="position:relative">
                <input type="password" id="session_secret" class="s-input"
                    placeholder="Leave blank to keep current secret"
                    style="padding-right:2.5rem" autocomplete="new-password">
                <button type="button" onclick="generateSessionSecret()" title="Generate a random secret"
                    style="position:absolute;right:0.75rem;top:50%;transform:translateY(-50%);
                           background:none;border:none;color:var(--text-sec);cursor:pointer">
                    <i class="fa-solid fa-dice"></i>
                </button>
            </div>
            <p style="font-size:0.75rem;color:var(--text-sec);margin-top:0.3rem">
                Signs admin login sessions. Changing it logs out all admins after the next restart.
                {% if settings.session_secret_set is defined and settings.session_secret_set %}
                    <i class="fa-solid fa-circle-check" style="color:var(--ok)"></i> Secret is set
                {% endif %}
            </p>
        </div>

        <hr class="divider">

        <!-- Auth Channels -->
        <label class="s-label">AUTH_CHANNELS
            <span style="font-weight:400;text-transform:none;letter-spacing:0">
                β€” users must be a member of at least one. Tick <strong>Anime</strong> on a
                channel to index its files with Kitsu β†’ TVDB β†’ TMDB β†’ Cinemeta priority.</span>
        </label>
        {% set anime_norm = settings.anime_channels | map('string') | map('replace', '-100', '') | list %}
        {% set titles = settings.channel_titles or {} %}
        <div class="multi-list-items" id="auth_channels_items">
            {% for ch in settings.auth_channels %}
            {% set is_anime = (ch | string | replace('-100', '')) in anime_norm %}
            {% set t = titles.get(ch|string, ch|string) %}
            <div class="multi-item auth-item">
                <span class="channel-chip" data-list="auth_channels" data-id="{{ ch }}" title="{{ ch }}">{{ t }}</span>
                <label class="anime-check {% if is_anime %}is-anime{% endif %}" title="Mark as anime channel β€” uses Kitsu β†’ TVDB β†’ TMDB β†’ Cinemeta">
                    <input type="checkbox" class="anime-toggle" {% if is_anime %}checked{% endif %} onchange="syncAnimeChip(this)">
                    <span>Anime</span>
                </label>
                <button class="remove-btn" onclick="removeItem(this)" title="Remove">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
            {% endfor %}
        </div>
        <div class="add-row">
            <input type="text" id="auth_channels_new" class="s-input"
                placeholder="-100xxxxxxxxxx (channels only)"
                onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('auth_channels')}">
            <button class="add-btn" onclick="addItem('auth_channels')">+ Add Channel</button>
        </div>
    </div>

    <!-- ── Media & Content ─────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-film"></i> Media &amp; Content</h2>
        <div class="grid-2">
            <div>
                <label class="s-label" for="tmdb_api">TMDB API Key</label>
                <input type="text" id="tmdb_api" class="s-input"
                    value="{{ settings.tmdb_api }}" autocomplete="off"
                    placeholder="Your TMDB v3 API key" spellcheck="false">
            </div>
            <div>
                <label class="s-label" for="tvdb_api">TVDB API Key</label>
                <input type="text" id="tvdb_api" class="s-input"
                    value="{{ settings.tvdb_api }}" autocomplete="off"
                    placeholder="TheTVDB v4 API key (series priority)" spellcheck="false">
            </div>
            <div>
                <label class="s-label" for="base_url">Base URL</label>
                <input type="url" id="base_url" class="s-input"
                    value="{{ settings.base_url }}"
                    placeholder="https://your-domain.com">
            </div>
        </div>
        <hr class="divider">
        <div class="grid-2">
            <div>
                <label class="s-label" for="upstream_repo">Upstream Repo</label>
                <input type="text" id="upstream_repo" class="s-input"
                    value="{{ settings.upstream_repo }}"
                    placeholder="https://github.com/user/repo">
            </div>
            <div>
                <label class="s-label" for="upstream_branch">Upstream Branch</label>
                <input type="text" id="upstream_branch" class="s-input"
                    value="{{ settings.upstream_branch }}"
                    placeholder="master">
            </div>
        </div>
    </div>

    <!-- ── Poster Provider ─────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-image"></i> Poster Provider</h2>
        <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
            Replace catalog posters with textless artwork. Only one provider can be active at a time.
        </p>

        <label class="toggle-wrap" style="margin-bottom:0.75rem">
            <input type="checkbox" class="toggle-input" id="better_poster_enabled"
                {% if settings.better_poster_enabled %}checked{% endif %}
                onchange="togglePosterProvider('better')">
            <span class="toggle-track"></span>
            <span class="toggle-label">
                <strong>BetterPoster</strong>
                <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                    Uses btttr.cc. Leave the URL empty for the default variant.
                </span>
            </span>
        </label>
        <div id="better-poster-wrap" style="margin-bottom:1.25rem;{% if not settings.better_poster_enabled %}display:none{% endif %}">
            <label class="s-label" for="better_poster">BetterPoster URL <span style="font-weight:400;text-transform:none">(optional)</span></label>
            <input type="text" id="better_poster" class="s-input"
                value="{{ settings.better_poster }}" autocomplete="off" spellcheck="false"
                placeholder="https://btttr.cc/poster/imdb/poster-default/{imdb_id}.jpg">
        </div>

        <label class="toggle-wrap" style="margin-bottom:0.75rem">
            <input type="checkbox" class="toggle-input" id="rpdb_enabled"
                {% if settings.rpdb_enabled %}checked{% endif %}
                onchange="togglePosterProvider('rpdb')">
            <span class="toggle-track"></span>
            <span class="toggle-label">
                <strong>RPDB</strong>
                <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                    Uses ratingposterdb.com. Leave the API key empty to use the free tier.
                </span>
            </span>
        </label>
        <div id="rpdb-wrap" style="margin-bottom:1.25rem;{% if not settings.rpdb_enabled %}display:none{% endif %}">
            <label class="s-label" for="rpdb_api_key">RPDB API Key <span style="font-weight:400;text-transform:none">(optional)</span></label>
            <input type="text" id="rpdb_api_key" class="s-input"
                value="{{ settings.rpdb_api_key }}" autocomplete="off" spellcheck="false"
                placeholder="Leave empty for free tier (t0-free-rpdb)">
        </div>

        <label class="toggle-wrap" style="margin-bottom:0.75rem">
            <input type="checkbox" class="toggle-input" id="spatial_poster_enabled"
                {% if settings.spatial_poster_enabled %}checked{% endif %}
                onchange="togglePosterProvider('spatial')">
            <span class="toggle-track"></span>
            <span class="toggle-label">
                <strong>SpatialPosters</strong>
                <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                    Your SpatialPosters instance. Paste its Stremio poster URL pattern.
                </span>
            </span>
        </label>
        <div id="spatial-poster-wrap" style="margin-bottom:1.25rem;{% if not settings.spatial_poster_enabled %}display:none{% endif %}">
            <label class="s-label" for="spatial_poster">SpatialPosters URL</label>
            <input type="text" id="spatial_poster" class="s-input"
                value="{{ settings.spatial_poster }}" autocomplete="off" spellcheck="false"
                placeholder="https://your-instance/api/poster/{type}/{imdb_id}?config=...">
        </div>

        <label class="toggle-wrap" style="margin-bottom:0.75rem">
            <input type="checkbox" class="toggle-input" id="fanart_enabled"
                {% if settings.fanart_enabled %}checked{% endif %}
                onchange="togglePosterProvider('fanart')">
            <span class="toggle-track"></span>
            <span class="toggle-label">
                <strong>Fanart.tv</strong>
                <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                    Poster, logo and backdrop from fanart.tv. An API key is required.
                </span>
            </span>
        </label>
        <div id="fanart-wrap" style="{% if not settings.fanart_enabled %}display:none{% endif %}">
            <label class="s-label" for="fanart_api_key">Fanart.tv API Key</label>
            <input type="text" id="fanart_api_key" class="s-input"
                value="{{ settings.fanart_api_key }}" autocomplete="off" spellcheck="false"
                placeholder="Your fanart.tv project API key">
            <label class="toggle-wrap" style="margin-top:0.85rem">
                <input type="checkbox" class="toggle-input" id="fanart_low_res_poster"
                    {% if settings.fanart_low_res_poster %}checked{% endif %}>
                <span class="toggle-track"></span>
                <span class="toggle-label">
                    <strong>Faster artwork</strong>
                    <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                        Low-resolution posters and logos plus medium-resolution backdrops for quicker loading, ideal for phones.
                    </span>
                </span>
            </label>
            <label class="toggle-wrap" style="margin-top:0.85rem">
                <input type="checkbox" class="toggle-input" id="fanart_shuffle"
                    {% if settings.fanart_shuffle %}checked{% endif %}
                    onchange="toggleFanartShuffle()">
                <span class="toggle-track"></span>
                <span class="toggle-label">
                    <strong>Shuffle artwork</strong>
                    <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                        Pick a random English artwork instead of the most liked one. Missing types fall back to the stored artwork.
                    </span>
                </span>
            </label>
            <div id="fanart-shuffle-wrap" style="margin-top:0.85rem;{% if not settings.fanart_shuffle %}display:none{% endif %}">
                <label class="s-label" for="fanart_shuffle_interval">Shuffle interval (minutes)</label>
                <input type="number" id="fanart_shuffle_interval" class="s-input" min="0" step="1"
                    value="{{ settings.fanart_shuffle_interval }}"
                    placeholder="5">
                <span style="color:var(--text-sec);font-size:0.8rem;display:block;margin-top:0.35rem">
                    How often the artwork changes. Use 0 for a fresh random pick on every load.
                </span>
            </div>
        </div>
    </div>

    <!-- ── Stream Formatter ────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-wand-magic-sparkles"></i> Stream Formatter</h2>
        <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
            How each stream's name and description look in Stremio. Uses the AIOStreams template syntax, so
            Prism, Tamtaro and any other community formatter can be pasted into Custom as-is.
            Empty fields are removed automatically.
        </p>
        <label class="s-label" for="stream_formatter">Formatter</label>
        <select id="stream_formatter" class="s-input" onchange="toggleFormatter()">
            {% set fmt = settings.stream_formatter or 'default' %}
            <option value="default" {% if fmt == 'default' %}selected{% endif %}>Default (built-in)</option>
            <option value="prism" {% if fmt == 'prism' %}selected{% endif %}>Prism</option>
            <option value="tamtaro" {% if fmt == 'tamtaro' %}selected{% endif %}>Tamtaro</option>
            <option value="gdrive" {% if fmt == 'gdrive' %}selected{% endif %}>GDrive</option>
            <option value="lightgdrive" {% if fmt == 'lightgdrive' %}selected{% endif %}>Light GDrive</option>
            <option value="minimalisticgdrive" {% if fmt == 'minimalisticgdrive' %}selected{% endif %}>Minimalistic GDrive</option>
            <option value="torrentio" {% if fmt == 'torrentio' %}selected{% endif %}>Torrentio</option>
            <option value="torbox" {% if fmt == 'torbox' %}selected{% endif %}>TorBox</option>
            <option value="custom" {% if fmt == 'custom' %}selected{% endif %}>Custom</option>
        </select>

        <div id="formatter-custom-wrap" style="margin-top:1rem;{% if fmt != 'custom' %}display:none{% endif %}">
            <div class="flex items-center justify-between gap-2" style="margin-bottom:0.4rem">
                <label class="s-label" for="formatter_name" style="margin:0">Name template</label>
                <select id="formatter_copy" class="s-input" style="width:auto;padding:0.3rem 0.6rem;font-size:0.78rem" onchange="copyPreset(this)">
                    <option value="">Start from preset…</option>
                    {% for key in formatter_presets %}<option value="{{ key }}">{{ key }}</option>{% endfor %}
                </select>
            </div>
            <textarea id="formatter_name" class="s-input" rows="3" spellcheck="false"
                style="font-family:monospace;font-size:0.78rem" oninput="schedulePreview()">{{ settings.formatter_name }}</textarea>
            <label class="s-label" for="formatter_description" style="margin-top:0.85rem">Description template</label>
            <textarea id="formatter_description" class="s-input" rows="8" spellcheck="false"
                style="font-family:monospace;font-size:0.78rem" oninput="schedulePreview()">{{ settings.formatter_description }}</textarea>
            <p style="font-size:0.75rem;color:var(--text-sec);margin-top:0.4rem">
                Fields: <code>{stream.resolution}</code> <code>{stream.quality}</code> <code>{stream.encode}</code>
                <code>{stream.visualTags}</code> <code>{stream.audioTags}</code> <code>{stream.audioChannels}</code>
                <code>{stream.languages}</code> <code>{stream.languageEmojis}</code> <code>{stream.size}</code>
                <code>{stream.releaseGroup}</code> <code>{stream.seasonEpisode}</code> <code>{stream.indexer}</code>
                <code>{addon.name}</code> … Wrap optional parts in <code>{?…?}</code> or <code>::exists["…"||""]</code>.
            </p>
        </div>

        <div id="formatter-preview-wrap" style="margin-top:1rem;{% if fmt == 'default' %}display:none{% endif %}">
            <label class="s-label" for="formatter_sample">Preview filename</label>
            <input type="text" id="formatter_sample" class="s-input" spellcheck="false" oninput="schedulePreview()"
                value="Dune.Part.Two.2024.2160p.UHD.BluRay.REMUX.DV.HDR10.HEVC.TrueHD.Atmos.7.1.ITA.ENG-GROUP.mkv">
            <div style="display:flex;gap:0.9rem;margin-top:0.75rem;padding:0.9rem;border-radius:0.8rem;border:1px solid var(--border);background:#0f0f14;color:#e5e5e5;font-size:0.8rem">
                <div id="formatter-preview-name" style="white-space:pre-wrap;font-weight: 600;min-width:6.5rem;max-width:40%"></div>
                <div id="formatter-preview-desc" style="white-space:pre-wrap;min-width:0;overflow-wrap:anywhere"></div>
            </div>
        </div>
    </div>

    <!-- ── Manual Add Channels ─────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-hand-pointer"></i> Manual Add Channels</h2>
        <label class="s-label">MANUAL_CHANNELS
            <span style="font-weight:400;text-transform:none;letter-spacing:0">
                β€” files sent here are <strong>not</strong> auto-indexed with TMDb/IMDb.
                Add them by hand from Media Management by pasting a message link.
                Listing a channel here also cleans up its streams when a file is deleted.</span>
        </label>
        <div class="multi-list-items" id="manual_channels_items">
            {% for ch in settings.manual_channels %}
            {% set t = (settings.channel_titles or {}).get(ch|string, ch|string) %}
            <div class="multi-item">
                <span class="channel-chip" data-list="manual_channels" data-id="{{ ch }}" title="{{ ch }}">{{ t }}</span>
                <button class="remove-btn" onclick="removeItem(this)" title="Remove">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
            {% endfor %}
        </div>
        <div class="add-row">
            <input type="text" id="manual_channels_new" class="s-input"
                placeholder="-100xxxxxxxxxx (channels only)"
                onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('manual_channels')}">
            <button class="add-btn" onclick="addItem('manual_channels')">+ Add Channel</button>
        </div>
    </div>

    <!-- ── Subscription ────────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-credit-card"></i> Subscription</h2>
        <label class="toggle-wrap" style="margin-bottom:1.25rem">
            <input type="checkbox" class="toggle-input" id="subscription"
                {% if settings.subscription %}checked{% endif %}
                onchange="toggleSubFields()">
            <span class="toggle-track"></span>
            <span class="toggle-label">
                <strong>Enable Subscription System</strong>
                <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                    Restrict Stremio access to subscribed members
                </span>
            </span>
        </label>

        <div id="sub-fields" style="{% if not settings.subscription %}display:none{% endif %}">
            <div style="margin-bottom:1rem">
                <label class="s-label" for="subscription_group_id">Subscription Group ID</label>
                <input type="number" id="subscription_group_id" class="s-input"
                    value="{{ settings.subscription_group_id }}"
                    placeholder="-100xxxxxxxx">
                <span style="color:var(--text-sec);font-size:0.78rem;display:block;margin-top:0.4rem">
                    Users are pointed back to your bot automatically for renewals and joining.
                </span>
            </div>

            <!-- Payment method -->
            <div style="margin-bottom:1rem">
                <label class="s-label" for="payment_instructions">Payment Instructions
                    <span style="font-weight:400;text-transform:none;letter-spacing:0">
                        β€” shown to users when they pick a plan (UPI ID, bank details, etc.)</span>
                </label>
                <textarea id="payment_instructions" class="s-input" rows="4"
                    placeholder="e.g. UPI: yourname@okhdfcbank&#10;Or PayPal: you@example.com&#10;After paying, send the screenshot here.">{{ settings.payment_instructions }}</textarea>
            </div>
            <div style="margin-bottom:1rem">
                <label class="s-label" for="payment_qr_url">Payment QR Image URL
                    <span style="font-weight:400;text-transform:none;letter-spacing:0">
                        β€” optional; if set, the bot sends this QR image with the plan</span>
                </label>
                <input type="url" id="payment_qr_url" class="s-input"
                    value="{{ settings.payment_qr_url }}"
                    placeholder="https://.../upi-qr.png">
            </div>

            <!-- Approver IDs -->
            <label class="s-label">APPROVER_IDS
                <span style="font-weight:400;text-transform:none;letter-spacing:0">
                    β€” Telegram user IDs allowed to approve subscriptions</span>
            </label>
            <div class="multi-list-items" id="approver_ids_items">
                {% for uid in settings.approver_ids %}
                <div class="multi-item">
                    <input type="number" class="s-input" value="{{ uid }}" data-list="approver_ids">
                    <button class="remove-btn" onclick="removeItem(this)" title="Remove">
                        <i class="fa-solid fa-xmark"></i>
                    </button>
                </div>
                {% endfor %}
            </div>
            <div class="add-row">
                <input type="number" id="approver_ids_new" class="s-input"
                    placeholder="Telegram user ID (numeric)"
                    onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('approver_ids')}">
                <button class="add-btn" onclick="addItem('approver_ids')">+ Add Approver</button>
            </div>
        </div>
    </div>




<!-- ── Telegram User Session ──────────────────────────────────────── -->
<div class="settings-card">
    <h2><i class="fa-solid fa-user-lock"></i> Telegram User Session</h2>
    <p class="bk-desc">
        Log in with your phone number to generate the User Session automatically β€” no manual
        session string needed. It's encrypted and stored securely, and powers Global Search.
    </p>

    <div id="sess-loading" style="color:var(--text-sec);font-size:0.85rem">
        <i class="fa-solid fa-spinner fa-spin"></i> Checking session…
    </div>

    <!-- Connected view -->
    <div id="sess-connected" style="display:none">
        <div class="sess-profile">
            <div class="sess-avatar"><i class="fa-solid fa-user-astronaut"></i></div>
            <div style="min-width:0;flex:1">
                <div class="flex items-center gap-2 flex-wrap">
                    <span id="sess-name" style="font-weight: 600"></span>
                    <span id="sess-live" class="sess-pill"></span>
                </div>
                <div id="sess-username" style="color:var(--text-sec);font-size:0.82rem"></div>
            </div>
        </div>
        <div class="sess-grid">
            <div><span class="sess-k">Phone</span><span id="sess-phone" class="sess-v">β€”</span></div>
            <div><span class="sess-k">Telegram ID</span><span id="sess-id" class="sess-v">β€”</span></div>
        </div>
        <div class="flex flex-wrap gap-2 mt-4">
            <button type="button" class="sess-btn" onclick="sessAction('reconnect')"><i class="fa-solid fa-rotate"></i> Reconnect</button>
            <button type="button" class="sess-btn warn" onclick="sessAction('disconnect')"><i class="fa-solid fa-plug-circle-xmark"></i> Disconnect</button>
            <button type="button" class="sess-btn danger" onclick="sessRemove()"><i class="fa-solid fa-trash"></i> Remove</button>
        </div>
    </div>

    <!-- Login flow -->
    <div id="sess-login" style="display:none">
        <div id="sess-step-phone">
            <label class="s-label">Phone number (with country code)</label>
            <div class="flex flex-col sm:flex-row gap-2">
                <input id="sess-phone-input" class="s-input" placeholder="+12025550123" style="flex:1">
                <button type="button" class="sess-btn primary" onclick="sessSendCode()"><i class="fa-solid fa-paper-plane"></i> Send code</button>
            </div>
        </div>
        <div id="sess-step-code" style="display:none;margin-top:0.85rem">
            <label class="s-label">Login code (sent on Telegram)</label>
            <div class="flex flex-col sm:flex-row gap-2">
                <input id="sess-code-input" class="s-input" inputmode="numeric" placeholder="1 2 3 4 5" style="flex:1">
                <button type="button" class="sess-btn primary" onclick="sessVerifyCode()"><i class="fa-solid fa-check"></i> Verify</button>
            </div>
        </div>
        <div id="sess-step-pass" style="display:none;margin-top:0.85rem">
            <label class="s-label">Two-step verification password</label>
            <div class="flex flex-col sm:flex-row gap-2">
                <input id="sess-pass-input" type="password" class="s-input" placeholder="Your 2FA password" style="flex:1">
                <button type="button" class="sess-btn primary" onclick="sessVerifyPassword()"><i class="fa-solid fa-lock-open"></i> Confirm</button>
            </div>
        </div>
        <p id="sess-msg" style="font-size:0.8rem;margin-top:0.7rem;display:none"></p>
    </div>

    {% if userbot_configured %}
    <hr class="divider">
    <label class="toggle-wrap">
        <input type="checkbox" class="toggle-input" id="default_streaming"
            {% if settings.default_streaming == 'userbot' %}checked{% endif %}>
        <span class="toggle-track"></span>
        <span class="toggle-label">
            <strong>Default Streaming: Userbot</strong>
            <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                Off streams library files by Bots (default). On streams them by the Userbot, falling back to Bots on error.
                Global Search files always use the Userbot.
            </span>
        </span>
    </label>
    {% endif %}
</div>

<style>
.sess-profile { display:flex; align-items:center; gap:0.9rem; padding:1rem; border-radius:0.9rem; border:1px solid var(--border); background:color-mix(in srgb,var(--card) 90%,var(--bg)); }
.sess-avatar { width:3rem; height:3rem; border-radius:9999px; display:flex; align-items:center; justify-content:center; font-size:1.2rem; background:color-mix(in srgb,var(--primary) 18%,transparent); color:var(--primary); flex-shrink:0; }
.sess-grid { display:grid; grid-template-columns:1fr 1fr; gap:0.75rem; margin-top:0.85rem; }
@media (max-width:520px){ .sess-grid { grid-template-columns:1fr; } }
.sess-grid > div { padding:0.7rem 0.9rem; border-radius:0.8rem; border:1px solid var(--border); background:color-mix(in srgb,var(--card) 92%,var(--bg)); }
.sess-k { display:block; font-size:0.68rem; text-transform:uppercase; letter-spacing:0.05em; color:var(--text-sec); font-weight: 600; }
.sess-v { display:block; font-weight: 600; margin-top:0.2rem; word-break:break-all; }
.sess-pill { font-size:0.62rem; font-weight: 600; text-transform:uppercase; letter-spacing:0.05em; padding:0.15rem 0.55rem; border-radius:9999px; }
.sess-pill.on { background:color-mix(in srgb, var(--ok) 13%, transparent); color:var(--ok); }
.sess-pill.off { background:color-mix(in srgb, var(--warn) 13%, transparent); color:var(--warn); }
.sess-btn { display:inline-flex; align-items:center; gap:0.5rem; padding:0.6rem 1.1rem; border-radius:9999px; font-weight: 600; font-size:0.82rem; cursor:pointer; border:1px solid var(--border); background:color-mix(in srgb,var(--card) 92%,var(--bg)); color:var(--text); transition:all .15s; }
.sess-btn:hover { border-color:var(--primary); }
.sess-btn.primary { background:var(--primary); color:#fff; border-color:transparent; }
.sess-btn.warn { color:var(--warn); }
.sess-btn.danger { color:var(--danger); }
</style>

<script>
let sessLoginId = null;

async function sessLoadStatus() {
    try {
        const res = await fetch('/api/admin/settings/session');
        const data = await res.json();
        document.getElementById('sess-loading').style.display = 'none';
        if (data.connected && data.profile) {
            const p = data.profile;
            document.getElementById('sess-name').textContent = p.name || 'Telegram User';
            document.getElementById('sess-username').textContent = p.username ? '@' + p.username : 'No username';
            document.getElementById('sess-phone').textContent = p.phone || 'β€”';
            document.getElementById('sess-id').textContent = p.user_id || 'β€”';
            const live = document.getElementById('sess-live');
            live.className = 'sess-pill ' + (data.live ? 'on' : 'off');
            live.textContent = data.live ? 'Connected' : 'Stored (restart to activate)';
            document.getElementById('sess-connected').style.display = '';
            document.getElementById('sess-login').style.display = 'none';
        } else {
            document.getElementById('sess-connected').style.display = 'none';
            document.getElementById('sess-login').style.display = '';
            sessShowStep('phone');
        }
    } catch (e) {
        document.getElementById('sess-loading').textContent = 'Unable to load session status.';
    }
}

function sessShowStep(step) {
    document.getElementById('sess-step-phone').style.display = step === 'phone' ? '' : 'none';
    document.getElementById('sess-step-code').style.display = step === 'code' ? '' : 'none';
    document.getElementById('sess-step-pass').style.display = step === 'pass' ? '' : 'none';
}

function sessMsg(text, ok) {
    const el = document.getElementById('sess-msg');
    el.style.display = '';
    el.style.color = ok ? 'var(--ok)' : 'var(--danger)';
    el.textContent = text;
}

async function sessSendCode() {
    const phone = document.getElementById('sess-phone-input').value.trim();
    if (!phone) return sessMsg('Enter your phone number.', false);
    sessMsg('Sending code…', true);
    try {
        const res = await fetch('/api/admin/settings/session/send-code', {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ phone })
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Failed to send code');
        sessLoginId = data.login_id;
        sessShowStep('code');
        sessMsg('Code sent. Check your Telegram app.', true);
    } catch (e) { sessMsg(e.message, false); }
}

async function sessVerifyCode() {
    const code = document.getElementById('sess-code-input').value.trim();
    if (!code) return sessMsg('Enter the login code.', false);
    sessMsg('Verifying…', true);
    try {
        const res = await fetch('/api/admin/settings/session/verify-code', {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ login_id: sessLoginId, code })
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Verification failed');
        if (data.status === 'password_needed') {
            sessShowStep('pass');
            sessMsg('This account has two-step verification. Enter your password.', true);
            return;
        }
        showToast('Session created successfully.', 'success', 'Telegram');
        sessLoadStatus();
    } catch (e) { sessMsg(e.message, false); }
}

async function sessVerifyPassword() {
    const password = document.getElementById('sess-pass-input').value;
    if (!password) return sessMsg('Enter your 2FA password.', false);
    sessMsg('Confirming…', true);
    try {
        const res = await fetch('/api/admin/settings/session/verify-password', {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ login_id: sessLoginId, password })
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Verification failed');
        showToast('Session created successfully.', 'success', 'Telegram');
        sessLoadStatus();
    } catch (e) { sessMsg(e.message, false); }
}

async function sessAction(kind) {
    try {
        const res = await fetch('/api/admin/settings/session/' + kind, { method: 'POST' });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Action failed');
        showToast(kind === 'reconnect' ? 'Reconnected.' : 'Disconnected.', 'info', 'Telegram');
        sessLoadStatus();
    } catch (e) { showToast(e.message, 'error', 'Telegram'); }
}

async function sessRemove() {
    if (!confirm('Remove the stored Telegram session? Global Search will stop working until you log in again.')) return;
    try {
        const res = await fetch('/api/admin/settings/session', { method: 'DELETE' });
        if (!res.ok) throw new Error();
        showToast('Session removed.', 'info', 'Telegram');
        sessLoadStatus();
    } catch (e) { showToast('Failed to remove session.', 'error', 'Telegram'); }
}

document.addEventListener('DOMContentLoaded', sessLoadStatus);
</script>


<!-- ── Global Search (Userbot) ────────────────────────────────────── -->
<div class="settings-card">
    <h2><i class="fa-solid fa-globe"></i> Global Search</h2>

    <label class="toggle-wrap" style="{% if not userbot_configured %}opacity:0.5{% endif %}">
        <input type="checkbox" class="toggle-input" id="global_search"
            {% if settings.global_search %}checked{% endif %}
            {% if not userbot_configured %}disabled{% endif %}
            onchange="toggleGlobalSearchFields()">
        <span class="toggle-track"></span>
        <span class="toggle-label">
            <strong>Enable Global Search</strong>
            <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                Search media <strong>only in the channels listed below</strong>.
                Results are tagged <strong>GLOBAL</strong> in the stream list
                for items not in your local catalog.
            </span>
        </span>
    </label>

    {% if not userbot_configured %}
    <p style="color:var(--text-sec);font-size:0.8rem;margin-top:0.75rem">
        <i class="fa-solid fa-circle-info"></i>
        Connect your <strong>Telegram User Session</strong> above to unlock Global Search.
    </p>
    {% endif %}

    <div id="global-search-fields"
         style="{% if not settings.global_search %}display:none{% endif %}">

        <hr class="divider">

        <div id="global-search-channels-wrap"
             style="{% if not userbot_configured %}opacity:0.5;pointer-events:none{% endif %}">

            <label class="s-label">
                GLOBAL SEARCH CHANNELS
                <span style="font-weight:400;text-transform:none;letter-spacing:0">
                    β€” optional. If set, search is restricted to these channels. If empty, searches all channels globally (faster).
                </span>
            </label>

            <p style="font-size:0.78rem;color:var(--text-sec);margin-bottom:0.75rem">
                <i class="fa-solid fa-circle-info"
                   style="color:var(--info,var(--info))"></i>
                Leave empty to search globally across all channels the account can see.
                Otherwise enter channel IDs in <code>-100xxxxxxxxxx</code> format only.
            </p>

            <div class="multi-list-items" id="global_search_channels_items">
                {% for ch in settings.global_search_channels %}
                {% set t = (settings.channel_titles or {}).get(ch|string, ch|string) %}
                <div class="multi-item">
                    <span class="channel-chip" data-list="global_search_channels" data-id="{{ ch }}" title="{{ ch }}">{{ t }}</span>
                    <button class="remove-btn"
                            onclick="removeItem(this)"
                            title="Remove">
                        <i class="fa-solid fa-xmark"></i>
                    </button>
                </div>
                {% endfor %}
            </div>

            <div class="add-row">
                <input type="text"
                       id="global_search_channels_new"
                       class="s-input"
                       placeholder="-100xxxxxxxxxx (channels only)"
                       onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('global_search_channels')}">

                <button class="add-btn"
                        onclick="addItem('global_search_channels')">
                    + Add Channel
                </button>
            </div>

        </div>
    </div>
</div>




<!-- ── New Content Announcements ──────────────────────────────────── -->
<div class="settings-card">
    <h2><i class="fa-solid fa-bullhorn"></i> New Content Announcements</h2>

    <label class="toggle-wrap">
        <input type="checkbox" class="toggle-input" id="announce_new_content"
            {% if settings.announce_new_content %}checked{% endif %}
            onchange="toggleAnnouncementFields()">
        <span class="toggle-track"></span>
        <span class="toggle-label">
            <strong>Announce New Titles</strong>
            <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                Auto-post a poster card to a Telegram channel the first time a
                new movie or series is added. Each title is announced only once.
            </span>
        </span>
    </label>

    <div id="announcement-fields"
         style="{% if not settings.announce_new_content %}display:none{% endif %}">
        <hr class="divider">
        <label class="s-label" for="announcement_channel">ANNOUNCEMENT CHANNEL</label>
        <p style="font-size:0.78rem;color:var(--text-sec);margin-bottom:0.75rem">
            <i class="fa-solid fa-circle-info"></i>
            Channel ID only in <code>-100xxxxxxxxxx</code> format (channels only).
            The bot must be an <strong>admin</strong> in that channel.
        </p>
        <div class="multi-item" style="margin-top:0.25rem">
            {% set ac_t = (settings.channel_titles or {}).get(settings.announcement_channel|string, settings.announcement_channel) %}
            <input type="text" id="announcement_channel" class="s-input"
                value="{{ ac_t if settings.announcement_channel else '' }}"
                data-id="{{ settings.announcement_channel }}"
                {% if settings.announcement_channel %}readonly{% endif %}
                placeholder="-100xxxxxxxxxx (channels only)"
                oninput="if(!this.readOnly){this.dataset.id='';}">
            <button type="button" class="remove-btn" id="announcement_channel_clear"
                style="{% if not settings.announcement_channel %}display:none{% endif %}"
                onclick="clearSingleChannel('announcement_channel')" title="Remove">
                <i class="fa-solid fa-xmark"></i>
            </button>
        </div>
    </div>
</div>


    <!-- ── Skip Channel (metadata failures) ────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-inbox"></i> Skip Channel</h2>
        <label class="s-label" for="skip_channel">SKIP CHANNEL
            <span style="font-weight:400;text-transform:none;letter-spacing:0">
                β€” when a file forwarded to an auth channel fails to index (title, quality or a
                match is missing/wrong), the bot copies it here with a note describing what to fix.
                Files sent to this channel are <strong>not</strong> indexed. Only one channel is
                allowed and the bot must be an <strong>admin</strong> here.</span>
        </label>
        <div class="multi-item" style="margin-top:0.25rem">
            {% set sc_t = (settings.channel_titles or {}).get(settings.skip_channel|string, settings.skip_channel) %}
            <input type="text" id="skip_channel" class="s-input"
                value="{{ sc_t if settings.skip_channel else '' }}"
                data-id="{{ settings.skip_channel }}"
                {% if settings.skip_channel %}readonly{% endif %}
                placeholder="-100xxxxxxxxxx (channels only)"
                oninput="if(!this.readOnly){this.dataset.id='';toggleSkipDeleteField();}">
            <button type="button" class="remove-btn" id="skip_channel_clear"
                style="{% if not settings.skip_channel %}display:none{% endif %}"
                onclick="clearSingleChannel('skip_channel')" title="Remove">
                <i class="fa-solid fa-xmark"></i>
            </button>
        </div>

        <label class="toggle-wrap" id="delete_on_metadata_fail_wrap" style="margin-top:1.25rem;{% if not settings.skip_channel %}display:none{% endif %}">
            <input type="checkbox" class="toggle-input" id="delete_on_metadata_fail"
                {% if settings.delete_on_metadata_fail %}checked{% endif %}>
            <span class="toggle-track"></span>
            <span class="toggle-label">
                <strong>Delete original on metadata fail</strong>
                <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                    After a failed file is copied to the skip channel, remove it from the main channel.
                </span>
            </span>
        </label>
    </div>

    <!-- ── Proxy ───────────────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-network-wired"></i> Proxy Settings</h2>
        <div style="margin-bottom:1rem">
            <label class="s-label" for="http_proxy_url">HTTP Proxy URL</label>
            <input type="url" id="http_proxy_url" class="s-input"
                value="{{ settings.http_proxy_url }}"
                placeholder="http://user:pass@host:port or leave empty"
                oninput="toggleMediaflowFields()">
        </div>

        <div id="mediaflow-wrap" style="{% if not settings.http_proxy_url %}display:none{% endif %}">
            <label class="toggle-wrap" style="margin-bottom:1rem">
                <input type="checkbox" class="toggle-input" id="mediaflow_proxy"
                    {% if settings.mediaflow_proxy %}checked{% endif %}
                    onchange="toggleMediaflowFields()">
                <span class="toggle-track"></span>
                <span class="toggle-label">
                    <strong>MediaFlow Proxy</strong>
                    <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                        Wrap streams as <code>/proxy/stream?d=&lt;url&gt;&amp;api_password=&lt;pass&gt;</code>
                    </span>
                </span>
            </label>
            <div id="mediaflow-password-wrap"
                 style="margin-bottom:1rem;{% if not settings.mediaflow_proxy %}display:none{% endif %}">
                <label class="s-label" for="mediaflow_password">MediaFlow API Password</label>
                <div style="position:relative">
                    <input type="password" id="mediaflow_password" class="s-input"
                        value="{{ settings.mediaflow_password }}"
                        placeholder="api_password" style="padding-right:2.5rem"
                        autocomplete="off" spellcheck="false">
                    <button type="button" onclick="toggleMfPwdVisibility()"
                        style="position:absolute;right:0.75rem;top:50%;transform:translateY(-50%);
                               background:none;border:none;color:var(--text-sec);cursor:pointer">
                        <i class="fa-solid fa-eye" id="mf-eye-icon"></i>
                    </button>
                </div>
            </div>
        </div>

        <label class="toggle-wrap">
            <input type="checkbox" class="toggle-input" id="show_proxy_and_non_proxy_both"
                {% if settings.show_proxy_and_non_proxy_both %}checked{% endif %}>
            <span class="toggle-track"></span>
            <span class="toggle-label">
                <strong>Show Proxy &amp; Non-Proxy Streams</strong>
                <span style="color:var(--text-sec);font-size:0.8rem;display:block">
                    Expose both proxied and direct stream links in Stremio
                </span>
            </span>
        </label>
    </div>


    <!-- ── Cloudflare Streaming ────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-brands fa-cloudflare"></i> Cloudflare Streaming</h2>
        <p style="font-size:0.8rem;color:var(--text-sec);margin:-0.25rem 0 1rem">
            Stream video from a Cloudflare streaming Worker instead of this server. Catalogs, tokens and
            limits stay here; the Worker reports each token's usage back. Enter the URL and secret you were given.
        </p>
        <a href="https://proxy.weebzonex.workers.dev" target="_blank" rel="noopener" class="add-btn" style="display:inline-flex;align-items:center;gap:.5rem;margin-bottom:1rem;text-decoration:none">
            <i class="fa-solid fa-bolt"></i> Get Cloudflare streaming
        </a>
        <p style="font-size:0.75rem;color:var(--text-sec);margin:-0.5rem 0 1rem">
            Recommended on free hosts (Koyeb, Render, orkestr): video then streams fast from Cloudflare instead of a slow, sleeping free server.
            After buying, you get the Worker URL and secret on Telegram.
        </p>
        <div style="margin-bottom:1rem">
            <label class="s-label" for="cf_stream_url">Worker URL</label>
            <input type="url" id="cf_stream_url" class="s-input"
                value="{{ settings.cf_stream_url }}"
                placeholder="https://telestream.your-name.workers.dev">
        </div>
        <div style="margin-bottom:1rem">
            <label class="s-label" for="cf_stream_secret">Shared Secret</label>
            <input type="password" id="cf_stream_secret" class="s-input"
                value="{{ settings.cf_stream_secret }}"
                placeholder="The secret that came with your Worker URL"
                autocomplete="off" spellcheck="false">
        </div>
        <div>
            <label class="s-label" for="cf_stream_mode">Stremio Links</label>
            <select id="cf_stream_mode" class="s-input">
                <option value="off" {% if settings.cf_stream_mode == "off" %}selected{% endif %}>Off β€” stream from this server</option>
                <option value="cloudflare" {% if settings.cf_stream_mode == "cloudflare" %}selected{% endif %}>Cloudflare only</option>
                <option value="both" {% if settings.cf_stream_mode == "both" %}selected{% endif %}>Both β€” Cloudflare and direct</option>
            </select>
        </div>
    </div>
    
    <!-- ── WebDAV ──────────────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-hard-drive"></i> WebDAV</h2>
        <p style="font-size:0.82rem;color:var(--text-sec);margin-bottom:1rem">
            Expose your library as a virtual filesystem.
            URL: <code id="webdav-url-hint">/webdav/&lt;API_TOKEN&gt;/</code>
            Use any valid Stremio API token in the path. Optional Basic auth below.
        </p>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4" style="margin-bottom:1rem">
            <div>
                <label class="s-label" for="webdav_user">WebDAV Username</label>
                <input type="text" id="webdav_user" class="s-input"
                    value="{{ settings.webdav_user | default('', true) }}"
                    placeholder="Leave empty to disable Basic auth"
                    autocomplete="off" spellcheck="false">
            </div>
            <div>
                <label class="s-label" for="webdav_password">WebDAV Password</label>
                <div style="position:relative">
                    <input type="password" id="webdav_password" class="s-input"
                        value="{{ settings.webdav_password | default('', true) }}"
                        placeholder="Optional"
                        style="padding-right:2.5rem"
                        autocomplete="off" spellcheck="false">
                    <button type="button" onclick="toggleWebdavPwdVisibility()"
                        style="position:absolute;right:0.75rem;top:50%;transform:translateY(-50%);
                               background:none;border:none;color:var(--text-sec);cursor:pointer">
                        <i class="fa-solid fa-eye" id="webdav-eye-icon"></i>
                    </button>
                </div>
            </div>
        </div>
        <p style="font-size:0.78rem;color:var(--text-sec)">
            <i class="fa-solid fa-circle-info"></i>
            Movies: <code>/webdav/TOKEN/Movies/</code> Β·
            TV: <code>/webdav/TOKEN/TV Shows/</code> Β·
            NFO files are generated automatically.
        </p>
    </div>

<!-- ── Databases ────────────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-database"></i> Databases</h2>
        <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
            Tracking and Storage 1 are required to boot the app and can't be edited
            here. Additional storage databases connect/disconnect instantly when
            saved β€” no restart needed. For data-safety reasons you can only
            <strong>append</strong> new databases or <strong>remove from the end</strong>
            of the list β€” editing or deleting one in the middle is rejected on save,
            since existing media documents reference databases by position.
        </p>

        <!-- Locked databases (rendered from db.get_database_list()) -->
        <div class="space-y-2 mb-4">
            {% for entry in settings.database_list %}
                {% if entry.locked %}
                <div class="multi-item" style="opacity:0.65">
                    <input type="text" class="s-input" value="{{ entry.uri_masked }}" disabled
                        style="cursor:not-allowed">
                    <span style="flex-shrink:0;font-size:0.7rem;font-weight: 600;text-transform:uppercase;
                                 padding:0.4rem 0.7rem;border-radius:0.5rem;
                                 background:color-mix(in srgb,var(--text-sec) 15%,transparent);
                                 color:var(--text-sec);white-space:nowrap">
                        <i class="fa-solid fa-lock"></i>
                        {{ "Tracking" if entry.type == "tracking" else "Storage 1" }}
                    </span>
                </div>
                {% endif %}
            {% endfor %}
        </div>

        <hr class="divider">

        <label class="s-label">EXTRA STORAGE DATABASES
            <span style="font-weight:400;text-transform:none;letter-spacing:0">
                β€” additional Mongo URIs for media storage rotation</span>
        </label>
        <div class="multi-list-items" id="extra_databases_items">
            {% for entry in settings.database_list %}
                {% if not entry.locked %}
                <div class="multi-item">
                    <input type="text" class="s-input" value="{{ entry.full_uri }}" spellcheck="false"
                        data-list="extra_databases" placeholder="mongodb+srv://user:pass@host/...">
                    <span title="{{ 'Connected' if entry.connected else 'Disconnected' }}"
                        style="flex-shrink:0;width:0.6rem;height:0.6rem;border-radius:50%;
                               background:{{ 'var(--ok)' if entry.connected else 'var(--danger)' }}"></span>
                    <button class="remove-btn" onclick="removeItem(this)" title="Remove (only safe from the end of the list)">
                        <i class="fa-solid fa-xmark"></i>
                    </button>
                </div>
                {% endif %}
            {% endfor %}
        </div>
        <div class="add-row">
            <input type="text" id="extra_databases_new" class="s-input" spellcheck="false"
                placeholder="mongodb+srv://user:pass@host/..."
                onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('extra_databases')}">
            <button class="add-btn" onclick="addItem('extra_databases')">+ Add Database</button>
        </div>
    </div>

    <!-- ── Multi-Token Clients ─────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-brands fa-telegram"></i> Multi-Token Clients</h2>
        <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
            Additional bot tokens used for parallel streaming. Changes reinitialise
            the client pool immediately (no restart needed).
        </p>
        <div class="multi-list-items" id="multi_tokens_items">
            {% for tok in settings.multi_tokens %}
            <div class="multi-item">
                <input type="text" class="s-input" value="{{ tok }}" spellcheck="false"
                    data-list="multi_tokens" placeholder="Bot token">
                <button class="remove-btn" onclick="removeItem(this)" title="Remove">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
            {% endfor %}
        </div>
        <div class="add-row">
            <input type="text" id="multi_tokens_new" class="s-input" spellcheck="false"
                placeholder="New bot token (1234567890:ABCdef…)"
                onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('multi_tokens')}">
            <button class="add-btn" onclick="addItem('multi_tokens')">+ Add Token</button>
        </div>
    </div>

    <!-- ── Helper Bots ─────────────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-brands fa-telegram"></i> Helper Bots</h2>
        <p style="font-size:0.83rem;color:var(--text-sec);margin-bottom:1rem">
            Bots that copy files into users' own channels. Add them as admins in your storage channels.
            Users can add their own bots from the addon page only while at least one helper bot is set.
        </p>
        <div class="multi-list-items" id="helper_tokens_items">
            {% for tok in settings.helper_tokens %}
            <div class="multi-item">
                <input type="text" class="s-input" value="{{ tok }}" spellcheck="false"
                    data-list="helper_tokens" placeholder="Bot token">
                <button class="remove-btn" onclick="removeItem(this)" title="Remove">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
            {% endfor %}
        </div>
        <div class="add-row">
            <input type="text" id="helper_tokens_new" class="s-input" spellcheck="false"
                placeholder="New bot token (1234567890:ABCdef…)"
                onkeydown="if(event.key==='Enter'){event.preventDefault();addItem('helper_tokens')}">
            <button class="add-btn" onclick="addItem('helper_tokens')">+ Add Token</button>
        </div>
    </div>

    <!-- ── Backup & Restore ───────────────────────────────────────────── -->
    <div class="settings-card">
        <h2><i class="fa-solid fa-box-archive"></i> Backup &amp; Restore</h2>
        <p class="bk-desc">
            Export everything β€” settings, custom catalogs, subscription plans and access tokens β€” to a JSON file,
            or restore from one. Passwords and the session secret are never exported, but the file can hold bot
            tokens and database URIs, so keep it private.
        </p>

        <div class="bk-actions">
            <a href="/api/admin/backup/export" class="bk-btn bk-export" download>
                <span class="bk-ic"><i class="fa-solid fa-cloud-arrow-down"></i></span>
                <span class="bk-txt"><b>Export</b><small>Download backup</small></span>
            </a>
            <input type="file" id="restore-file" accept="application/json,.json" style="display:none" onchange="restoreBackup(this)">
            <button type="button" id="restore-btn" class="bk-btn bk-import"
                    onclick="document.getElementById('restore-file').click()">
                <span class="bk-ic"><i class="fa-solid fa-cloud-arrow-up"></i></span>
                <span class="bk-txt"><b>Import</b><small>Restore from file</small></span>
            </button>
            <a href="/api/admin/backup/library" class="bk-btn bk-export" style="grid-column:1/-1" download>
                <span class="bk-ic"><i class="fa-solid fa-mobile-screen-button"></i></span>
                <span class="bk-txt"><b>Library for TeleStremio</b><small>Movies, series &amp; channels</small></span>
            </a>
        </div>

        <div id="restore-status" class="bk-status" style="display:none"></div>

        <div class="bk-chips">
            <span class="bk-chip"><i class="fa-solid fa-gear"></i> Settings</span>
            <span class="bk-chip"><i class="fa-solid fa-layer-group"></i> Custom catalogs</span>
            <span class="bk-chip"><i class="fa-solid fa-credit-card"></i> Plans</span>
            <span class="bk-chip"><i class="fa-solid fa-key"></i> Access tokens</span>
        </div>

        <p class="bk-warn">
            <i class="fa-solid fa-triangle-exclamation"></i>
            Restoring replaces your catalogs, plans and tokens, and reconnects extra databases and bot tokens from the file.
            The TeleStremio library file is restored in TeleStremio under Settings β†’ Backup β†’ Import file, and replaces the library there.
        </p>
    </div>

    <div class="settings-card" id="contributors-card">
        <div class="flex items-center justify-between flex-wrap gap-2" style="margin-bottom:.35rem">
            <h2 style="margin-bottom:0"><i class="fa-solid fa-people-group"></i> Contributors</h2>
            <a href="https://github.com/weebzone/Telegram-Stremio/graphs/contributors" target="_blank" rel="noopener" class="text-sm" style="color:var(--primary)">View on GitHub <i class="fa-solid fa-arrow-up-right-from-square text-xs"></i></a>
        </div>
        <p class="hint" style="margin-bottom:1rem">The people who build Telegram Stremio. Updated live from GitHub.</p>
        <div id="contributors" class="contrib-grid" aria-live="polite">
            <div class="contrib-skel"></div><div class="contrib-skel"></div><div class="contrib-skel"></div>
        </div>
    </div>

</div><!-- /settings-root -->

<style>
.contrib-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(150px, 100%), 1fr)); gap: .6rem; }
.contrib { display: flex; align-items: center; gap: .7rem; padding: .6rem .75rem; border-radius: var(--radius-sm); background: var(--bg); border: 1px solid var(--border); color: var(--text); text-decoration: none; min-width: 0; transition: border-color .15s var(--ease), transform .15s var(--ease); }
.contrib:hover { border-color: color-mix(in srgb, var(--primary) 45%, var(--border)); transform: translateY(-1px); }
.contrib img { width: 36px; height: 36px; border-radius: 99px; flex-shrink: 0; background: var(--card-high); }
.contrib b { display: block; font-weight: 500; font-size: .9rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.contrib small { color: var(--text-sec); font-size: .78rem; }
.contrib-skel { height: 58px; border-radius: var(--radius-sm); border: 1px solid var(--border); background: linear-gradient(90deg, var(--bg) 25%, var(--card-high) 37%, var(--bg) 63%); background-size: 400% 100%; animation: contrib-sh 1.4s ease infinite; }
@keyframes contrib-sh { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
</style>
<script>
document.addEventListener('DOMContentLoaded', async function contributors() {
    const box = document.getElementById('contributors');
    if (!box) return;
    const KEY = 'tgs-contributors', TTL = 6 * 3600 * 1000;
    const render = list => {
        box.innerHTML = list.length ? list.map(c => `
            <a class="contrib" href="${escapeHtml(c.html_url)}" target="_blank" rel="noopener">
                <img src="${escapeHtml(c.avatar_url)}&s=72" alt="" loading="lazy" width="36" height="36">
                <span class="min-w-0"><b>${escapeHtml(c.login)}</b><small>${c.contributions} commit${c.contributions === 1 ? '' : 's'}</small></span>
            </a>`).join('') : '<p class="hint">No contributors to show yet.</p>';
    };
    let cached = null;
    try { cached = JSON.parse(localStorage.getItem(KEY)); } catch (e) {}
    if (cached?.list) render(cached.list);
    if (cached && Date.now() - cached.at < TTL) return;
    try {
        const res = await fetch('https://api.github.com/repos/weebzone/Telegram-Stremio/contributors?per_page=100', { headers: { Accept: 'application/vnd.github+json' } });
        if (!res.ok) throw new Error(res.status);
        const list = (await res.json()).filter(c => c.type !== 'Bot').map(({ login, avatar_url, html_url, contributions }) => ({ login, avatar_url, html_url, contributions }));
        render(list);
        try { localStorage.setItem(KEY, JSON.stringify({ at: Date.now(), list })); } catch (e) {}
    } catch (e) {
        if (!cached?.list) box.innerHTML = '<p class="hint">GitHub could not be reached right now. <a href="https://github.com/weebzone/Telegram-Stremio/graphs/contributors" target="_blank" rel="noopener" style="color:var(--primary)">See the list on GitHub</a>.</p>';
    }
});
</script>

<!-- ── Restart overlay ──────────────────────────────────────────────────── -->
<div id="restart-overlay" class="rs-overlay" role="alertdialog" aria-modal="true" aria-labelledby="rs-title" aria-describedby="restart-overlay-msg" hidden>
    <div class="rs-card">
        <div class="rs-spinner" aria-hidden="true"><i class="fa-solid fa-arrows-rotate"></i></div>
        <h3 id="rs-title">Restarting the server</h3>
        <p id="restart-overlay-msg">Pulling the latest code and restarting. This usually takes 10 to 60 seconds.</p>
        <ol class="rs-steps">
            <li data-step="0" class="on"><span></span>Restart requested</li>
            <li data-step="1"><span></span>Server offline</li>
            <li data-step="2"><span></span>Back online</li>
        </ol>
        <p class="rs-note">Keep this page open. It reloads by itself.</p>
    </div>
</div>
<style>
.rs-overlay { position: fixed; inset: 0; z-index: 9998; display: grid; place-items: center; padding: 16px; background: var(--scrim); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); overscroll-behavior: contain; touch-action: none; animation: rs-fade .2s var(--ease); }
.rs-overlay[hidden] { display: none; }
.rs-card { width: min(100%, 400px); padding: 1.75rem 1.5rem 1.4rem; border-radius: var(--radius); background: var(--card); border: 1px solid var(--border); box-shadow: var(--shadow-strong); text-align: center; color: var(--text); }
.rs-spinner { display: grid; place-items: center; width: 56px; height: 56px; margin: 0 auto 1rem; border-radius: 99px; background: color-mix(in srgb, var(--primary) 14%, transparent); color: var(--primary); font-size: 1.35rem; }
.rs-spinner i { animation: fa-spin 1.1s linear infinite; }
.rs-overlay.done .rs-spinner { background: color-mix(in srgb, var(--ok) 16%, transparent); color: var(--ok); }
.rs-overlay.done .rs-spinner i { animation: none; }
.rs-card h3 { font-size: 1.15rem; font-weight: 600; }
.rs-card #restart-overlay-msg { margin-top: .4rem; font-size: .9rem; color: var(--text-sec); line-height: 1.5; }
.rs-steps { list-style: none; margin: 1.25rem 0 0; padding: .9rem 1rem; border-radius: var(--radius-sm); background: var(--bg); border: 1px solid var(--border); display: grid; gap: .55rem; text-align: left; font-size: .88rem; color: var(--text-sec); }
.rs-steps li { display: flex; align-items: center; gap: .65rem; }
.rs-steps li span { width: 10px; height: 10px; border-radius: 99px; border: 2px solid var(--border); flex-shrink: 0; transition: all .25s var(--ease); }
.rs-steps li.on { color: var(--text); }
.rs-steps li.on span { border-color: var(--primary); background: var(--primary); }
.rs-steps li.now span { box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary) 25%, transparent); }
.rs-note { margin-top: .9rem; font-size: .78rem; color: var(--text-sec); }
@keyframes rs-fade { from { opacity: 0; } }
html.rs-lock, html.rs-lock body { overflow: hidden !important; }
</style>

<!-- Floating save (mobile) -->
<div class="fixed right-4 md:hidden z-30" style="bottom:calc(84px + env(safe-area-inset-bottom))">
    <button onclick="saveSettings()" aria-label="Save settings" data-shortcut-save
        class="btn-primary w-14 h-14" style="box-shadow:0 8px 24px rgba(0,0,0,.35)">
        <i class="fa-solid fa-floppy-disk text-lg"></i>
    </button>
</div>

<script>
/* ── Duplicate protection only applies when Replace Mode is off ───────── */
function toggleDuplicateProtection() {
    const replaceOn = document.getElementById('replace_mode').checked;
    const wrap = document.getElementById('dup-protect-wrap');
    const input = document.getElementById('duplicate_protection');
    input.disabled = replaceOn;
    wrap.style.opacity = replaceOn ? '0.5' : '';
    wrap.style.pointerEvents = replaceOn ? 'none' : '';
}

/* ── Toggle sub-fields visibility ─────────────────────────────────────── */
function toggleSubFields() {
    const enabled = document.getElementById('subscription').checked;
    document.getElementById('sub-fields').style.display = enabled ? '' : 'none';
}

function toggleGlobalSearchFields() {
    const enabled = document.getElementById('global_search').checked;
    const fields = document.getElementById('global-search-fields');

    if (fields) {
        fields.style.display = enabled ? '' : 'none';
    }
}

function toggleAnnouncementFields() {
    const enabled = document.getElementById('announce_new_content').checked;
    const fields = document.getElementById('announcement-fields');
    if (fields) {
        fields.style.display = enabled ? '' : 'none';
    }
}

function toggleMediaflowFields() {
    const hasProxy = document.getElementById('http_proxy_url').value.trim() !== '';
    const wrap = document.getElementById('mediaflow-wrap');
    const toggle = document.getElementById('mediaflow_proxy');
    if (wrap) wrap.style.display = hasProxy ? '' : 'none';
    if (!hasProxy && toggle) toggle.checked = false;
    const pwdWrap = document.getElementById('mediaflow-password-wrap');
    if (pwdWrap) pwdWrap.style.display = (hasProxy && toggle.checked) ? '' : 'none';
}

function toggleMfPwdVisibility() {
    const input = document.getElementById('mediaflow_password');
    const icon = document.getElementById('mf-eye-icon');
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'fa-solid fa-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'fa-solid fa-eye';
    }
}

function toggleSkipDeleteField() {
    const el = document.getElementById('skip_channel');
    const hasChannel = !!(el && (el.dataset.id || extractChannelId(el.value.trim())));
    const wrap = document.getElementById('delete_on_metadata_fail_wrap');
    if (wrap) {
        wrap.style.display = hasChannel ? '' : 'none';
    }
    if (!hasChannel) {
        document.getElementById('delete_on_metadata_fail').checked = false;
    }
}

function togglePosterProvider(which) {
    const els = {
        better: document.getElementById('better_poster_enabled'),
        rpdb: document.getElementById('rpdb_enabled'),
        spatial: document.getElementById('spatial_poster_enabled'),
        fanart: document.getElementById('fanart_enabled'),
    };
    if (which && els[which] && els[which].checked) {
        for (const k in els) if (k !== which) els[k].checked = false;
    }
    document.getElementById('better-poster-wrap').style.display = els.better.checked ? '' : 'none';
    document.getElementById('rpdb-wrap').style.display = els.rpdb.checked ? '' : 'none';
    document.getElementById('spatial-poster-wrap').style.display = els.spatial.checked ? '' : 'none';
    document.getElementById('fanart-wrap').style.display = els.fanart.checked ? '' : 'none';
}

const FORMATTER_PRESETS = {{ formatter_presets|tojson }};
let previewTimer = null;

function toggleFormatter() {
    const v = document.getElementById('stream_formatter').value;
    document.getElementById('formatter-custom-wrap').style.display = v === 'custom' ? '' : 'none';
    document.getElementById('formatter-preview-wrap').style.display = v === 'default' ? 'none' : '';
    const name = document.getElementById('formatter_name');
    if (v === 'custom' && !name.value.trim()) {
        name.value = FORMATTER_PRESETS.gdrive.name;
        document.getElementById('formatter_description').value = FORMATTER_PRESETS.gdrive.description;
    }
    schedulePreview();
}

function copyPreset(sel) {
    const p = FORMATTER_PRESETS[sel.value];
    if (p && confirm('Replace the custom templates with the ' + sel.value + ' preset?')) {
        document.getElementById('formatter_name').value = p.name;
        document.getElementById('formatter_description').value = p.description;
        schedulePreview();
    }
    sel.value = '';
}

function schedulePreview() {
    clearTimeout(previewTimer);
    previewTimer = setTimeout(renderPreview, 300);
}

async function renderPreview() {
    const preset = document.getElementById('stream_formatter').value;
    if (preset === 'default') return;
    try {
        const res = await fetch('/api/admin/settings/formatter-preview', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                preset,
                name: document.getElementById('formatter_name').value,
                description: document.getElementById('formatter_description').value,
                filename: document.getElementById('formatter_sample').value,
            }),
        });
        const data = await res.json();
        document.getElementById('formatter-preview-name').textContent = data.name || '';
        document.getElementById('formatter-preview-desc').textContent = data.description || '';
    } catch (e) {
        document.getElementById('formatter-preview-desc').textContent = 'Preview failed.';
    }
}

document.addEventListener('DOMContentLoaded', schedulePreview);

function toggleFanartShuffle() {
    const on = document.getElementById('fanart_shuffle').checked;
    document.getElementById('fanart-shuffle-wrap').style.display = on ? '' : 'none';
}

/* ── Password visibility ──────────────────────────────────────────────── */
function togglePwdVisibility() {
    const input = document.getElementById('admin_password');
    const icon  = document.getElementById('eye-icon');
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'fa-solid fa-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'fa-solid fa-eye';
    }
}

/* ── Session secret generator ─────────────────────────────────────────── */
function generateSessionSecret() {
    const bytes = new Uint8Array(32);
    crypto.getRandomValues(bytes);
    const input = document.getElementById('session_secret');
    input.value = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
    input.type = 'text';
}

/* ── Multi-value list helpers ─────────────────────────────────────────── */
function authRowHTML(id, title, isAnime) {
    const display = title ? escapeHtmlAttr(title) : escapeHtmlAttr(id);
    return `
        <span class="channel-chip" data-list="auth_channels" data-id="${escapeHtmlAttr(id)}" title="${escapeHtmlAttr(id)}">${display}</span>
        <label class="anime-check ${isAnime ? 'is-anime' : ''}" title="Mark as anime channel β€” uses Kitsu β†’ TVDB β†’ TMDB β†’ Cinemeta">
            <input type="checkbox" class="anime-toggle" ${isAnime ? 'checked' : ''} onchange="syncAnimeChip(this)">
            <span>Anime</span>
        </label>
        <button class="remove-btn" onclick="removeItem(this)" title="Remove">
            <i class="fa-solid fa-xmark"></i>
        </button>
    `;
}

function syncAnimeChip(cb) {
    const chip = cb.closest('.anime-check');
    if (chip) chip.classList.toggle('is-anime', cb.checked);
}

function isValidChannelId(value) {
    return /^-100\d{6,}$/.test(value);
}

function addItem(listKey) {
    const newInput = document.getElementById(listKey + '_new');
    const value = newInput.value.trim();
    if (!value) return;

    const channelLists = ['auth_channels', 'global_search_channels', 'manual_channels'];
    if (channelLists.includes(listKey) && !isValidChannelId(value)) {
        alert('Only channel IDs in -100xxxxxxxxxx format are accepted (channels only).');
        return;
    }

    const existing = collectList(listKey);
    if (existing.includes(value)) {
        alert('This channel is already added.');
        return;
    }

    const container = document.getElementById(listKey + '_items');
    const item = document.createElement('div');

    if (listKey === 'auth_channels') {
        item.className = 'multi-item auth-item';
        item.innerHTML = authRowHTML(value, value, false);
    } else if (channelLists.includes(listKey)) {
        item.className = 'multi-item';
        item.innerHTML = channelChipHTML(listKey, value, value);
    } else {
        const isNumeric = listKey === 'approver_ids';
        item.className = 'multi-item';
        item.innerHTML = `
        <input type="${isNumeric ? 'number' : 'text'}"
               class="s-input"
               value="${escapeHtmlAttr(value)}"
               data-list="${listKey}">
        <button class="remove-btn" onclick="removeItem(this)" title="Remove">
            <i class="fa-solid fa-xmark"></i>
        </button>
    `;
    }

    container.appendChild(item);
    newInput.value = '';
    newInput.focus();
}

function channelChipHTML(listKey, id, title) {
    const display = title ? escapeHtmlAttr(title) : escapeHtmlAttr(id);
    return `
        <span class="channel-chip" data-list="${listKey}" data-id="${escapeHtmlAttr(id)}" title="${escapeHtmlAttr(id)}">${display}</span>
        <button class="remove-btn" onclick="removeItem(this)" title="Remove">
            <i class="fa-solid fa-xmark"></i>
        </button>
    `;
}

function extractChannelId(raw) {
    if (!raw) return '';
    const m = String(raw).match(/-100\d+/);
    return m ? m[0] : raw.trim();
}

function clearSingleChannel(fieldId) {
    const el = document.getElementById(fieldId);
    if (!el) return;
    el.value = '';
    el.dataset.id = '';
    el.readOnly = false;
    const btn = document.getElementById(fieldId + '_clear');
    if (btn) btn.style.display = 'none';
    if (fieldId === 'skip_channel') toggleSkipDeleteField();
}

function collectAnimeChannels() {
    const container = document.getElementById('auth_channels_items');
    if (!container) return [];
    const out = [];
    container.querySelectorAll('.multi-item').forEach(row => {
        const toggle = row.querySelector('.anime-toggle');
        const el = row.querySelector('[data-list="auth_channels"]');
        if (toggle && toggle.checked && el) {
            const id = el.dataset.id || extractChannelId(el.value || el.textContent);
            if (id) out.push(id);
        }
    });
    return out;
}

function removeItem(btn) {
    btn.closest('.multi-item').remove();
}

function collectList(listKey) {
    const container = document.getElementById(listKey + '_items');
    if (!container) return [];
    return [...container.querySelectorAll('[data-list="' + listKey + '"]')]
        .map(i => {
            if (i.dataset.id) return i.dataset.id.trim();
            if (i.value !== undefined) return extractChannelId(i.value);
            return extractChannelId(i.textContent || '');
        })
        .filter(Boolean);
}

/* ── Save ──────────────────────────────────────────────────────────────── */

function toggleWebdavPwdVisibility() {
    const input = document.getElementById('webdav_password');
    const icon = document.getElementById('webdav-eye-icon');
    if (!input) return;
    if (input.type === 'password') {
        input.type = 'text';
        if (icon) icon.className = 'fa-solid fa-eye-slash';
    } else {
        input.type = 'password';
        if (icon) icon.className = 'fa-solid fa-eye';
    }
}

async function saveSettings() {
    const btn   = document.getElementById('save-btn');
    const label = document.getElementById('save-label');

    const channelFields = [
        ...collectList('auth_channels'),
        ...collectList('global_search_channels'),
        ...collectList('manual_channels'),
    ];
    const acEl = document.getElementById('announcement_channel');
    const scEl = document.getElementById('skip_channel');
    const acId = (acEl.dataset.id || extractChannelId(acEl.value.trim()));
    const scId = (scEl.dataset.id || extractChannelId(scEl.value.trim()));
    if (acId) channelFields.push(acId);
    if (scId) channelFields.push(scId);
    for (const c of channelFields) {
        if (!isValidChannelId(c)) {
            alert('Only channel IDs in -100xxxxxxxxxx format are accepted: ' + c);
            return;
        }
    }
    if (acEl.value.trim() && !acId) {
        alert('Announcement channel must be -100xxxxxxxxxx format.');
        return;
    }
    if (scEl.value.trim() && !scId) {
        alert('Skip channel must be -100xxxxxxxxxx format.');
        return;
    }

    btn.disabled  = true;
    label.textContent = 'Saving…';

    const payload = {
        replace_mode:                  document.getElementById('replace_mode').checked,
        duplicate_protection:          document.getElementById('duplicate_protection').checked,
        hide_catalog:                  document.getElementById('hide_catalog').checked,
        admin_username:                document.getElementById('admin_username').value.trim(),
        admin_password:                document.getElementById('admin_password').value,  // blank = keep
        session_secret:                document.getElementById('session_secret').value,  // blank = keep
        tmdb_api:                      document.getElementById('tmdb_api').value.trim(),
        tvdb_api:                      (document.getElementById('tvdb_api') || {}).value?.trim() || '',
        base_url:                      document.getElementById('base_url').value.trim(),
        better_poster_enabled:         document.getElementById('better_poster_enabled').checked,
        better_poster:                 document.getElementById('better_poster').value.trim(),
        rpdb_enabled:                  document.getElementById('rpdb_enabled').checked,
        rpdb_api_key:                  document.getElementById('rpdb_api_key').value.trim(),
        spatial_poster_enabled:        document.getElementById('spatial_poster_enabled').checked,
        spatial_poster:                document.getElementById('spatial_poster').value.trim(),
        stream_formatter:              document.getElementById('stream_formatter').value,
        formatter_name:                document.getElementById('formatter_name').value,
        formatter_description:         document.getElementById('formatter_description').value,
        fanart_enabled:                document.getElementById('fanart_enabled').checked,
        fanart_api_key:                document.getElementById('fanart_api_key').value.trim(),
        fanart_shuffle:                document.getElementById('fanart_shuffle').checked,
        fanart_shuffle_interval:       parseInt(document.getElementById('fanart_shuffle_interval').value, 10) || 0,
        fanart_low_res_poster:         document.getElementById('fanart_low_res_poster').checked,
        upstream_repo:                 document.getElementById('upstream_repo').value.trim(),
        upstream_branch:               document.getElementById('upstream_branch').value.trim(),
        auth_channels:                 collectList('auth_channels'),
        anime_channels:                collectAnimeChannels(),
        subscription:                  document.getElementById('subscription').checked,
        subscription_group_id:         parseInt(document.getElementById('subscription_group_id').value || '0', 10),
        payment_instructions:          document.getElementById('payment_instructions').value.trim(),
        payment_qr_url:                document.getElementById('payment_qr_url').value.trim(),
        approver_ids:                  collectList('approver_ids').map(Number),
        http_proxy_url:                document.getElementById('http_proxy_url').value.trim(),
        show_proxy_and_non_proxy_both: document.getElementById('show_proxy_and_non_proxy_both').checked,
        mediaflow_proxy:               document.getElementById('mediaflow_proxy').checked,
        mediaflow_password:            document.getElementById('mediaflow_password').value,
        cf_stream_url:                 document.getElementById('cf_stream_url').value.trim(),
        cf_stream_secret:              document.getElementById('cf_stream_secret').value.trim(),
        cf_stream_mode:                document.getElementById('cf_stream_mode').value,
        webdav_user:                   document.getElementById('webdav_user').value.trim(),
        webdav_password:               document.getElementById('webdav_password').value,
        multi_tokens:                  collectList('multi_tokens'),
        helper_tokens:                 collectList('helper_tokens'),
        extra_databases:               collectList('extra_databases'),
        global_search:                 document.getElementById('global_search').checked,
        global_search_channels:        collectList('global_search_channels'),
        manual_channels:               collectList('manual_channels'),
        announce_new_content:          document.getElementById('announce_new_content').checked,
        announcement_channel:          (function(){const el=document.getElementById('announcement_channel');return el.dataset.id||extractChannelId(el.value.trim());})(),
        skip_channel:                  (function(){const el=document.getElementById('skip_channel');return el.dataset.id||extractChannelId(el.value.trim());})(),
        delete_on_metadata_fail:       document.getElementById('delete_on_metadata_fail').checked,
    };
    const dsEl = document.getElementById('default_streaming');
    if (dsEl) payload.default_streaming = dsEl.checked ? 'userbot' : 'bots';

    try {
        const res  = await fetch('/api/admin/settings', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload),
        });
        const data = await res.json();

        if (res.ok) {
            showToast('Settings saved successfully!', 'success', 'Saved');

            // Show reinit notices
            const reinit = data.reinit || {};
            for (const [subsystem, msg] of Object.entries(reinit)) {
                showToast(`${capitalize(subsystem)}: ${msg}`, 'info');
            }

            // Pull the freshly-saved state back from the server and patch
            // the UI in place β€” no full page reload needed. This also
            // picks up server-computed bits the form can't know on its
            // own (e.g. each database's live connection-status dot).
            await refreshSettingsFromServer();
        } else {
            showToast(data.detail || 'Save failed', 'error', 'Error');
        }
    } catch (err) {
        showToast('Network error β€” could not reach server.', 'error', 'Error');
        console.error(err);
    } finally {
        btn.disabled  = false;
        label.textContent = 'Save Settings';
    }
}

/* ── Backup & Restore ───────────────────────────────────────────────────── */
async function restoreBackup(input) {
    const file = input.files && input.files[0];
    input.value = '';
    if (!file) return;
    if (!confirm('Restore this backup? It will replace your catalogs, plans and tokens, and reconnect databases / bot tokens.')) return;

    const btn = document.getElementById('restore-btn');
    const status = document.getElementById('restore-status');
    if (btn) btn.disabled = true;
    if (status) {
        status.style.display = 'flex';
        status.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Importing β€” connecting databases and starting clients…';
    }
    try {
        const payload = JSON.parse(await file.text());
        const res = await fetch('/api/admin/backup/import', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Restore failed');
        if (status) status.innerHTML = '<i class="fa-solid fa-circle-check" style="color:var(--ok)"></i> Imported successfully β€” reloading…';
        showToast(data.message || 'Backup restored.', 'success', 'Restored');
        setTimeout(() => location.reload(), 1500);
    } catch (err) {
        if (status) status.innerHTML = '<i class="fa-solid fa-circle-xmark" style="color:var(--danger)"></i> ' + escapeHtmlAttr(err.message || 'Invalid backup file.');
        showToast(err.message || 'Invalid backup file.', 'error', 'Error');
        if (btn) btn.disabled = false;
    }
}

/* ── Utilities ─────────────────────────────────────────────────────────── */
function escapeHtmlAttr(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1).replace(/_/g, ' ');
}

/* ── Post-save refresh, no page reload ──────────────────────────────────── */
async function refreshSettingsFromServer() {
    try {
        const res = await fetch('/api/admin/settings');
        if (!res.ok) return;
        const data = await res.json();
        renderSettings(data.settings || {});
    } catch (err) {
        console.error('Failed to refresh settings UI:', err);
    }
}

function renderSettings(s) {
    // Toggles
    document.getElementById('replace_mode').checked = !!s.replace_mode;
    document.getElementById('duplicate_protection').checked = !!s.duplicate_protection;
    toggleDuplicateProtection();
    document.getElementById('hide_catalog').checked = !!s.hide_catalog;
    document.getElementById('subscription').checked = !!s.subscription;
    document.getElementById('show_proxy_and_non_proxy_both').checked = !!s.show_proxy_and_non_proxy_both;
    document.getElementById('global_search').checked = !!s.global_search;
    const dsEl = document.getElementById('default_streaming');
    if (dsEl) dsEl.checked = s.default_streaming === 'userbot';
    document.getElementById('announce_new_content').checked = !!s.announce_new_content;
    document.getElementById('delete_on_metadata_fail').checked = !!s.delete_on_metadata_fail;
    toggleSubFields();
    toggleGlobalSearchFields();
    toggleAnnouncementFields();

    // Plain text/number fields
    document.getElementById('admin_username').value = s.admin_username || '';
    document.getElementById('admin_password').value = '';  // never re-fill password
    document.getElementById('tmdb_api').value = s.tmdb_api || '';
    if (document.getElementById('tvdb_api')) document.getElementById('tvdb_api').value = s.tvdb_api || '';
    document.getElementById('base_url').value = s.base_url || '';
    document.getElementById('better_poster_enabled').checked = !!s.better_poster_enabled;
    document.getElementById('better_poster').value = s.better_poster || '';
    document.getElementById('rpdb_enabled').checked = !!s.rpdb_enabled;
    document.getElementById('rpdb_api_key').value = s.rpdb_api_key || '';
    document.getElementById('spatial_poster_enabled').checked = !!s.spatial_poster_enabled;
    document.getElementById('spatial_poster').value = s.spatial_poster || '';
    document.getElementById('stream_formatter').value = s.stream_formatter || 'default';
    document.getElementById('formatter_name').value = s.formatter_name || '';
    document.getElementById('formatter_description').value = s.formatter_description || '';
    toggleFormatter();
    document.getElementById('fanart_enabled').checked = !!s.fanart_enabled;
    document.getElementById('fanart_api_key').value = s.fanart_api_key || '';
    document.getElementById('fanart_shuffle').checked = !!s.fanart_shuffle;
    document.getElementById('fanart_shuffle_interval').value = (s.fanart_shuffle_interval ?? 5);
    document.getElementById('fanart_low_res_poster').checked = (s.fanart_low_res_poster ?? true);
    togglePosterProvider();
    toggleFanartShuffle();
    document.getElementById('upstream_repo').value = s.upstream_repo || '';
    document.getElementById('upstream_branch').value = s.upstream_branch || '';
    document.getElementById('subscription_group_id').value = s.subscription_group_id || 0;
    document.getElementById('http_proxy_url').value = s.http_proxy_url || '';
    document.getElementById('mediaflow_proxy').checked = !!s.mediaflow_proxy;
    document.getElementById('mediaflow_password').value = s.mediaflow_password || '';
    document.getElementById('cf_stream_url').value = s.cf_stream_url || '';
    document.getElementById('cf_stream_secret').value = s.cf_stream_secret || '';
    document.getElementById('cf_stream_mode').value = s.cf_stream_mode || 'off';
    const wu = document.getElementById('webdav_user');
    if (wu) wu.value = s.webdav_user || '';
    const wp = document.getElementById('webdav_password');
    if (wp) wp.value = s.webdav_password || '';
    toggleMediaflowFields();

    const titles = s.channel_titles || {};
    rebuildAuthChannels(s.auth_channels, s.anime_channels, titles);
    rebuildSimpleList('approver_ids_items', s.approver_ids, 'number');
    rebuildSimpleList('multi_tokens_items', s.multi_tokens, 'text');
    rebuildSimpleList('helper_tokens_items', s.helper_tokens, 'text');
    rebuildSimpleList('global_search_channels_items', s.global_search_channels, 'text', titles);
    rebuildSimpleList('manual_channels_items', s.manual_channels, 'text', titles);

    const ac = document.getElementById('announcement_channel');
    if (ac) {
        const acid = s.announcement_channel || '';
        ac.dataset.id = acid;
        ac.value = acid ? (titles[acid] || acid) : '';
        ac.readOnly = !!acid;
        const acBtn = document.getElementById('announcement_channel_clear');
        if (acBtn) acBtn.style.display = acid ? '' : 'none';
    }
    const sc = document.getElementById('skip_channel');
    if (sc) {
        const scid = s.skip_channel || '';
        sc.dataset.id = scid;
        sc.value = scid ? (titles[scid] || scid) : '';
        sc.readOnly = !!scid;
        const scBtn = document.getElementById('skip_channel_clear');
        if (scBtn) scBtn.style.display = scid ? '' : 'none';
    }
    toggleSkipDeleteField();

    rebuildDatabaseList(s.database_list || []);
}

function rebuildSimpleList(containerId, values, inputType, titles) {
    const container = document.getElementById(containerId);
    if (!container) return;
    const listKey = containerId.replace('_items', '');
    const channelLists = ['global_search_channels', 'manual_channels'];
    titles = titles || {};

    container.innerHTML = '';
    (values || []).forEach(val => {
        const item = document.createElement('div');
        item.className = 'multi-item';
        if (channelLists.includes(listKey)) {
            const id = String(val);
            item.innerHTML = channelChipHTML(listKey, id, titles[id] || id);
        } else {
            item.innerHTML = `
                <input type="${inputType}" class="s-input"
                       value="${escapeHtmlAttr(val)}" data-list="${listKey}">
                <button class="remove-btn" onclick="removeItem(this)" title="Remove">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            `;
        }
        container.appendChild(item);
    });
}

function rebuildAuthChannels(values, animeValues, titles) {
    const container = document.getElementById('auth_channels_items');
    if (!container) return;
    const animeNorm = (animeValues || []).map(v => String(v).replace(/^-100/, ''));
    titles = titles || {};
    container.innerHTML = '';
    (values || []).forEach(val => {
        const id = String(val);
        const isAnime = animeNorm.includes(id.replace(/^-100/, ''));
        const item = document.createElement('div');
        item.className = 'multi-item auth-item';
        item.innerHTML = authRowHTML(id, titles[id] || id, isAnime);
        container.appendChild(item);
    });
}

function rebuildDatabaseList(dbList) {
    const container = document.getElementById('extra_databases_items');
    if (!container) return;

    container.innerHTML = '';
    dbList.filter(entry => !entry.locked).forEach(entry => {
        const item = document.createElement('div');
        item.className = 'multi-item';
        item.innerHTML = `
            <input type="text" class="s-input" spellcheck="false"
                   value="${escapeHtmlAttr(entry.full_uri || '')}" data-list="extra_databases">
            <span title="${entry.connected ? 'Connected' : 'Disconnected'}"
                style="flex-shrink:0;width:0.6rem;height:0.6rem;border-radius:50%;
                       background:${entry.connected ? 'var(--ok)' : 'var(--danger)'}"></span>
            <button class="remove-btn" onclick="removeItem(this)" title="Remove (only safe from the end of the list)">
                <i class="fa-solid fa-xmark"></i>
            </button>
        `;
        container.appendChild(item);
    });
}

/* ── System & Maintenance ───────────────────────────────────────────────── */
const STAT_FIELDS = [
    ['movies', 'Movies'], ['tv_shows', 'TV Shows'], ['episodes', 'Episodes'],
    ['streams', 'Streams'], ['db_size', 'DB Size'],
    ['auth_channels', 'AUTH Channels'], ['version', 'Version'],
];
let logLiveTimer = null;

/* Spin the clicked refresh button's icon while an async action runs */
function spinIcon(btn, on) {
    const icon = btn && btn.querySelector('i');
    if (icon) icon.classList.toggle('fa-spin', on);
}

async function loadDbStats(btn) {
    const grid = document.getElementById('stats-grid');
    spinIcon(btn, true);
    try {
        const res = await fetch('/api/admin/stats');
        const data = await res.json();
        if (data.status !== 'success') throw new Error(data.message || 'failed');
        const s = data.data;
        grid.innerHTML = STAT_FIELDS.map(([k, label]) =>
            `<div class="stat-box"><div class="v">${escapeHtml(String(s[k] ?? 'β€”'))}</div><div class="l">${label}</div></div>`
        ).join('');
    } catch (e) {
        grid.innerHTML = `<div class="hint" style="grid-column:1/-1;color:var(--danger)">Failed to load stats.</div>`;
    } finally {
        spinIcon(btn, false);
    }
}

async function loadLogs(btn) {
    const view = document.getElementById('log-view');
    spinIcon(btn, true);
    try {
        const res = await fetch('/api/admin/logs');
        const data = await res.json();
        if (data.status === 'success') {
            const atBottom = view.scrollHeight - view.scrollTop - view.clientHeight < 40;
            view.textContent = data.log || '(log is empty)';
            if (atBottom) view.scrollTop = view.scrollHeight;
        } else {
            view.textContent = data.message || 'Could not read log.';
        }
    } catch (e) {
        view.textContent = 'Network error while loading logs.';
    } finally {
        spinIcon(btn, false);
    }
}

function toggleLiveLogs() {
    const on = document.getElementById('log-live-toggle').checked;
    if (logLiveTimer) { clearInterval(logLiveTimer); logLiveTimer = null; }
    if (on) { loadLogs(); logLiveTimer = setInterval(loadLogs, 2000); }
}

async function restartApp() {
    if (!confirm('Restart the app now? It will pull the latest code and be unreachable for a few seconds.')) return;

    let before = null;
    try { before = (await (await fetch('/api/admin/health')).json()).start_time; } catch (e) {}

    try {
        const res = await fetch('/api/admin/restart', { method: 'POST' });
        const data = await res.json();
        if (!res.ok) { showToast(data.detail || 'Could not restart.', 'error', 'Error'); return; }
        showToast(data.message || 'Restart initiated.', 'info', 'Restart');
    } catch (e) {
        showToast('Network error.', 'error', 'Error'); return;
    }

    // Web app goes down during restart β€” poll health until start_time changes, then reload.
    if (logLiveTimer) { clearInterval(logLiveTimer); logLiveTimer = null; }
    const overlay = document.getElementById('restart-overlay');
    overlay.hidden = false;
    document.documentElement.classList.add('rs-lock');
    document.activeElement?.blur();
    const msg = document.getElementById('restart-overlay-msg');
    const step = n => overlay.querySelectorAll('[data-step]').forEach(li => {
        li.classList.toggle('on', +li.dataset.step <= n);
        li.classList.toggle('now', +li.dataset.step === n);
    });
    step(0);
    let wasDown = false;

    const poll = setInterval(async () => {
        try {
            const res = await fetch('/api/admin/health', { cache: 'no-store' });
            if (!res.ok) throw new Error('not ready');
            const d = await res.json();
            if (wasDown || (before && d.start_time && d.start_time !== before)) {
                clearInterval(poll);
                msg.textContent = 'The server is back. Reloading the page…';
                document.getElementById('rs-title').textContent = 'Restart complete';
                overlay.classList.add('done');
                step(2);
                // Persist a flag so the success notice survives the page reload below.
                sessionStorage.setItem('restartSuccess', '1');
                setTimeout(() => window.location.reload(), 900);
            }
        } catch (e) {
            wasDown = true;   // server is down β€” it's restarting
            msg.textContent = 'The server is offline while it restarts. Waiting for it to come back…';
            step(1);
        }
    }, 2000);
}

/* Run after DOMContentLoaded so base.html helpers (showToast) are defined β€”
   the base script that defines showToast is parsed after this block, so calling
   it at parse time would throw and abort the initial stats/log load. */
window.addEventListener('DOMContentLoaded', () => {
    // Post-restart success notice (survives the reload) for ~8s
    if (sessionStorage.getItem('restartSuccess')) {
        sessionStorage.removeItem('restartSuccess');
        showToast('The app restarted successfully and is back online.', 'success', 'Restart complete', 8000);
    }
    toggleDuplicateProtection();
    toggleMediaflowFields();
    loadDbStats();
    loadLogs();
});
</script>

{% endblock %}