File size: 60,333 Bytes
ddebc3e
 
 
 
 
 
 
 
 
 
a9f0d16
 
ddebc3e
 
 
a9f0d16
 
ddebc3e
 
a9f0d16
ddebc3e
 
 
 
a9f0d16
ddebc3e
a9f0d16
 
 
 
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9f0d16
 
ddebc3e
 
a9f0d16
ddebc3e
a9f0d16
ddebc3e
a9f0d16
 
ddebc3e
 
 
 
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
a9f0d16
ddebc3e
a9f0d16
 
ddebc3e
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
a9f0d16
 
 
 
ddebc3e
 
 
 
 
 
 
a9f0d16
ddebc3e
 
a9f0d16
ddebc3e
 
 
 
 
 
 
 
 
a9f0d16
 
 
ddebc3e
 
 
 
 
 
 
 
a9f0d16
 
 
ddebc3e
 
 
 
 
 
 
 
a9f0d16
 
ddebc3e
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9f0d16
 
 
ddebc3e
 
a9f0d16
 
ddebc3e
 
 
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
 
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
a9f0d16
 
 
ddebc3e
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
 
a9f0d16
 
 
ddebc3e
 
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
a9f0d16
 
 
ddebc3e
 
a9f0d16
ddebc3e
 
 
 
 
 
a9f0d16
 
 
 
 
 
ddebc3e
 
 
a9f0d16
 
 
ddebc3e
 
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
 
a9f0d16
ddebc3e
a9f0d16
 
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
a9f0d16
ddebc3e
 
a9f0d16
ddebc3e
a9f0d16
ddebc3e
 
 
 
 
 
 
a9f0d16
 
ddebc3e
 
 
 
 
 
 
a9f0d16
ddebc3e
 
a9f0d16
ddebc3e
 
 
 
 
 
 
 
 
 
a9f0d16
 
 
 
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9f0d16
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9f0d16
 
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
026f22a
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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title data-i18n="config.pageTitle">Grok2API - 配置管理</title>
  <link rel="icon" href="/favicon.ico?v={{APP_VERSION}}">
  <link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
  <link href="/static/css/app.css?v={{APP_VERSION}}" rel="stylesheet">
  <style>
    /* 全局基础深灰色调 */
    body { background: #18181b; color: #e4e4e7; }

    /* Page header */
    .page-hd   { display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:20px }
    .page-title{ font-size:22px; font-weight:700; line-height:1.2; color: #ffffff; }
    .page-sub  { font-size:13px; color:#a1a1aa; margin-top:5px }
    .page-actions { display:flex; gap:8px; align-items:center; flex-shrink:0 }

    /* 按钮深色适配 */
    .page-action-btn {
      height:32px; padding:0 14px; border-radius:999px;
      display:inline-flex; align-items:center; justify-content:center; gap:6px;
      font-size:13px; font-weight:600;
      border:1px solid #3f3f46; background:#27272a; color:#e4e4e7;
    }
    .page-action-btn:hover { background:#3f3f46; border-color:#52525b; color:#fff }
    .page-action-btn-primary { background:#fafafa; border-color:#fafafa; color:#111 }
    .page-action-btn-primary:hover { background:#e4e4e7; border-color:#e4e4e7 }
    .page-action-btn:disabled { opacity:.3; pointer-events:none }

    /* Section nav tabs */
    .cfg-nav {
      display:flex;
      align-items:center;
      gap:6px;
      flex-wrap:wrap;
      margin-bottom:16px;
      padding:0;
    }
    .cfg-tab {
      height:30px;
      padding:0 12px;
      border-radius:999px;
      font-size:12px;
      font-weight:500;
      color:#a1a1aa;
      background:#27272a;
      transition:color .15s, background .15s;
      cursor:pointer;
      border:none;
    }
    .cfg-tab:hover { color:#fff; background:#3f3f46 }
    .cfg-tab.active {
      background:#fafafa;
      color:#111;
      font-weight:600;
    }
    .cfg-tab .dot {
      display:none;
      width:6px;
      height:6px;
      border-radius:50%;
      background:currentColor;
      margin-left:5px;
      vertical-align:middle;
      opacity:.7;
    }
    .cfg-tab.dirty .dot { display:inline-block }

    /* Section panels */
    .cfg-panel { display:none }
    .cfg-panel.active { display:block }

    /* Field rows - 容器与行卡片适配 */
    .cfg-group {
      background:#27272a;
      border:1px solid #3f3f46;
      border-radius:12px;
      overflow:hidden;
      margin-bottom:12px;
    }
    .cfg-group-title {
      font-size:11px;
      font-weight:700;
      color:#a1a1aa;
      text-transform:uppercase;
      letter-spacing:.08em;
      padding:12px 16px 6px;
      background:#27272a;
      border-bottom:none;
    }
    .cfg-row {
      display:grid;
      grid-template-columns:minmax(0, 2fr) minmax(300px, 1fr);
      gap:18px;
      align-items:center;
      padding:11px 16px;
      border-bottom:1px solid #3f3f46;
      transition:background .15s;
    }
    .cfg-row:last-child { border-bottom:none }
    .cfg-row:hover { background:#2f2f33 }
    /* 暗色模式下修改状态使用暗琥珀色背景 */
    .cfg-row.modified { background:#2c1d05 }
    .cfg-row.modified:hover { background:#382607 }
    .cfg-label-col { min-width:0; display:grid; gap:3px; align-content:start }
    .cfg-label {
      display:inline-flex;
      align-items:center;
      gap:6px;
      font-size:12px;
      font-weight:600;
      color:#f4f4f5;
      line-height:1.35;
    }
    .cfg-desc  { max-width:520px; font-size:11px; color:#a1a1aa; line-height:1.45 }
    .cfg-help {
      position:relative;
      width:16px;
      height:16px;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      padding:0;
      border-radius:50%;
      border:1px solid #3f3f46;
      background:#27272a;
      color:#a1a1aa;
      font-size:11px;
      line-height:1;
      font-weight:700;
      cursor:help;
      flex-shrink:0;
    }
    .cfg-help:hover,
    .cfg-help:focus-visible {
      color:#fff;
      border-color:#52525b;
      background:#3f3f46;
      outline:none;
    }
    .cfg-help-tip {
      position:fixed;
      box-sizing:border-box;
      max-width:min(320px, calc(100vw - 24px));
      padding:9px 10px;
      border-radius:8px;
      background:#27272a;
      border:1px solid #3f3f46;
      color:#fff;
      font-size:12px;
      font-weight:500;
      line-height:1.5;
      text-align:left;
      white-space:pre-line;
      overflow-wrap:anywhere;
      box-shadow:0 8px 24px rgba(0,0,0,.4);
      opacity:0;
      pointer-events:none;
      transform:translateY(3px);
      transition:opacity .15s, transform .15s;
      z-index:1000;
    }
    .cfg-help-tip.visible {
      opacity:1;
      transform:translateY(0);
    }
    .cfg-help-tip::before {
      content:'';
      position:absolute;
      left:var(--arrow-left, 50%);
      width:8px;
      height:8px;
      background:#27272a;
      border-left:1px solid #3f3f46;
      border-top:1px solid #3f3f46;
      transform:translateX(-50%) rotate(45deg);
    }
    .cfg-help-tip[data-placement="top"]::before { bottom:-5px; transform:translateX(-50%) rotate(225deg); }
    .cfg-help-tip[data-placement="bottom"]::before { top:-5px; transform:translateX(-50%) rotate(45deg); }
    .cfg-input-col { min-width:0; display:flex; align-items:center; justify-content:flex-start; gap:8px }
    .cfg-input-col.is-bool { justify-content:flex-end }
    .cfg-inline-action {
      width:16px;
      height:16px;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      padding:0;
      color:#a1a1aa;
      border:0;
      background:transparent;
      cursor:pointer;
      flex-shrink:0;
      transition:color .15s, opacity .15s, transform .15s;
    }
    .cfg-inline-action:hover { color:#fff; transform:translateY(-.5px) }
    .cfg-inline-action:disabled {
      opacity:.32;
      cursor:not-allowed;
      pointer-events:none;
    }
    .cfg-inline-action svg { width:14px; height:14px; display:block }

    /* Inputs - 输入框元素全局深色化与边框调校 */
    .cfg-text {
      width:100%;
      max-width:none;
      height:32px;
      padding:0 10px;
      font-size:13px;
      border-radius:8px;
      border:1px solid #3f3f46;
      background:#1f1f23;
      color:#e4e4e7;
      transition:border-color .15s, background .15s;
      font-family: inherit; text-align:right;
    }
    .cfg-text:focus { border-color:#71717a; background:#27272a; outline:none; box-shadow:none; color:#fff; }
    .cfg-text.wide  { max-width:none }
    .cfg-textarea {
      width:100%;
      max-width:none;
      min-height:72px;
      padding:8px 10px;
      font-size:12px;
      border-radius:10px;
      border:1px solid #3f3f46;
      background:#1f1f23;
      color:#e4e4e7;
      resize:vertical;
      transition:border-color .15s, background .15s;
      font-family: 'Geist Mono', 'Courier New', monospace; line-height:1.5; text-align:right;
    }
    .cfg-textarea:focus { border-color:#71717a; background:#27272a; outline:none; color:#fff; }
    .cfg-number {
      width:100%;
      max-width:none;
      height:32px;
      padding:0 10px;
      font-size:13px;
      border-radius:8px;
      border:1px solid #3f3f46;
      background:#1f1f23;
      color:#e4e4e7;
      text-align:right;
    }
    .cfg-number:focus { border-color:#71717a; background:#27272a; outline:none; color:#fff; }
    .cfg-select {
      width:100%;
      height:32px;
      padding:0 28px 0 10px;
      font-size:13px;
      border-radius:8px;
      border:1px solid #3f3f46;
      background:#1f1f23;
      color:#e4e4e7;
      appearance:none; 
      /* 调整 SVG 图标为浅灰色以防暗色下看不见 */
      background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24'%3E%3Cpath d='M6 9l6 6 6-6' stroke='%23aaa' stroke-width='2' fill='none'/%3E%3C/svg%3E");
      background-repeat:no-repeat; background-position:right 8px center;
      cursor:pointer; text-align:right;
    }
    .cfg-select:focus { border-color:#71717a; background:#27272a; outline:none }
    .cfg-select option { background:#27272a; color:#e4e4e7 }
    .cfg-select option:disabled { color:#71717a }

    /* Toggle switch */
    .toggle {
      position:relative; display:inline-block; width:36px; height:20px; flex-shrink:0;
    }
    .toggle input { opacity:0; width:0; height:0 }
    .toggle-track {
      position:absolute; cursor:pointer; inset:0;
      background:#3f3f46; border-radius:20px; transition:background .2s;
    }
    .toggle-track::before {
      content:''; position:absolute; width:14px; height:14px;
      left:3px; bottom:3px; background:#fff; border-radius:50%;
      transition:transform .2s; box-shadow:0 1px 2px rgba(0,0,0,.3);
    }
    .toggle input:checked + .toggle-track { background:#fafafa }
    .toggle input:checked + .toggle-track::before { transform:translateX(16px); background:#111; }

    /* Modified badge */
    .cfg-modified-dot {
      display:inline-block; width:6px; height:6px; border-radius:50%;
      background:#f59e0b; margin-left:6px; vertical-align:middle;
      visibility:hidden;
    }
    .cfg-row.modified .cfg-modified-dot { visibility:visible }

    /* Random button */
    .cfg-rand-btn {
      width:30px; height:30px; border-radius:999px;
      display:inline-flex; align-items:center; justify-content:center;
      color:#a1a1aa; border:1px solid #3f3f46; background:#27272a;
      cursor:pointer; flex-shrink:0; transition:background .15s, border-color .15s;
    }
    .cfg-rand-btn:hover { background:#3f3f46; border-color:#52525b; color:#fff }

    /* Save bar - 底部保存栏半透明磨砂质感 */
    .save-bar {
      position:fixed;
      left:50%;
      bottom:18px;
      z-index:50;
      width:min(calc(100% - 56px), 1280px);
      transform:translate(-50%, calc(100% + 20px));
      background:rgba(39,39,42,.96);
      border:1px solid #3f3f46;
      border-radius:16px;
      padding:12px 16px;
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:12px;
      transition:transform .25s ease;
      box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    }
    .save-bar.visible { transform:translate(-50%, 0) }
    .save-bar-msg { font-size:13px; color:#a1a1aa }
    .save-bar-actions { display:flex; gap:8px }
    .save-bar-btn {
      height:32px;
      padding:0 14px;
      border-radius:999px;
      font-size:13px;
      font-weight:600;
      border:1px solid transparent;
      cursor:pointer;
    }
    .save-bar-btn-cancel { border-color:#3f3f46; background:#27272a; color:#e4e4e7; }
    .save-bar-btn-cancel:hover { background:#3f3f46; border-color:#52525b; color:#fff; }
    .save-bar-btn-save { background:#fafafa; color:#111 }
    .save-bar-btn-save:hover { background:#e4e4e7Prefix }

    @media (max-width:640px) {
      .cfg-row { grid-template-columns:1fr; gap:8px; align-items:flex-start }
      .cfg-input-col { justify-content:flex-start }
      .cfg-nav { gap:8px }
      .save-bar {
        width:calc(100% - 24px);
        bottom:12px;
        padding:12px;
        flex-direction:column;
        align-items:stretch;
      }
      .save-bar-actions { justify-content:flex-end }
    }
  </style>
</head>
<body>

<!-- ── Header ─────────────────────────────────────────────────────────────── -->
<div id="admin-header" data-active="/admin/config"></div>

<!-- ── Main ───────────────────────────────────────────────────────────────── -->
<main class="admin-main" style="padding-bottom:80px">

  <div class="page-hd">
    <div>
      <div class="page-title" data-i18n="config.pageHeading">配置管理</div>
      <div class="page-sub" data-i18n="config.pageSubtitle">统一管理运行时参数与服务行为。保存后即时生效,部分配置需重启服务。</div>
    </div>
    <div class="page-actions">
      <button id="btn-reset" onclick="doReset()" class="page-action-btn">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 1 0 3-6.708"/><path d="M3 4v5h5"/></svg>
        <span data-i18n="config.resetShort">重置</span>
      </button>
      <button id="btn-save" onclick="doSave()" class="page-action-btn page-action-btn-primary" disabled>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m5 12 4.2 4.2L19 6.5"/></svg>
        <span data-i18n="config.saveShort">保存</span>
      </button>
    </div>
  </div>

  <!-- Section tabs -->
  <div class="cfg-nav" id="cfg-nav"></div>

  <!-- Section panels, rendered by JS -->
  <div id="cfg-panels"></div>

</main>

<!-- ── Save bar (bottom) ──────────────────────────────────────────────────── -->
<div class="save-bar" id="save-bar">
  <div class="save-bar-msg" id="save-bar-msg" data-i18n="config.unsavedDefault">存在未保存的更改</div>
  <div class="save-bar-actions">
    <button class="save-bar-btn save-bar-btn-cancel" onclick="doReset()" data-i18n="config.discardShort">撤销</button>
    <button class="save-bar-btn save-bar-btn-save"   onclick="doSave()" data-i18n="config.saveBarShort">保存</button>
  </div>
</div>

<script src="/static/js/i18n.js?v={{APP_VERSION}}"></script>
<script src="/static/js/auth.js?v={{APP_VERSION}}"></script>
<script src="/static/js/admin-header.js?v={{APP_VERSION}}"></script>
<script src="/static/js/toast.js?v={{APP_VERSION}}"></script>
<script src="/static/js/footer.js?v={{APP_VERSION}}"></script>
<script>
const SCHEMA_DEF = [
  {
    id: 'system', label: '系统配置', labelKey: 'config.schema.tabs.system',
    groups: [
      {
        title: '基础访问控制', titleKey: 'config.schema.groups.baseAccess',
        section: 'app',
        fields: [
          { key: 'app_url', label: 'APP 访问地址', labelKey: 'config.schema.fields.appUrl.label', type: 'text', desc: '应用对外提供服务的根 URL,格式如 https://your-domain.com。本地代理模式必须配置。', descKey: 'config.schema.fields.appUrl.desc', wide: true },
          { key: 'app_key', label: 'APP 访问密码', labelKey: 'config.schema.fields.appKey.label', type: 'password', desc: '管理后台鉴权密码。修改后已有 Session 将立即失效,需重新登录。', descKey: 'config.schema.fields.appKey.desc', rand: true },
          { key: 'api_key', label: 'API 调用密钥', labelKey: 'config.schema.fields.apiKey.label', type: 'text', desc: 'OpenAI 兼容 API 的鉴权密钥。多个值请使用英文逗号分隔;留空则禁用鉴权。', descKey: 'config.schema.fields.apiKey.desc', rand: true },
          { key: 'webui_enabled', label: '启用 WebUI', labelKey: 'config.schema.fields.webuiEnabled.label', type: 'bool', desc: '开放 WebUI 功能入口。关闭后相关路由将返回 404。', descKey: 'config.schema.fields.webuiEnabled.desc' },
          { key: 'webui_key', label: 'WebUI 访问密码', labelKey: 'config.schema.fields.webuiKey.label', type: 'password', desc: 'WebUI 的访问鉴权密码。配置后访问时必须提供。', descKey: 'config.schema.fields.webuiKey.desc', rand: true, showIf: 'app.webui_enabled' },
        ]
      },
      {
        title: '日志配置', titleKey: 'config.schema.groups.logging',
        section: 'logging',
        fields: [
          {
            key: 'file_level',
            label: '文件日志等级',
            labelKey: 'config.schema.fields.fileLogLevel.label',
            type: 'select',
            options: [
              { value: 'DEBUG', label: 'DEBUG' },
              { value: 'INFO', label: 'INFO' },
              { value: 'WARNING', label: 'WARNING' },
              { value: 'ERROR', label: 'ERROR' },
            ],
            desc: '日志 file 写入最低等级,可独立于控制台配置。默认 INFO。',
            descKey: 'config.schema.fields.fileLogLevel.desc',
          },
          {
            key: 'max_files',
            label: '日志保留天数',
            labelKey: 'config.schema.fields.logMaxFiles.label',
            type: 'number',
            desc: '按天轮转时最多保留的日志文件数量。默认 7。',
            descKey: 'config.schema.fields.logMaxFiles.desc',
          },
        ]
      },
    ]
  },
  {
    id: 'features', label: '应用功能', labelKey: 'config.schema.tabs.features',
    groups: [
      {
        title: '基本功能设置', titleKey: 'config.schema.groups.features',
        section: 'features',
        fields: [
          { key: 'temporary', label: '临时会话', labelKey: 'config.schema.fields.temporary.label', type: 'bool', desc: '启用后请求不会写入 Grok 会话历史,等同于无痕对话。', descKey: 'config.schema.fields.temporary.desc' },
          { key: 'memory', label: '开启会话记忆', labelKey: 'config.schema.fields.memory.label', type: 'bool', desc: '启用 Grok Memory,允许模型跨会话记忆用户偏好与上下文。', descKey: 'config.schema.fields.memory.desc' },
          { key: 'stream', label: '默认流式输出', labelKey: 'config.schema.fields.stream.label', type: 'bool', desc: '请求未显式指定 stream 参数时所采用的默认值。', descKey: 'config.schema.fields.stream.desc' },
          { key: 'thinking', label: '默认思考输出', labelKey: 'config.schema.fields.thinking.label', type: 'bool', desc: '请求未显式指定 thinking 参数时所采用的默认值。启用后将在 reasoning_content 字段返回思考过程。', descKey: 'config.schema.fields.thinking.desc' },
          { key: 'auto_chat_mode_fallback', label: 'AUTO 聊天模式回退', labelKey: 'config.schema.fields.autoChatModeFallback.label', type: 'bool', desc: 'AUTO 聊天模型在 auto 额度不可用时,自动尝试 fast 和 expert 聊天额度窗口。', descKey: 'config.schema.fields.autoChatModeFallback.desc' },
          { key: 'thinking_summary', label: '思考精简输出', labelKey: 'config.schema.fields.thinkingSummary.label', type: 'bool', desc: '启用后将思考过程提炼为结构化摘要。关闭时输出完整的原始推理过程,支持多 Agent 模型的协作详情与工具调用展示。', descKey: 'config.schema.fields.thinkingSummary.desc' },
          { key: 'dynamic_statsig', label: '动态 Statsig', labelKey: 'config.schema.fields.dynamicStatsig.label', type: 'bool', desc: '为每次请求动态生成 Statsig 设备指纹,以降低风控拦截概率。', descKey: 'config.schema.fields.dynamicStatsig.desc' },
          { key: 'enable_nsfw', label: '允许 NSFW 生成', labelKey: 'config.schema.fields.enableNsfw.label', type: 'bool', desc: '允许图像生成接口绕过 NSFW 内容过滤。', descKey: 'config.schema.fields.enableNsfw.desc' },
          { key: 'show_search_sources', label: '正文追加信源', labelKey: 'config.schema.fields.showSearchSources.label', type: 'bool', desc: '搜索信源始终以 search_sources 字段输出。此选项控制是否同时在正文末尾追加 ## Sources 段落(兼容文本解析客户端)。', descKey: 'config.schema.fields.showSearchSources.desc' },
          { key: 'custom_instruction', label: '全局附加指令', labelKey: 'config.schema.fields.customInstruction.label', type: 'textarea', desc: '为每次请求注入统一的 system 消息,用于约束模型行为或固定角色设定。', descKey: 'config.schema.fields.customInstruction.desc' },
        ]
      },
      {
        title: '媒体返回格式', titleKey: 'config.schema.groups.mediaFormat',
        section: 'features',
        fields: [
          {
            key: 'image_format',
            label: '图片返回格式',
            labelKey: 'config.schema.fields.imageFormat.label',
            type: 'select',
            options: [
              { value: 'grok_url', label: 'URL(Grok 原生)', labelKey: 'config.schema.options.imageFormat.grokUrl' },
              { value: 'local_url', label: 'URL(本地代理)', labelKey: 'config.schema.options.imageFormat.localUrl', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
              { value: 'grok_md', label: 'Markdown(Grok 原生)', labelKey: 'config.schema.options.imageFormat.grokMarkdown' },
              { value: 'local_md', label: 'Markdown(本地代理)', labelKey: 'config.schema.options.imageFormat.localMarkdown', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
              { value: 'base64', label: 'Base64(内嵌)', labelKey: 'config.schema.options.imageFormat.base64' },
            ],
            desc: 'grok_url / grok_md 默认直接返回 Grok CDN 地址;local_* 模式会先下载到服务端,再通过本地 URL 代理分发;base64 会以内嵌 Data URI 返回。开启 Imagine Public 图片代理后,WebSocket 返回的 imagine-public 图片也会本地代理。',
            descKey: 'config.schema.fields.imageFormat.desc',
          },
          {
            key: 'imagine_public_image_proxy',
            label: 'Imagine Public 图片代理',
            labelKey: 'config.schema.fields.imaginePublicImageProxy.label',
            type: 'bool',
            desc: '开启后将 WebSocket 返回的 imagine-public 图片下载到服务端,再通过本地 URL 代理分发;关闭时保持公开图片直返。',
            descKey: 'config.schema.fields.imaginePublicImageProxy.desc',
          },
          {
            key: 'video_format',
            label: '视频返回格式',
            labelKey: 'config.schema.fields.videoFormat.label',
            type: 'select',
            options: [
              { value: 'grok_url', label: 'URL(Grok 原生)', labelKey: 'config.schema.options.videoFormat.grokUrl' },
              { value: 'local_url', label: 'URL(本地代理)', labelKey: 'config.schema.options.videoFormat.localUrl', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
              { value: 'grok_html', label: 'HTML(Grok 原生)', labelKey: 'config.schema.options.videoFormat.grokHtml' },
              { value: 'local_html', label: 'HTML(本地代理)', labelKey: 'config.schema.options.videoFormat.localHtml', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
            ],
            desc: 'local_* 模式会先将视频下载至服务端,再通过本地 URL 代理分发;请确保已配置 APP 访问地址,并评估出站带宽消耗。',
            descKey: 'config.schema.fields.videoFormat.desc',
          },
        ]
      },
    ]
  },
  {
    id: 'schedule', label: '任务调度', labelKey: 'config.schema.tabs.schedule',
    groups: [
      {
        title: '配额刷新调度', titleKey: 'config.schema.groups.refreshSchedule',
        section: 'account.refresh',
        fields: [
          { key: 'enabled', label: '启用配额刷新', labelKey: 'config.schema.fields.refreshEnabled.label', type: 'bool', desc: '开启后自动进入配额刷新模式,关闭后自动进入自动重试模式。', descKey: 'config.schema.fields.refreshEnabled.desc', help: '开启:配额刷新模式,scheduler 周期同步真实配额,选号按评分。\n关闭:自动重试模式,不主动探测 upstream,选号随机,出错自动换号重试最多 5 次。\n建议:万级以上账号关闭,避免主动探测触发 upstream 429。', helpKey: 'config.schema.fields.refreshEnabled.help' },
          { key: 'basic_interval_sec', label: 'Basic 周期(秒)', labelKey: 'config.schema.fields.basicInterval.label', type: 'number', desc: 'basic 号池共用周期:quota 模式下用于后台刷新,random 模式下用于 429 冷却。默认 86400s。', descKey: 'config.schema.fields.basicInterval.desc' },
          { key: 'super_interval_sec', label: 'Super 周期(秒)', labelKey: 'config.schema.fields.superInterval.label', type: 'number', desc: 'super 号池共用周期:quota 模式下用于后台刷新,random 模式下用于 429 冷却。默认 7200s。', descKey: 'config.schema.fields.superInterval.desc' },
          { key: 'heavy_interval_sec', label: 'Heavy 周期(秒)', labelKey: 'config.schema.fields.heavyInterval.label', type: 'number', desc: 'heavy 号池共用周期:quota 模式下用于后台刷新,random 模式下用于 429 冷却。默认 7200s。', descKey: 'config.schema.fields.heavyInterval.desc' },
          { key: 'on_demand_min_interval_sec', label: '按需刷新间隔(秒)', labelKey: 'config.schema.fields.onDemandMinInterval.label', type: 'number', desc: '请求链路触发刷新(例如收到 429)时的节流间隔。N 秒内重复触发只执行一次,避免批量打爆配额接口。', descKey: 'config.schema.fields.onDemandMinInterval.desc' },
          { key: 'usage_concurrency', label: '刷新并发数', labelKey: 'config.schema.fields.usageConcurrency.label', type: 'number', desc: '并发调用 usage 接口刷新额度时允许的最大并行数。', descKey: 'config.schema.fields.usageConcurrency.desc' },
        ]
      },
      {
        title: '选号并发限制', titleKey: 'config.schema.groups.selection',
        section: 'account.selection',
        fields: [
          { key: 'max_inflight', label: '单号并发上限', labelKey: 'config.schema.fields.maxInflight.label', type: 'number', desc: '单个账号同时在执行的请求上限,超过则选号路径跳过该号(两种模式共用)。', descKey: 'config.schema.fields.maxInflight.desc' },
        ]
      },
      {
        title: '批量操作并发', titleKey: 'config.schema.groups.batchConcurrency',
        section: 'batch',
        fields: [
          { key: 'nsfw_concurrency', label: '开启 NSFW 并发数', labelKey: 'config.schema.fields.nsfwConcurrency.label', type: 'number', min: 1, max: 80, desc: '批量开启 NSFW 时的 token 级并发数;每个 token 需经历三步网络请求。', descKey: 'config.schema.fields.nsfwConcurrency.desc' },
          { key: 'refresh_concurrency', label: '刷新 Usage 并发数', labelKey: 'config.schema.fields.refreshConcurrency.label', type: 'number', min: 1, max: 80, desc: '批量刷新账户额度时的 token 级并发数。', descKey: 'config.schema.fields.refreshConcurrency.desc' },
          { key: 'asset_upload_concurrency', label: '上传 Asset 并发数', labelKey: 'config.schema.fields.assetUploadConcurrency.label', type: 'number', desc: 'API 接收文件附件后触发的 Asset 上传任务,全局最大并发数,跨所有请求共享。', descKey: 'config.schema.fields.assetUploadConcurrency.desc' },
          { key: 'asset_list_concurrency', label: '查询 Asset 并发数', labelKey: 'config.schema.fields.assetListConcurrency.label', type: 'number', desc: 'list_assets 接口的全局最大并发数,跨所有请求共享。', descKey: 'config.schema.fields.assetListConcurrency.desc' },
          { key: 'asset_delete_concurrency', label: '删除 Asset 并发数', labelKey: 'config.schema.fields.assetDeleteConcurrency.label', type: 'number', desc: 'delete_asset 接口的全局最大并发数,同时作为管理后台批量清理的 token 级默认并发值。', descKey: 'config.schema.fields.assetDeleteConcurrency.desc' },
        ]
      },
    ]
  },
  {
    id: 'proxy', label: '网络代理', labelKey: 'config.schema.tabs.proxy',
    groups: [
      {
        title: '出站代理设置', titleKey: 'config.schema.groups.egressProxy',
        section: 'proxy.egress',
        fields: [
          {
            key: 'mode',
            label: '代理模式',
            labelKey: 'config.schema.fields.proxyMode.label',
            type: 'select',
            options: [
              { value: 'direct', label: '直连', labelKey: 'config.schema.options.proxyMode.direct' },
              { value: 'single_proxy', label: '代理(固定)', labelKey: 'config.schema.options.proxyMode.singleProxy' },
              { value: 'proxy_pool', label: '代理(轮转)', labelKey: 'config.schema.options.proxyMode.proxyPool' },
            ],
            desc: '控制出站流量代理策略。direct 为直连;single_proxy 使用固定代理;proxy_pool 在代理池中轮转。',
            descKey: 'config.schema.fields.proxyMode.desc',
          },
          {
            key: 'proxy_url',
            label: '基础代理 URL',
            labelKey: 'config.schema.fields.proxyUrl.label',
            type: 'text',
            wide: true,
            desc: 'API 流量的出站代理地址,支持 http、https、socks5 协议。',
            descKey: 'config.schema.fields.proxyUrl.desc',
            showIf: { path: 'proxy.egress.mode', values: ['single_proxy'] },
          },
          {
            key: 'resource_proxy_url',
            label: '资源代理 URL',
            labelKey: 'config.schema.fields.resourceProxyUrl.label',
            type: 'text',
            wide: true,
            desc: '图片、视频等媒体资源下载的专用代理地址;留空时回落至基础代理。',
            descKey: 'config.schema.fields.resourceProxyUrl.desc',
            showIf: { path: 'proxy.egress.mode', values: ['single_proxy'] },
          },
          {
            key: 'proxy_pool',
            label: '基础代理池',
            labelKey: 'config.schema.fields.proxyPool.label',
            type: 'textarea',
            desc: 'API 流量代理池,每行一个代理 URL,请求时轮转使用。',
            descKey: 'config.schema.fields.proxyPool.desc',
            showIf: { path: 'proxy.egress.mode', values: ['proxy_pool'] },
          },
          {
            key: 'resource_proxy_pool',
            label: '资源代理池',
            labelKey: 'config.schema.fields.resourceProxyPool.label',
            type: 'textarea',
            desc: '媒体资源下载专用代理池,每行一个代理 URL;留空时回落至基础代理池。',
            descKey: 'config.schema.fields.resourceProxyPool.desc',
            showIf: { path: 'proxy.egress.mode', values: ['proxy_pool'] },
          },
          {
            key: 'skip_ssl_verify',
            label: '跳过 SSL 校验',
            labelKey: 'config.schema.fields.skipSslVerify.label',
            type: 'bool',
            desc: '跳过代理服务器 TLS 证书校验,仅在使用自签名证书的代理时启用。',
            descKey: 'config.schema.fields.skipSslVerify.desc',
            showIf: { path: 'proxy.egress.mode', values: ['single_proxy', 'proxy_pool'] },
          },
        ]
      },
      {
        title: 'Cloudflare Clearance', titleKey: 'config.schema.groups.clearance',
        section: 'proxy.clearance',
        fields: [
          {
            key: 'mode',
            label: 'Clearance 校准',
            labelKey: 'config.schema.fields.clearanceMode.label',
            type: 'select',
            options: [
              { value: 'none', label: '关闭', labelKey: 'config.schema.options.clearanceMode.none' },
              { value: 'manual', label: '手动', labelKey: 'config.schema.options.clearanceMode.manual' },
              { value: 'flaresolverr', label: 'FlareSolverr', labelKey: 'config.schema.options.clearanceMode.flaresolverr' },
            ],
            desc: '控制 Cloudflare Clearance 的获取方式。',
            descKey: 'config.schema.fields.clearanceMode.desc',
          },
          {
            key: 'browser',
            label: '浏览器指纹',
            labelKey: 'config.schema.fields.browserFingerprint.label',
            type: 'text',
            desc: 'curl_cffi 浏览器指纹标识,需与 Cloudflare 期望的 JA3 指纹匹配,例如 chrome136。',
            descKey: 'config.schema.fields.browserFingerprint.desc',
            showIf: { path: 'proxy.clearance.mode', values: ['manual', 'flaresolverr'] },
          },
          {
            key: 'user_agent',
            label: 'User-Agent',
            labelKey: 'config.schema.fields.userAgent.label',
            type: 'text',
            wide: true,
            desc: '请求头中的 User-Agent,需与 Cloudflare 校验 Cookie 时所使用的浏览器保持一致。',
            descKey: 'config.schema.fields.userAgent.desc',
            showIf: { path: 'proxy.clearance.mode', values: ['manual'] },
          },
          {
            key: 'cf_cookies',
            label: 'Cloudflare Cookies',
            labelKey: 'config.schema.fields.cfCookies.label',
            type: 'text',
            wide: true,
            desc: 'Cloudflare 下发的完整 Cookie 字符串,应包含 cf_clearance 等字段。',
            descKey: 'config.schema.fields.cfCookies.desc',
            showIf: { path: 'proxy.clearance.mode', values: ['manual'] },
          },
          {
            key: 'flaresolverr_url',
            label: 'FlareSolverr URL',
            labelKey: 'config.schema.fields.flaresolverrUrl.label',
            type: 'text',
            wide: true,
            desc: 'FlareSolverr 实例的 HTTP 服务地址。',
            descKey: 'config.schema.fields.flaresolverrUrl.desc',
            showIf: { path: 'proxy.clearance.mode', values: ['flaresolverr'] },
          },
          {
            key: 'timeout_sec',
            label: '挑战超时(秒)',
            labelKey: 'config.schema.fields.challengeTimeout.label',
            type: 'number',
            desc: 'FlareSolverr 完成 Cloudflare 挑战允许的最长等待时长。',
            descKey: 'config.schema.fields.challengeTimeout.desc',
            showIf: { path: 'proxy.clearance.mode', values: ['flaresolverr'] },
          },
          {
            key: 'refresh_interval',
            label: '刷新间隔(秒)',
            labelKey: 'config.schema.fields.refreshInterval.label',
            type: 'number',
            desc: 'Clearance Cookie 预热刷新任务的调度间隔。',
            descKey: 'config.schema.fields.refreshInterval.desc',
            showIf: { path: 'proxy.clearance.mode', values: ['flaresolverr'] },
          },
        ]
      },
      {
        title: '重试策略', titleKey: 'config.schema.groups.retry',
        section: 'retry',
        fields: [
          { key: 'max_retries', label: '应用层重试上限', labelKey: 'config.schema.fields.maxRetries.label', type: 'number', desc: '请求失败后的应用层最大重试次数;0 表示不重试。适用于 chat.completions 与 responses 端点。', descKey: 'config.schema.fields.maxRetries.desc' },
          { key: 'on_codes', label: '应用层重试触发状态码', labelKey: 'config.schema.fields.retryCodes.label', type: 'text', desc: '收到指定 HTTP 状态码时触发应用层重试,多个值请使用英文逗号分隔,例如 429,503。', descKey: 'config.schema.fields.retryCodes.desc' },
          { key: 'reset_session_status_codes', label: '传输层会话重建状态码', labelKey: 'config.schema.fields.resetSessionCodes.label', type: 'text', desc: '收到指定 HTTP 状态码时自动重建传输层代理会话(Transport Session),多个值请使用英文逗号分隔。', descKey: 'config.schema.fields.resetSessionCodes.desc' },
        ]
      },
      {
        title: '请求超时设置', titleKey: 'config.schema.groups.timeouts',
        section: 'chat',
        fields: [
          { key: 'timeout', section: 'chat', label: '对话请求超时(秒)', labelKey: 'config.schema.fields.chatTimeout.label', type: 'number', desc: '对话与图像编辑请求的 HTTP 连接超时时间。', descKey: 'config.schema.fields.chatTimeout.desc' },
          { key: 'timeout', section: 'image', label: '图像请求超时(秒)', labelKey: 'config.schema.fields.imageTimeout.label', type: 'number', desc: '图像生成 WebSocket 请求的总超时时间。', descKey: 'config.schema.fields.imageTimeout.desc' },
          { key: 'stream_timeout', section: 'image', label: '图像流式空闲超时(秒)', type: 'number', desc: '图像生成 WebSocket 在流式接收阶段允许的最长连续空闲等待时长。' },
          { key: 'timeout', section: 'video', label: '视频请求超时(秒)', labelKey: 'config.schema.fields.videoTimeout.label', type: 'number', desc: '视频生成请求的统一超时时间。', descKey: 'config.schema.fields.videoTimeout.desc' },
          { key: 'timeout', section: 'voice', label: '语音请求超时(秒)', labelKey: 'config.schema.fields.voiceTimeout.label', type: 'number', desc: '语音请求的统一超时时间。', descKey: 'config.schema.fields.voiceTimeout.desc' },
          { key: 'timeout', section: 'nsfw', label: 'NSFW 处理超时(秒)', labelKey: 'config.schema.fields.nsfwTimeout.label', type: 'number', desc: 'set_birth_date 与 enable_nsfw 接口调用的超时时间。', descKey: 'config.schema.fields.nsfwTimeout.desc' },
          { key: 'upload_timeout', section: 'asset', label: '资产上传超时(秒)', labelKey: 'config.schema.fields.assetUploadTimeout.label', type: 'number', desc: 'Asset 上传接口的超时时间。', descKey: 'config.schema.fields.assetUploadTimeout.desc' },
          { key: 'download_timeout', section: 'asset', label: '资产下载超时(秒)', labelKey: 'config.schema.fields.assetDownloadTimeout.label', type: 'number', desc: 'Asset 下载接口的超时时间。', descKey: 'config.schema.fields.assetDownloadTimeout.desc' },
          { key: 'list_timeout', section: 'asset', label: '资产查询超时(秒)', labelKey: 'config.schema.fields.assetListTimeout.label', type: 'number', desc: 'Asset 查询接口的超时时间。', descKey: 'config.schema.fields.assetListTimeout.desc' },
          { key: 'delete_timeout', section: 'asset', label: '资产删除超时(秒)', labelKey: 'config.schema.fields.assetDeleteTimeout.label', type: 'number', desc: 'Asset 删除接口的超时时间。', descKey: 'config.schema.fields.assetDeleteTimeout.desc' },
        ]
      },
    ]
  },
  {
    id: 'cache', label: '缓存存储', labelKey: 'config.schema.tabs.cache',
    groups: [
      {
        title: '本地媒体缓存', titleKey: 'config.schema.groups.localMediaCache',
        section: 'cache.local',
        fields: [
          {
            key: 'image_max_mb',
            label: '图片缓存上限(MB)',
            labelKey: 'config.schema.fields.imageCacheMaxMb.label',
            type: 'number',
            desc: '0 表示不限制。仅对本地代理落盘生效;超限后按最旧文件优先清理,并一次性回落到上限的 60%。',
            descKey: 'config.schema.fields.imageCacheMaxMb.desc',
          },
          {
            key: 'video_max_mb',
            label: '视频缓存上限(MB)',
            labelKey: 'config.schema.fields.videoCacheMaxMb.label',
            type: 'number',
            desc: '0 表示不限制。仅对本地代理落盘生效;超限后按最旧文件优先清理,并一次性回落到上限的 60%。',
            descKey: 'config.schema.fields.videoCacheMaxMb.desc',
          },
        ]
      },
    ]
  },
];

let SCHEMA = [];
let _cfg = {};
let _dirty = {};
let _activeTab = SCHEMA_DEF[0].id;
let _configLoaded = false;
let _rowRefs = new Map();
let _tabButtons = new Map();
let _tabDirtyCounts = new Map();
let _tabFieldIndex = new Map();
let _conditionalRows = [];
let _selectRefs = [];
let _showIfDeps = new Map();
let _disabledSelectDeps = new Map();

function tr(key, params, fallback) {
  if (!key) return fallback ?? '';
  const value = t(key, params);
  return value === key ? (fallback ?? key) : value;
}

function waitI18n() {
  return new Promise((resolve) => I18n.onReady(resolve));
}

function _addDependency(depMap, path, target) {
  if (!path || !target) return;
  if (!depMap.has(path)) depMap.set(path, []);
  depMap.get(path).push(target);
}

function _showIfPaths(showIf) {
  if (!showIf) return [];
  return [typeof showIf === 'string' ? showIf : showIf.path].filter(Boolean);
}

function _disabledWhenPaths(condition) {
  if (condition === 'no_app_url') return ['app.app_url'];
  return [];
}

function _collectDependentTargets(paths, depMap) {
  if (!Array.isArray(paths) || !paths.length) return [];
  const seen = new Set();
  const items = [];
  paths.forEach((path) => {
    (depMap.get(path) || []).forEach((target) => {
      if (seen.has(target)) return;
      seen.add(target);
      items.push(target);
    });
  });
  return items;
}

function _syncTabDirtyState(tabId) {
  const btn = _tabButtons.get(tabId);
  if (!btn) return;
  btn.classList.toggle('dirty', (_tabDirtyCounts.get(tabId) || 0) > 0);
}

function _updateDirtyCount(fp, delta) {
  const tabId = _tabFieldIndex.get(fp);
  if (!tabId || !delta) return;
  const next = Math.max(0, (_tabDirtyCounts.get(tabId) || 0) + delta);
  _tabDirtyCounts.set(tabId, next);
  _syncTabDirtyState(tabId);
}

function _resetRenderCaches() {
  _rowRefs = new Map();
  _tabButtons = new Map();
  _tabDirtyCounts = new Map();
  _tabFieldIndex = new Map();
  _conditionalRows = [];
  _selectRefs = [];
  _showIfDeps = new Map();
  _disabledSelectDeps = new Map();
}

function _localizeOption(opt) {
  if (typeof opt !== 'object') return opt;
  return {
    ...opt,
    label: tr(opt.labelKey, null, opt.label ?? opt.value),
    ...(opt.disabledTipKey ? { disabledTip: tr(opt.disabledTipKey, null, opt.disabledTip ?? '') } : {}),
  };
}

function _localizeField(field) {
  return {
    ...field,
    label: field.labelKey ? tr(field.labelKey, null, field.label ?? field.key) : (field.label ?? field.key),
    desc: field.descKey ? tr(field.descKey, null, field.desc ?? '') : (field.desc ?? ''),
    help: field.helpKey ? tr(field.helpKey, null, field.help ?? '') : (field.help ?? ''),
    options: field.options ? field.options.map(_localizeOption) : field.options,
  };
}

function buildSchema() {
  return SCHEMA_DEF.map((tab) => ({
    ...tab,
    label: tr(tab.labelKey, null, tab.label ?? tab.id),
    groups: tab.groups.map((group) => ({
      ...group,
      title: group.titleKey ? tr(group.titleKey, null, group.title ?? '') : (group.title ?? ''),
      fields: group.fields.map(_localizeField),
    })),
  }));
}

function applyConfigI18n() {
  document.title = tr('config.pageTitle', null, 'Grok2API - 配置管理');
  SCHEMA = buildSchema();
  if (!_configLoaded) return;
  renderAll();
  _refreshDirtyState({ autoNormalizeSelects: false });
}

async function _api(method, path, body) {
  const key = await adminKey.get();
  const r = await fetch(ADMIN_API + path, {
    method,
    headers: { ...(body != null && { 'Content-Type': 'application/json' }), Authorization: `Bearer ${key}` },
    ...(body != null && { body: JSON.stringify(body) }),
  });
  if (!r.ok) { const d = await r.json().catch(() => ({})); throw new Error(d.detail || r.status); }
  return r.json();
}

function _getByPath(obj, dottedPath) {
  return dottedPath.split('.').reduce((node, k) =>
    (node != null && typeof node === 'object') ? node[k] : undefined, obj);
}

function _setByPath(obj, dottedPath, value) {
  const keys = dottedPath.split('.');
  let cur = obj;
  for (let i = 0; i < keys.length - 1; i++) {
    if (cur[keys[i]] == null || typeof cur[keys[i]] !== 'object') cur[keys[i]] = {};
    cur = cur[keys[i]];
  }
  cur[keys[keys.length - 1]] = value;
}

function _evalDisabledWhen(condition) {
  if (condition === 'no_app_url') {
    const v = 'app.app_url' in _dirty ? _dirty['app.app_url'] : _getByPath(_cfg, 'app.app_url');
    return !v || String(v).trim() === '';
  }
  return false;
}

function _evalShowIf(showIf) {
  if (!showIf) return true;
  const path = typeof showIf === 'string' ? showIf : showIf.path;
  const cur  = path in _dirty ? _dirty[path] : _getByPath(_cfg, path);
  if (typeof showIf === 'string') return !!cur;
  return showIf.values.includes(cur);
}

function _fullPath(section, key) { return `${section}.${key}`; }

function _getValue(section, key, field) {
  const value = _getByPath(_cfg, _fullPath(section, key));
  return value === undefined && field && Object.prototype.hasOwnProperty.call(field, 'default')
    ? field.default
    : value;
}

function _getCurrentValue(section, key, field) {
  const fp = _fullPath(section, key);
  return fp in _dirty ? _dirty[fp] : _getValue(section, key, field);
}

function _el(tag, attrs, ...children) {
  const el = document.createElement(tag);
  Object.entries(attrs || {}).forEach(([k, v]) => {
    if (k === 'class') el.className = v;
    else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
    else el.setAttribute(k, v);
  });
  children.flat().forEach(c => {
    if (c == null) return;
    el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
  });
  return el;
}

let _helpTipEl = null;
let _activeHelpButton = null;

function _hideHelpTip() {
  if (_activeHelpButton) _activeHelpButton.removeAttribute('aria-describedby');
  if (_helpTipEl) _helpTipEl.remove();
  _helpTipEl = null;
  _activeHelpButton = null;
}

function _positionHelpTip(button, tip) {
  const margin = 12;
  const rect = button.getBoundingClientRect();
  const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
  const maxWidth = Math.max(120, viewportWidth - margin * 2);

  tip.style.maxWidth = `${Math.min(320, maxWidth)}px`;
  tip.style.left = '0px';
  tip.style.top = '0px';

  const tipRect = tip.getBoundingClientRect();
  let left = rect.left + rect.width / 2 - tipRect.width / 2;
  left = Math.max(margin, Math.min(left, viewportWidth - tipRect.width - margin));

  let placement = 'top';
  let top = rect.top - tipRect.height - 8;
  if (top < margin) {
    placement = 'bottom';
    top = rect.bottom + 8;
  }
  if (top + tipRect.height > viewportHeight - margin) {
    top = Math.max(margin, viewportHeight - tipRect.height - margin);
  }

  const arrowLeft = Math.max(12, Math.min(rect.left + rect.width / 2 - left, tipRect.width - 12));
  tip.dataset.placement = placement;
  tip.style.setProperty('--arrow-left', `${arrowLeft}px`);
  tip.style.left = `${left}px`;
  tip.style.top = `${top}px`;
}

function _showHelpTip(button) {
  const text = button.getAttribute('data-tip');
  if (!text) return;
  _hideHelpTip();

  const tip = _el('div', {
    class: 'cfg-help-tip',
    id: 'cfg-help-tip',
    role: 'tooltip',
  }, text);
  document.body.appendChild(tip);
  button.setAttribute('aria-describedby', 'cfg-help-tip');

  _helpTipEl = tip;
  _activeHelpButton = button;
  _positionHelpTip(button, tip);
  requestAnimationFrame(() => tip.classList.add('visible'));
}

window.addEventListener('resize', _hideHelpTip);
window.addEventListener('scroll', _hideHelpTip, true);
document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') _hideHelpTip();
});
document.addEventListener('click', (event) => {
  if (!event.target.closest?.('.cfg-help')) _hideHelpTip();
});

function renderInput(field, section, value) {
  const fp = _fullPath(section, field.key);

  const onChange = (v) => {
    const wasDirty = fp in _dirty;
    const orig = _getValue(section, field.key, field);
    const same = String(orig) === String(v) || orig === v;
    if (same) delete _dirty[fp]; else _dirty[fp] = v;
    const isDirty = fp in _dirty;
    if (wasDirty !== isDirty) _updateDirtyCount(fp, isDirty ? 1 : -1);
    _refreshRow(section, field.key);
    _refreshDirtyState({ changedPaths: [fp] });
  };

  if (field.type === 'bool') {
    const chk = document.createElement('input');
    chk.type = 'checkbox';
    chk.checked = Boolean(value);
    chk.id = `field-${section}-${field.key}`;
    chk.addEventListener('change', () => onChange(chk.checked));
    const track = _el('span', { class: 'toggle-track' });
    const label = _el('label', { class: 'toggle', for: chk.id }, chk, track);
    return label;
  }

  if (field.type === 'select') {
    const sel = _el('select', { class: 'cfg-select', id: `field-${section}-${field.key}` });
    const deps = new Set();
    (field.options || []).forEach(opt => {
      const o = document.createElement('option');
      o.value = (typeof opt === 'object') ? opt.value : opt;
      o.textContent = (typeof opt === 'object') ? opt.label : opt;
      if (o.value === value) o.selected = true;
      if (typeof opt === 'object' && opt.disabledWhen) {
        o.dataset.disabledWhen = opt.disabledWhen;
        if (opt.disabledTip) o.dataset.disabledTip = opt.disabledTip;
        const isDisabled = _evalDisabledWhen(opt.disabledWhen);
        o.disabled = isDisabled;
        if (isDisabled && opt.disabledTip) o.title = opt.disabledTip;
        _disabledWhenPaths(opt.disabledWhen).forEach((path) => deps.add(path));
      }
      sel.appendChild(o);
    });
    if (deps.size) {
      _selectRefs.push(sel);
      deps.forEach((path) => _addDependency(_disabledSelectDeps, path, sel));
    }
    sel.addEventListener('change', () => onChange(sel.value));
    return sel;
  }

  if (field.type === 'textarea') {
    const ta = _el('textarea', { class: 'cfg-textarea', id: `field-${section}-${field.key}`,
      rows: '3', placeholder: '' });
    ta.value = value ?? '';
    ta.addEventListener('input', () => onChange(ta.value));
    return ta;
  }

  if (field.type === 'number') {
    const attrs = { class: 'cfg-number', type: 'number',
      id: `field-${section}-${field.key}`, value: value ?? '' };
    if (field.min != null) attrs.min = field.min;
    if (field.max != null) attrs.max = field.max;
    const inp = _el('input', attrs);
    inp.addEventListener('input', () => {
      let n = inp.value === '' ? '' : Number(inp.value);
      if (typeof n === 'number' && !isNaN(n)) {
        if (field.min != null && n < field.min) n = field.min;
        if (field.max != null && n > field.max) n = field.max;
        if (inp.value !== String(n)) inp.value = n;
      }
      onChange(n);
    });
    return inp;
  }

  const inp = _el('input', {
    class: `cfg-text${field.wide ? ' wide' : ''}`,
    type: field.type === 'password' ? 'password' : 'text',
    id: `field-${section}-${field.key}`,
    value: value ?? '',
    autocomplete: 'off',
  });
  inp.addEventListener('input', () => onChange(inp.value));

  if (field.rand) {
    const btn = _el('button', { class: 'cfg-rand-btn', type: 'button', title: tr('config.randomize', null, '随机生成'), onclick: () => {
      const uuid = crypto.randomUUID().replace(/-/g, '').slice(0, 24);
      inp.value = uuid;
      inp.type = 'text';
      onChange(uuid);
    }});
    btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="3"/><circle cx="8" cy="8" r="1.5" fill="currentColor" stroke="none"/><circle cx="16" cy="8" r="1.5" fill="currentColor" stroke="none"/><circle cx="8" cy="16" r="1.5" fill="currentColor" stroke="none"/><circle cx="16" cy="16" r="1.5" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/></svg>';
    const wrap = _el('div', { style: 'display:flex;align-items:center;gap:6px;flex:1;min-width:0' }, inp, btn);
    return wrap;
  }

  return inp;
}

function renderRow(field, section, tabId) {
  const fp      = _fullPath(section, field.key);
  const value   = _getValue(section, field.key, field);
  const isDirty = fp in _dirty;

  const dot   = _el('span', { class: 'cfg-modified-dot' });
  const input = renderInput(field, section, isDirty ? _dirty[fp] : value);
  const labelChildren = [field.label];

  if (section === 'app' && field.key === 'webui_enabled') {
    const btn = _el('button', {
      class: 'cfg-inline-action',
      type: 'button',
      title: '打开 WebUI',
      'aria-label': '打开 WebUI',
      'data-webui-link': 'true',
      onclick: () => window.open('/webui/login', '_blank', 'noopener,noreferrer'),
    });
    btn._configField = field;
    btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 5h5v5"/><path d="M10 14 19 5"/><path d="M19 14v5h-14v-14h5"/></svg>';
    btn.disabled = !Boolean(_getCurrentValue(section, field.key, field));
    labelChildren.push(btn);
  }

  if (field.help) {
    labelChildren.push(_el('button', {
      class: 'cfg-help',
      type: 'button',
      'aria-label': field.help,
      'data-tip': field.help,
      onmouseenter: (event) => _showHelpTip(event.currentTarget),
      onmouseleave: _hideHelpTip,
      onfocus: (event) => _showHelpTip(event.currentTarget),
      onblur: _hideHelpTip,
      onclick: (event) => {
        event.preventDefault();
        event.stopPropagation();
        _showHelpTip(event.currentTarget);
      },
    }, '?'));
  }

  labelChildren.push(dot);

  const labelCol = _el('div', { class: 'cfg-label-col' },
    _el('div', { class: 'cfg-label' }, labelChildren),
    field.desc ? _el('div', { class: 'cfg-desc' }, field.desc) : null,
  );
  const inputCol = _el('div', { class: `cfg-input-col${field.type === 'bool' ? ' is-bool' : ''}` }, input);

  const row = _el('div', {
    class: `cfg-row${isDirty ? ' modified' : ''}`,
    'data-section': section,
    'data-key': field.key,
  }, labelCol, inputCol);

  _rowRefs.set(fp, row);
  _tabFieldIndex.set(fp, tabId);
  if (isDirty) _tabDirtyCounts.set(tabId, (_tabDirtyCounts.get(tabId) || 0) + 1);

  if (field.showIf) {
    row._showIfSpec = field.showIf;
    row.style.display = _evalShowIf(field.showIf) ? '' : 'none';
    _conditionalRows.push(row);
    _showIfPaths(field.showIf).forEach((path) => _addDependency(_showIfDeps, path, row));
  }

  return row;
}

function renderGroup(group, tabId) {
  const section = group.section;
  const rows    = group.fields.map(f => renderRow(f, f.section || section, tabId));
  const titleEl = _el('div', { class: 'cfg-group-title' }, group.title || '');
  const wrap    = _el('div', { class: 'cfg-group' }, titleEl, ...rows);
  return wrap;
}

function renderPanel(tab) {
  const panel = _el('div', { class: `cfg-panel${tab.id === _activeTab ? ' active' : ''}`,
    id: `panel-${tab.id}` });
  tab.groups.forEach(g => panel.appendChild(renderGroup(g, tab.id)));
  return panel;
}

function renderAll() {
  const nav    = document.getElementById('cfg-nav');
  const panels = document.getElementById('cfg-panels');
  _resetRenderCaches();
  nav.innerHTML = ''; panels.innerHTML = '';

  SCHEMA.forEach(tab => {
    const btn = _el('button', {
      class: `cfg-tab${tab.id === _activeTab ? ' active' : ''}`,
      onclick: () => switchTab(tab.id),
      'data-tab': tab.id,
    }, tab.label, _el('span', { class: 'dot' }));
    _tabButtons.set(tab.id, btn);
    nav.appendChild(btn);

    panels.appendChild(renderPanel(tab));
  });
  _tabButtons.forEach((_, tabId) => _syncTabDirtyState(tabId));
}

function switchTab(id) {
  _activeTab = id;
  document.querySelectorAll('.cfg-tab').forEach(b =>
    b.classList.toggle('active', b.dataset.tab === id));
  document.querySelectorAll('.cfg-panel').forEach(p =>
    p.classList.toggle('active', p.id === `panel-${id}`));
}

function _refreshRow(section, key) {
  const row = _rowRefs.get(_fullPath(section, key));
  if (row) row.classList.toggle('modified', _fullPath(section, key) in _dirty);
}

function _refreshConditionalRows(changedPaths = null) {
  const rows = changedPaths ? _collectDependentTargets(changedPaths, _showIfDeps) : _conditionalRows;
  rows.forEach((row) => {
    row.style.display = _evalShowIf(row._showIfSpec) ? '' : 'none';
  });
}

function _refreshSelectStates(changedPaths = null, { autoNormalizeSelects = true } = {}) {
  const selects = changedPaths ? _collectDependentTargets(changedPaths, _disabledSelectDeps) : _selectRefs;
  selects.forEach((sel) => {
    let anyChanged = false;
    [...sel.options].forEach(o => {
      if (!o.dataset.disabledWhen) return;
      const isDisabled = _evalDisabledWhen(o.dataset.disabledWhen);
      o.disabled = isDisabled;
      o.title = isDisabled ? (o.dataset.disabledTip || '') : '';
      if (autoNormalizeSelects && isDisabled && o.selected) anyChanged = true;
    });
    if (anyChanged) {
      const firstEnabled = [...sel.options].find(o => !o.disabled);
      if (firstEnabled) {
        firstEnabled.selected = true;
        sel.dispatchEvent(new Event('change'));
      }
    }
  });
}

function _refreshDirtyState({ autoNormalizeSelects = true, changedPaths = null } = {}) {
  const n = Object.keys(_dirty).length;
  document.getElementById('btn-save').disabled  = n === 0;
  document.getElementById('btn-reset').disabled = n === 0;
  const bar = document.getElementById('save-bar');
  bar.classList.toggle('visible', n > 0);
  document.getElementById('save-bar-msg').textContent =
    n === 0
      ? tr('config.unsavedDefault', null, '存在未保存的更改')
      : n === 1
        ? tr('config.unsavedSingle', { n }, '存在 1 项未保存的更改')
        : tr('config.unsavedMultiple', { n }, `存在 ${n} 项未保存的更改`);

  const webuiLinkBtn = document.querySelector('[data-webui-link="true"]');
  if (webuiLinkBtn) {
    const enabled = Boolean(_getCurrentValue('app', 'webui_enabled', webuiLinkBtn._configField));
    webuiLinkBtn.disabled = !enabled;
    webuiLinkBtn.title = enabled ? '打开 WebUI' : '启用 WebUI 后可打开';
    webuiLinkBtn.setAttribute('aria-label', webuiLinkBtn.title);
  }

  _refreshConditionalRows(changedPaths);
  _refreshSelectStates(changedPaths, { autoNormalizeSelects });
  if (!changedPaths) _tabButtons.forEach((_, tabId) => _syncTabDirtyState(tabId));
}

async function load() {
  try {
    _cfg = await _api('GET', '/config');
    _dirty = {};
    _configLoaded = true;
    if (!SCHEMA.length) SCHEMA = buildSchema();
    renderAll();
    _refreshDirtyState({ autoNormalizeSelects: false });
  } catch (e) {
    showToast(tr('config.loadFailed', { message: e.message }, `配置加载失败: ${e.message}`), 'error');
  }
}

async function doSave() {
  if (!Object.keys(_dirty).length) return;

  const patch = {};
  Object.entries(_dirty).forEach(([fp, v]) => _setByPath(patch, fp, v));

  try {
    showToast(tr('config.saving', null, '正在保存更改…'), 'info');
    await _api('POST', '/config', patch);
    Object.entries(_dirty).forEach(([fp, v]) => _setByPath(_cfg, fp, v));
    _dirty = {};
    renderAll();
    _refreshDirtyState({ autoNormalizeSelects: false });
    showToast(tr('config.saveSuccess', null, '更改已保存'), 'success');
  } catch (e) {
    showToast(tr('config.saveFailed', { message: e.message }, `保存更改失败: ${e.message}`), 'error');
  }
}

function doReset() {
  if (!Object.keys(_dirty).length) return;
  _dirty = {};
  renderAll();
  _refreshDirtyState({ autoNormalizeSelects: false });
  showToast(tr('config.resetSuccess', null, '未保存的更改已撤销'), 'info');
}

(async () => {
  try {
    SCHEMA = buildSchema();

    waitI18n().then(() => {
      applyConfigI18n();
    }).catch((e) => {
      console.error('i18n init failed', e);
    });

    await renderAdminHeader?.();
    await renderSiteFooter?.();
    const key = await adminKey.get();
    if (!key || !await verifyKey(ADMIN_API + '/verify', key).catch(() => false))
      return location.href = '/admin/login';
    await load();
  } catch (e) {
    console.error('config page boot failed', e);
    showToast(tr('config.loadFailed', { message: e.message }, `配置页初始化失败: ${e.message}`), 'error');
  }
})();
</script>
</body>
</html>