File size: 97,250 Bytes
79dca2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="zh-CN" data-theme="cool">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>驱动管理后台</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%E2%9A%99%EF%B8%8F%3C/text%3E%3C/svg%3E">
<style>
/* ════════════════════════════════════════
   Design System — Theme Variables
   ════════════════════════════════════════ */
:root {
  --bg-page: #f0f4f8;
  --bg-card: #ffffff;
  --bg-elevated: #ffffff;
  --bg-subtle: #f8fafc;
  --bg-sidebar: #ffffff;
  --text-primary: #0f172a;
  --text-secondary: #475569;
  --text-muted: #94a3b8;
  --border-light: #e2e8f0;
  --border-subtle: #f1f5f9;
  --shadow-card: 0 1px 3px rgba(0,0,0,.04), 0 1px 2px rgba(0,0,0,.06);
  --shadow-modal: 0 8px 32px rgba(0,0,0,.15);
  --header-start: #0b1426;
  --header-mid: #14203a;
  --header-end: #0b1426;
  --header-text: #f1f5f9;
  --header-sub: #64748b;
  --sidebar-active-bg: #e8f0fe;
  --sidebar-active-border: #3b82f6;
  --input-border: #d0d5dd;
  --input-focus: #3b82f6;
  --btn-save-bg: #0f172a;
  --btn-save-hover: #1e293b;
  --btn-cancel-bg: #f1f5f9;
  --btn-cancel-border: #d0d5dd;
  --btn-cancel-text: #475569;
  --os-android: #16a34a;
  --os-windows: #2563eb;
  --os-linux: #d97706;
  --del-hover-bg: #fef2f2;
  --del-hover-text: #dc2626;
  --scrollbar-track: #f1f5f9;
  --scrollbar-thumb: #cbd5e1;
  --bg-pattern: rgba(59,130,246,.015);
}

[data-theme="warm"] {
  --bg-page: #fef7ee;
  --bg-card: #ffffff;
  --bg-elevated: #ffffff;
  --bg-subtle: #fffbeb;
  --bg-sidebar: #ffffff;
  --text-primary: #1c1917;
  --text-secondary: #57534e;
  --text-muted: #a8a29e;
  --border-light: #e7e5e4;
  --border-subtle: #f5f5f4;
  --shadow-card: 0 1px 3px rgba(120,80,40,.04), 0 1px 2px rgba(120,80,40,.06);
  --shadow-modal: 0 8px 32px rgba(120,80,40,.15);
  --header-start: #1c130d;
  --header-mid: #2d1f14;
  --header-end: #1c130d;
  --header-text: #fefce8;
  --header-sub: #a8a29e;
  --sidebar-active-bg: #fef3c7;
  --sidebar-active-border: #d97706;
  --input-border: #d6d3d1;
  --input-focus: #d97706;
  --btn-save-bg: #1c1917;
  --btn-save-hover: #292524;
  --btn-cancel-bg: #f5f5f4;
  --btn-cancel-border: #d6d3d1;
  --btn-cancel-text: #57534e;
  --os-android: #16a34a;
  --os-windows: #2563eb;
  --os-linux: #dc2626;
  --del-hover-bg: #fef2f2;
  --del-hover-text: #dc2626;
  --scrollbar-track: #f5f5f4;
  --scrollbar-thumb: #d6d3d1;
  --bg-pattern: rgba(245,158,11,.015);
}

* { margin:0; padding:0; box-sizing:border-box; }
body {
  font-family:"PingFang SC","Microsoft YaHei","Helvetica Neue",sans-serif;
  background:var(--bg-page); color:var(--text-primary); min-height:100vh;
  transition:background .4s ease,color .3s ease;
}
body::before {
  content:''; position:fixed; inset:0; z-index:-1;
  background-image:
    linear-gradient(var(--bg-pattern) 1px, transparent 1px),
    linear-gradient(90deg, var(--bg-pattern) 1px, transparent 1px);
  background-size:60px 60px;
}

/* ── Theme Toggle (on login screen) ── */
.theme-toggle-wrap {
  position:fixed; top:20px; right:20px; z-index:100;
}
.theme-toggle {
  width:44px; height:44px; border-radius:50%;
  border:2px solid var(--border-light); background:var(--bg-card);
  cursor:pointer; font-size:20px; display:flex; align-items:center; justify-content:center;
  transition:all .3s cubic-bezier(.4,0,.2,1);
  box-shadow:0 2px 12px rgba(0,0,0,.08);
  backdrop-filter:blur(8px);
}
.theme-toggle:hover { transform:scale(1.1); box-shadow:0 4px 20px rgba(0,0,0,.12); }

/* ── Login ── */
#loginScreen {
  display:flex; align-items:center; justify-content:center; min-height:100vh;
  background:linear-gradient(135deg,var(--header-start),var(--header-mid));
  transition:background .4s ease;
}
.login-card {
  background:var(--bg-card); border-radius:16px; padding:44px; width:400px;
  box-shadow:var(--shadow-modal); transition:all .4s ease;
  position:relative; overflow:hidden;
}
.login-card::before {
  content:''; position:absolute; top:0; left:0; right:0; height:4px;
  background:linear-gradient(90deg,var(--header-mid),var(--header-sub));
}
.login-card h1 { font-size:24px; margin-bottom:4px; color:var(--text-primary); }
.login-card .sub { color:var(--text-muted); font-size:13px; margin-bottom:28px; }
.login-card input {
  width:100%; padding:13px 16px; border:1px solid var(--input-border); border-radius:10px;
  font-size:14px; margin-bottom:14px; outline:none; transition:all .2s;
  background:var(--bg-card); color:var(--text-primary);
}
.login-card input:focus { border-color:var(--input-focus); box-shadow:0 0 0 3px color-mix(in srgb,var(--input-focus) 15%,transparent); }
.login-card button {
  width:100%; padding:13px; background:var(--btn-save-bg); color:#fff; border:none;
  border-radius:10px; font-size:15px; font-weight:600; cursor:pointer;
  transition:all .2s; letter-spacing:1px;
}
.login-card button:hover { background:var(--btn-save-hover); transform:translateY(-1px); box-shadow:0 4px 12px rgba(0,0,0,.1); }
.login-card .error { color:#dc2626; font-size:13px; margin-top:10px; text-align:center; }

/* ── Layout ── */
#adminScreen { display:none; height:100vh; }
.admin-header {
  background:linear-gradient(135deg,var(--header-start),var(--header-mid),var(--header-end));
  color:var(--header-text); padding:14px 24px;
  display:flex; justify-content:space-between; align-items:center;
  transition:background .4s ease;
}
.admin-header h2 { font-size:17px; font-weight:700; letter-spacing:1px; }
.admin-header .user-info { display:flex; align-items:center; gap:12px; font-size:13px; }
.admin-header .user-info .sep {
  width:1px; height:20px; background:rgba(255,255,255,.1);
}
.admin-header .header-left { display:flex; align-items:center; gap:10px; }
.admin-header .header-toggle {
  width:34px; height:34px; border-radius:50%;
  border:1px solid rgba(255,255,255,.12);
  background:rgba(255,255,255,.04);
  cursor:pointer; font-size:16px;
  display:flex; align-items:center; justify-content:center;
  transition:all .2s; flex-shrink:0;
}
.admin-header .header-toggle:hover { background:rgba(255,255,255,.1); border-color:rgba(255,255,255,.25); }
.admin-header .logout-btn {
  background:transparent; color:var(--header-sub); border:1px solid rgba(255,255,255,.1);
  padding:6px 14px; border-radius:8px; cursor:pointer; font-size:12px;
  transition:all .2s; text-decoration:none;
}
.admin-header .logout-btn:hover { color:var(--header-text); border-color:rgba(255,255,255,.25); background:rgba(255,255,255,.05); }
.admin-body { display:flex; height:calc(100vh - 52px); }

/* ── Sidebar ── */
.sidebar {
  width:280px; min-width:280px; background:var(--bg-sidebar);
  border-right:1px solid var(--border-light); display:flex; flex-direction:column;
  overflow:hidden; transition:all .3s ease;
}
.sidebar-header {
  padding:18px 20px 14px; border-bottom:1px solid var(--border-subtle);
  display:flex; justify-content:space-between; align-items:center;
}
.sidebar-header h3 { font-size:13px; font-weight:600; letter-spacing:1px; text-transform:uppercase; color:var(--text-muted); }
.add-btn {
  background:var(--btn-save-bg); color:#fff; border:none; width:34px; height:34px;
  border-radius:8px; cursor:pointer; font-size:20px; line-height:34px; text-align:center;
  transition:all .2s; display:flex; align-items:center; justify-content:center;
}
.add-btn:hover { background:var(--btn-save-hover); transform:scale(1.08); box-shadow:0 2px 8px rgba(0,0,0,.1); }
.device-list { flex:1; overflow-y:auto; }
.device-list::-webkit-scrollbar { width:4px; }
.device-list::-webkit-scrollbar-track { background:var(--scrollbar-track); }
.device-list::-webkit-scrollbar-thumb { background:var(--scrollbar-thumb); border-radius:2px; }
.device-item {
  padding:14px 20px; cursor:pointer; border-bottom:1px solid var(--border-subtle);
  display:flex; align-items:center; gap:12px; transition:all .15s;
}
.device-item:hover { background:var(--bg-subtle); }
.device-item.active { background:var(--sidebar-active-bg); box-shadow:inset 3px 0 0 var(--sidebar-active-border); }
.device-item .dname { font-size:14px; font-weight:500; }
.device-item .dtype { font-size:11px; color:var(--text-muted); }
.device-item .del-btn {
  margin-left:auto; background:transparent; border:1px solid transparent; color:var(--text-muted);
  cursor:pointer; font-size:13px; padding:5px 12px; border-radius:8px;
  transition:all .15s; line-height:1;
}
.device-item .del-btn:hover { color:var(--del-hover-text); background:var(--del-hover-bg); border-color:var(--del-hover-text); }

/* ── Main content ── */
.main-content { flex:1; padding:24px; overflow-y:auto; }
.main-content::-webkit-scrollbar { width:6px; }
.main-content::-webkit-scrollbar-track { background:var(--scrollbar-track); }
.main-content::-webkit-scrollbar-thumb { background:var(--scrollbar-thumb); border-radius:3px; }
.empty-hint {
  text-align:center; padding:80px 20px; color:var(--text-muted); font-size:14px;
}

/* ── OS section ── */
.section { margin-bottom:32px; }
.section h3 {
  font-size:14px; font-weight:600; margin-bottom:14px;
  display:flex; align-items:center; gap:8px; color:var(--text-primary);
}
.section h3 .count { color:var(--text-muted); font-size:12px; font-weight:400; }

.os-card {
  background:var(--bg-card); border-radius:10px; border:1px solid var(--border-light);
  margin-bottom:10px; overflow:hidden; box-shadow:var(--shadow-card);
  transition:all .2s ease;
}
.os-card:hover { box-shadow:0 4px 16px rgba(0,0,0,.06); border-color:var(--text-muted); }
.os-card-header {
  padding:13px 18px; display:flex; align-items:center; gap:10px; cursor:pointer;
  transition:background .15s;
}
.os-card-header:hover { background:var(--bg-subtle); }
.os-dot { width:9px; height:9px; border-radius:50%; flex-shrink:0; }
.os-dot.android { background:var(--os-android); }
.os-dot.windows { background:var(--os-windows); }
.os-dot.linux { background:var(--os-linux); }
.os-card-header .ov { font-size:14px; font-weight:500; }
.os-card-header .actions { margin-left:auto; display:flex; gap:8px; }
.os-card-header .actions button {
  background:transparent; border:1px solid var(--border-light); color:var(--text-secondary); cursor:pointer;
  padding:6px 14px; border-radius:8px; font-size:12px; font-weight:500; transition:all .15s;
  display:flex; align-items:center; gap:4px;
}
.os-card-header .actions button:hover { background:var(--bg-subtle); color:var(--text-primary); border-color:var(--text-muted); }
.os-card-header .actions button.del:hover { background:var(--del-hover-bg); color:var(--del-hover-text); border-color:var(--del-hover-text); }

/* ── Download items ── */
.dl-section { display:none; padding:4px 16px 16px; }
.dl-section.open { display:block; animation:slideIn .2s ease; }
@keyframes slideIn { from { opacity:0; transform:translateY(-4px); } to { opacity:1; transform:translateY(0); } }
.dl-item {
  display:flex; align-items:center; gap:14px; padding:10px 14px;
  border-radius:8px; transition:background .15s;
}
.dl-item:hover { background:var(--bg-subtle); }
.dl-item .info { flex:1; min-width:0; }
.dl-item .title { font-size:13px; font-weight:500; color:var(--text-primary); }
.dl-item .meta { font-size:11px; color:var(--text-muted); }
.dl-item .link-text { font-size:11px; color:var(--input-focus); word-break:break-all; opacity:.7; }
.dl-item .actions { display:flex; gap:8px; flex-shrink:0; }
.dl-item .actions button {
  background:transparent; border:1px solid var(--border-light); color:var(--text-secondary); cursor:pointer;
  padding:6px 14px; border-radius:8px; font-size:12px; font-weight:500; transition:all .15s;
  display:flex; align-items:center; gap:4px;
}
.dl-item .actions button:hover { background:var(--bg-subtle); color:var(--text-primary); border-color:var(--text-muted); }
.dl-item .actions button.del:hover { background:var(--del-hover-bg); color:var(--del-hover-text); border-color:var(--del-hover-text); }
.add-dl-btn {
  display:block; width:100%; padding:12px; margin-top:8px;
  background:transparent; border:1px dashed var(--border-light); border-radius:8px;
  color:var(--text-muted); cursor:pointer; font-size:13px; transition:all .2s;
}
.add-dl-btn:hover { border-color:var(--input-focus); color:var(--input-focus); background:var(--bg-subtle); }

/* ── Modal ── */
.modal-overlay {
  display:none; position:fixed; top:0; left:0; right:0; bottom:0;
  background:rgba(0,0,0,.4); z-index:1000; align-items:center; justify-content:center;
  backdrop-filter:blur(4px);
}
.modal-overlay.open { display:flex; }
.modal {
  background:var(--bg-card); border-radius:16px; padding:32px; width:480px; max-width:90vw;
  max-height:80vh; overflow-y:auto; box-shadow:var(--shadow-modal);
  transition:all .4s ease;
}
.modal h3 { font-size:18px; margin-bottom:20px; color:var(--text-primary); }
.modal label { display:block; font-size:12px; color:var(--text-secondary); margin-bottom:4px; margin-top:16px; font-weight:500; }
.modal label:first-of-type { margin-top:0; }
.modal input,.modal select,.modal textarea {
  width:100%; padding:11px 14px; border:1px solid var(--input-border); border-radius:10px;
  font-size:14px; outline:none; font-family:inherit; transition:all .2s;
  background:var(--bg-card); color:var(--text-primary);
}
.modal input:focus,.modal select:focus,.modal textarea:focus { border-color:var(--input-focus); box-shadow:0 0 0 3px color-mix(in srgb,var(--input-focus) 15%,transparent); }
.modal textarea { resize:vertical; min-height:60px; }
.modal-actions { display:flex; gap:10px; justify-content:flex-end; margin-top:24px; }
.modal-actions button {
  padding:10px 24px; border-radius:10px; font-size:14px; font-weight:500; cursor:pointer;
  transition:all .2s;
}
.modal-actions .btn-cancel { background:var(--btn-cancel-bg); border:1px solid var(--btn-cancel-border); color:var(--btn-cancel-text); }
.modal-actions .btn-cancel:hover { background:var(--border-light); }
.modal-actions .btn-save { background:var(--btn-save-bg); border:none; color:#fff; }
.modal-actions .btn-save:hover { background:var(--btn-save-hover); transform:translateY(-1px); box-shadow:0 4px 12px rgba(0,0,0,.1); }

/* ── Tabs ── */
.admin-tabs { display:flex; gap:6px; padding:12px 24px; background:var(--bg-page); border-bottom:1px solid var(--border-light); flex-shrink:0; }
.admin-tab { padding:9px 22px; border-radius:8px; cursor:pointer; font-size:13px; font-weight:500; border:none; background:transparent; color:var(--text-muted); transition:all .2s; }
.admin-tab:hover { background:var(--bg-subtle); color:var(--text-secondary); }
.admin-tab.active { background:var(--sidebar-active-bg); color:var(--text-primary); font-weight:600; box-shadow:0 1px 3px rgba(0,0,0,.04); }

/* ── Search ── */
.search-wrap { position:relative; padding:12px 16px 6px; }
.search-icon { position:absolute; left:26px; top:18px; color:var(--text-muted); font-size:14px; pointer-events:none; }
.search-input { width:100%; padding:10px 12px 10px 32px; border:1px solid var(--border-light); border-radius:10px; font-size:13px; outline:none; background:var(--bg-sidebar); color:var(--text-primary); transition:all .2s; }
.search-input:focus { border-color:var(--input-focus); box-shadow:0 0 0 3px color-mix(in srgb,var(--sidebar-active-bg) 40%,transparent); }

/* ── Announcements ── */
.announce-form { background:var(--bg-subtle); border-radius:10px; padding:16px; margin-bottom:16px; border:1px solid var(--border-light); }
.announce-item { padding:14px 18px; border:1px solid var(--border-light); border-radius:10px; margin-bottom:8px; background:var(--bg-card); }
.announce-item .title { font-size:14px; font-weight:600; }
.announce-item .meta { font-size:11px; color:var(--text-muted); margin-top:2px; }
.announce-item .content { font-size:13px; color:var(--text-secondary); margin-top:6px; line-height:1.5; white-space:pre-wrap; }
.announce-item .badge { display:inline-block; padding:1px 8px; border-radius:4px; font-size:10px; font-weight:600; margin-left:8px; }
.announce-item .badge.on { background:#dcfce7; color:#166534; }
.announce-item .badge.off { background:#fef2f2; color:#991b1b; }
.announce-empty { text-align:center; padding:60px 20px; color:var(--text-muted); font-size:14px; }

/* ── Dashboard ── */
.dash-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:14px; margin-bottom:20px; }
.dash-card { background:var(--bg-card); border:1px solid var(--border-light); border-radius:12px; padding:20px; text-align:center; box-shadow:var(--shadow-card); }
.dash-card .num { font-size:30px; font-weight:800; color:var(--text-primary); }
.dash-card .label { font-size:12px; color:var(--text-muted); margin-top:4px; }
.dash-section { background:var(--bg-card); border:1px solid var(--border-light); border-radius:12px; margin-bottom:16px; overflow:hidden; }
.dash-section h3 { font-size:14px; font-weight:600; padding:14px 18px; border-bottom:1px solid var(--border-subtle); margin:0; }
.dash-row { display:flex; justify-content:space-between; padding:10px 18px; font-size:13px; border-bottom:1px solid var(--border-subtle); }
.dash-row:last-child { border-bottom:none; }
.dash-row .name { color:var(--text-secondary); }
.dash-row .count { font-weight:600; color:var(--text-primary); }
</style>
</head>
<body>

<!-- Theme Toggle -->
<div class="theme-toggle-wrap">
  <button class="theme-toggle" id="themeToggle" onclick="toggleTheme()" title="切换冷暖色调">❄️</button>
</div>

<!-- ─── Login ─── -->
<div id="loginScreen">
  <div class="login-card">
    <h1>驱动管理后台</h1>
    <div class="sub">登录以管理设备、系统和下载链接</div>
    <input type="text" id="loginUser" placeholder="用户名" autocomplete="username">
    <input type="password" id="loginPass" placeholder="密码" autocomplete="current-password">
    <input type="password" id="loginKey" placeholder="管理入口密钥" autocomplete="off">
    <button id="loginBtn">登 录</button>
    <div class="error" id="loginError"></div>
  </div>
</div>

<!-- ─── Admin ─── -->
<div id="adminScreen">
  <div class="admin-header">
    <div class="header-left">
      <button class="theme-toggle header-toggle" onclick="toggleTheme()" title="切换冷暖色调">❄️</button>
      <h2>MES 管理后台</h2>
    </div>
    <div class="user-info">
      <span id="userDisplay"></span>
      <span class="sep"></span>
      <a class="logout-btn" href="index.html" target="_blank">公开页面 ↗</a>
      <button class="logout-btn" onclick="logout()">退出</button>
    </div>
  </div>
  <div class="admin-tabs">
      <button class="admin-tab active" data-tab="mesmon" onclick="switchTab('mesmon')">📈 MES 监控</button>
<button class="admin-tab" data-tab="reports" onclick="switchTab('reports')">⚑ 问题上报</button>
<button class="admin-tab" data-tab="snmap" onclick="switchTab('snmap')">📋 映射管理</button>
<button class="admin-tab" data-tab="mes" onclick="switchTab('mes')">🔧 MES 调试</button>
<button class="admin-tab" data-tab="sysset" onclick="switchTab('sysset')">⚙️ 系统设置</button>
<button class="admin-tab" data-tab="profiles" onclick="switchTab('profiles')">🔑 访问码管理</button>
  </div>
  <div class="admin-body">
    <!-- MES Query Monitor Panel -->
    <div id="mesMonPanel" style="display:none;flex:1;overflow-y:auto;padding:24px;">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <h3 style="font-size:18px;margin:0;">📈 MES 查询监控</h3>
        <button onclick="loadMesMonitor()" style="padding:8px 16px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">🔄 刷新</button>
      </div>
      <div class="dash-grid" id="mesDashGrid">
        <div class="dash-card"><div class="num" id="mesStatTotal">-</div><div class="label">总查询次数</div></div>
        <div class="dash-card"><div class="num" id="mesStatToday">-</div><div class="label">今日查询</div></div>
        <div class="dash-card"><div class="num" id="mesStatCache">-</div><div class="label">缓存命中</div></div>
        <div class="dash-card"><div class="num" id="mesStatAvg">-</div><div class="label">平均耗时 (ms)</div></div>
      </div>
      <div class="dash-grid" style="margin-top:16px;">
        <div class="dash-card"><div class="num" id="mesStatError">-</div><div class="label">失败查询</div></div>
        <div class="dash-card"><div class="num" id="mesStatUnique">-</div><div class="label">不同 SN 数</div></div>
        <div class="dash-card"><div class="num" id="mesStatPending">-</div><div class="label">待处理上报</div></div>
        <div class="dash-card"><div class="num" id="mesStatMaps">-</div><div class="label">映射条数 (OS / SN)</div></div>
      </div>
      <div class="dash-section"><h3>每日查询趋势 (近 30 天)</h3><div id="mesDaily"><div class="dash-row" style="color:var(--text-muted)">暂无数据</div></div></div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
        <div class="dash-section"><h3>热门 SN</h3><div id="mesTopSn"><div class="dash-row" style="color:var(--text-muted)">暂无数据</div></div></div>
        <div class="dash-section"><h3>最近查询</h3><div id="mesRecent"><div class="dash-row" style="color:var(--text-muted)">暂无数据</div></div></div>
      </div>
    </div>
    <!-- MES Debug Panel -->
    <div id="mesPanel" style="display:none;flex:1;overflow-y:auto;padding:24px;">
      <h3 style="font-size:18px;margin-bottom:16px;">MES 调试</h3>
      <div style="margin-bottom:16px;">
        <input type="text" id="mesSnInput" placeholder="输入 SN,如 M1TA688A0NXA26E0484" style="flex:1;padding:10px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;background:var(--bg-card);color:var(--text-primary);width:300px;">
        <button onclick="queryMES()" style="margin-left:8px;padding:10px 20px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">查询</button>
      </div>
      <div id="mesResult" style="background:var(--bg-subtle);border:1px solid var(--border-light);border-radius:8px;padding:16px;min-height:300px;font-family:monospace;font-size:12px;white-space:pre-wrap;word-break:break-word;max-height:600px;overflow:auto;"></div>
    </div>
    <!-- System Settings Panel -->
    <div id="profilesPanel" style="display:none;flex:1;overflow-y:auto;padding:24px;">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
        <h3 style="font-size:18px;margin:0;">🔑 访问码管理</h3>
        <button onclick="openProfileEditor()" style="padding:9px 18px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">+ 新建访问码</button>
      </div>
      <p style="color:var(--text-muted);font-size:12px;margin:0 0 16px;line-height:1.7;max-width:760px;">
        每个访问码对应一套可见字段。用户用该访问码登录后,未勾选的字段既不会显示也不会下发到浏览器;勾选「管理员」的访问码可见全部字段。修改后立即生效,已登录的会话会自动失效。
      </p>
      <div id="profileList" style="max-width:900px;"></div>

      <div id="profileModal" style="display:none;position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:1000;align-items:center;justify-content:center;">
        <div style="background:var(--bg-card);border-radius:14px;width:780px;max-width:94vw;max-height:88vh;display:flex;flex-direction:column;box-shadow:0 20px 60px rgba(0,0,0,.25);">
          <div style="padding:16px 22px;border-bottom:1px solid var(--border-light);display:flex;justify-content:space-between;align-items:center;">
            <h3 id="profileModalTitle" style="margin:0;font-size:16px;">新建访问码</h3>
            <button onclick="closeProfileEditor()" style="border:none;background:transparent;font-size:22px;line-height:1;cursor:pointer;color:var(--text-muted);">×</button>
          </div>
          <div style="padding:18px 22px;overflow-y:auto;flex:1;">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px;">
              <label style="font-size:12px;color:var(--text-secondary);">访问码
                <input id="pfCode" type="text" autocomplete="off" placeholder="3-64 位,不含空格" style="width:100%;margin-top:6px;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:14px;background:var(--bg-card);color:var(--text-primary);font-family:monospace;">
              </label>
              <label style="font-size:12px;color:var(--text-secondary);">名称 / 备注
                <input id="pfName" type="text" autocomplete="off" placeholder="例如:产线查询" style="width:100%;margin-top:6px;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:14px;background:var(--bg-card);color:var(--text-primary);">
              </label>
            </div>
            <div style="display:flex;gap:22px;margin-bottom:16px;">
              <label style="font-size:13px;display:flex;align-items:center;gap:7px;cursor:pointer;">
                <input id="pfAdmin" type="checkbox" onchange="onPfAdminChange()" style="accent-color:#3b82f6;">管理员(可见全部字段)
              </label>
              <label style="font-size:13px;display:flex;align-items:center;gap:7px;cursor:pointer;">
                <input id="pfEnabled" type="checkbox" checked style="accent-color:#3b82f6;">启用
              </label>
            </div>
            <div id="pfFieldWrap">
              <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                <span style="font-size:13px;font-weight:600;">可见字段 <span id="pfCount" style="color:var(--text-muted);font-weight:400;font-size:12px;"></span></span>
                <span style="display:flex;gap:6px;">
                  <button type="button" onclick="pfSetAll(true)" style="padding:4px 10px;font-size:11px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-subtle);cursor:pointer;color:var(--text-secondary);">全选</button>
                  <button type="button" onclick="pfSetAll(false)" style="padding:4px 10px;font-size:11px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-subtle);cursor:pointer;color:var(--text-secondary);">全不选</button>
                </span>
              </div>
              <div id="pfFields" style="border:1px solid var(--border-light);border-radius:10px;padding:12px 14px;max-height:330px;overflow-y:auto;background:var(--bg-subtle);"></div>
            </div>
          </div>
          <div style="padding:14px 22px;border-top:1px solid var(--border-light);display:flex;justify-content:flex-end;gap:10px;">
            <button onclick="closeProfileEditor()" style="padding:9px 18px;background:var(--btn-cancel-bg);border:1px solid var(--btn-cancel-border);color:var(--btn-cancel-text);border-radius:8px;cursor:pointer;font-size:13px;">取消</button>
            <button onclick="saveProfile()" style="padding:9px 20px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">保存</button>
          </div>
        </div>
      </div>
    </div>
    <div id="sysPanel" style="display:none;flex:1;overflow-y:auto;padding:24px;">
      <h3 style="font-size:18px;margin:0 0 16px;">⚙️ 系统设置</h3>
      <div class="dash-section" style="max-width:620px;">
        <h3>公开查询访问码</h3>
        <p style="color:var(--text-muted);font-size:12px;margin:0 0 14px;line-height:1.7;">
          用户在前台输入此访问码后才能使用 MES 查询。修改后立即生效,无需重启服务;已登录的用户需重新输入新访问码。
        </p>
        <div style="display:flex;gap:8px;align-items:center;">
          <input id="accessCodeInput" type="text" placeholder="至少 6 位,不含空格" autocomplete="off" style="flex:1;padding:10px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:14px;background:var(--bg-card);color:var(--text-primary);font-family:monospace;">
          <button onclick="saveAccessCode()" style="padding:10px 20px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">保存</button>
        </div>
        <div id="accessCodeHint" style="margin-top:10px;font-size:12px;color:var(--text-muted);"></div>
      </div>
      <div class="dash-section" style="max-width:620px;margin-top:18px;">
        <h3>管理员密码</h3>
        <p style="color:var(--text-muted);font-size:12px;margin:0 0 14px;line-height:1.7;">
          当前登录账号:<span id="adminAccount" style="font-family:monospace;">-</span>。修改后立即生效,其他已登录的浏览器会被强制退出。
        </p>
        <div style="display:flex;flex-direction:column;gap:8px;">
          <input id="oldPwdInput" type="password" placeholder="当前密码" autocomplete="current-password" style="padding:10px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:14px;background:var(--bg-card);color:var(--text-primary);">
          <input id="newPwdInput" type="password" placeholder="新密码(至少 8 位)" autocomplete="new-password" style="padding:10px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:14px;background:var(--bg-card);color:var(--text-primary);">
          <input id="newPwd2Input" type="password" placeholder="再次输入新密码" autocomplete="new-password" style="padding:10px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:14px;background:var(--bg-card);color:var(--text-primary);">
          <div>
            <button onclick="savePassword()" style="padding:10px 20px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">修改密码</button>
          </div>
        </div>
        <div id="pwdHint" style="margin-top:10px;font-size:12px;color:var(--text-muted);"></div>
      </div>
    </div>
    <!-- Reports Panel -->
    <div id="reportsPanel" style="display:none;flex:1;overflow-y:auto;padding:24px;">
      <h3 style="font-size:18px;margin:0 0 16px;">⚑ 问题上报管理</h3>
      <div style="margin-bottom:12px;display:flex;gap:8px;align-items:center;flex-wrap:wrap">
        <button class="report-filter active" data-status="" onclick="filterReports(this,'')" style="padding:6px 14px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-card);font-size:12px;cursor:pointer">全部</button>
        <button class="report-filter" data-status="pending" onclick="filterReports(this,'pending')" style="padding:6px 14px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-card);font-size:12px;cursor:pointer">待处理</button>
        <button class="report-filter" data-status="resolved" onclick="filterReports(this,'resolved')" style="padding:6px 14px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-card);font-size:12px;cursor:pointer">已解决</button>
        <button class="report-filter" data-status="ignored" onclick="filterReports(this,'ignored')" style="padding:6px 14px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-card);font-size:12px;cursor:pointer">已忽略</button>
      </div>
      <div id="reportsList"></div>
    </div>
    <!-- SN/OS Mapping Panel -->
    <div id="snmapPanel" style="display:none;flex:1;overflow-y:auto;padding:24px;">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <h3 style="font-size:18px;margin:0;">📋 映射管理</h3>
        <div style="display:flex;gap:10px;align-items:center">
          <label id="mapDisplayModeLabel" style="font-size:12px;color:var(--text-muted);cursor:pointer;display:flex;align-items:center;gap:6px;user-select:none">
            <input type="checkbox" id="mapDisplayModeToggle" onchange="toggleMapDisplayMode()" style="accent-color:#3b82f6">
            <span>有映射时隐藏原始中性 OS 文件</span>
          </label>
        </div>
      </div>

      <!-- ═══ OS 映射 ═══ -->
      <div style="background:var(--bg-card);border:1px solid var(--border-light);border-radius:12px;padding:20px;margin-bottom:24px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
          <h4 style="margin:0;font-size:15px;font-weight:600">🔄 OS 名称映射</h4>
          <button onclick="showOsMapForm()" style="padding:6px 14px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:12px;">+ 新建</button>
        </div>
        <p style="font-size:12px;color:var(--text-muted);margin:0 0 12px">将 MES 返回的 OS 版本字符串映射到文件名,适用于多个 SN 共用同一 OS 的场景。</p>
        <div id="osMapForm" style="display:none;background:var(--bg-subtle);border:1px solid var(--border-light);border-radius:10px;padding:16px;margin-bottom:16px;">
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;">
            <div>
              <label style="display:block;font-size:12px;font-weight:500;color:var(--text-secondary);margin-bottom:4px">OS 版本</label>
              <input id="mapOsVersion" placeholder="如 I17J_020103111020113012000000_20250318V1" style="width:100%;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;background:var(--bg-card);color:var(--text-primary);box-sizing:border-box;">
            </div>
            <div>
              <label style="display:block;font-size:12px;font-weight:500;color:var(--text-secondary);margin-bottom:4px">备注</label>
              <input id="mapOsNote" placeholder="可选" style="width:100%;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;background:var(--bg-card);color:var(--text-primary);box-sizing:border-box;">
            </div>
          </div>
          <div style="margin-bottom:12px">
            <label style="display:block;font-size:12px;font-weight:500;color:var(--text-secondary);margin-bottom:4px">文件名(每行一个)</label>
            <textarea id="mapOsFiles" rows="3" placeholder="SCD_20240604_23H2_22631.3593_UL17_US_Win11_X64_Home_NewScripts&#10;RCD_20250318_I17JV2_V10_X64_NewScripts_EC25R06_EC200A_Meig5G_MeigASR_V17" style="width:100%;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;font-family:monospace;background:var(--bg-card);color:var(--text-primary);box-sizing:border-box;resize:vertical"></textarea>
          </div>
          <div style="display:flex;gap:8px;">
            <button onclick="saveOsMap()" style="padding:8px 20px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">保存</button>
            <button onclick="hideOsMapForm()" style="padding:8px 20px;background:var(--btn-cancel-bg);border:1px solid var(--btn-cancel-border);color:var(--btn-cancel-text);border-radius:8px;cursor:pointer;font-size:13px;">取消</button>
          </div>
        </div>
        <div id="osMapList"><div style="text-align:center;padding:20px;color:var(--text-muted);font-size:13px">加载中...</div></div>
      </div>

      <!-- ═══ SN 映射 ═══ -->
      <div style="background:var(--bg-card);border:1px solid var(--border-light);border-radius:12px;padding:20px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
          <h4 style="margin:0;font-size:15px;font-weight:600">🔢 SN 映射</h4>
          <button onclick="showSnMapForm()" style="padding:6px 14px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:12px;">+ 新建</button>
        </div>
        <p style="font-size:12px;color:var(--text-muted);margin:0 0 12px">将指定 SN 映射到文件名,优先级高于 OS 映射。</p>
        <div id="snMapForm" style="display:none;background:var(--bg-subtle);border:1px solid var(--border-light);border-radius:10px;padding:16px;margin-bottom:16px;">
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;">
            <div>
              <label style="display:block;font-size:12px;font-weight:500;color:var(--text-secondary);margin-bottom:4px">SN</label>
              <input id="mapSn" placeholder="输入 SN 编号" style="width:100%;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;background:var(--bg-card);color:var(--text-primary);box-sizing:border-box;">
            </div>
            <div>
              <label style="display:block;font-size:12px;font-weight:500;color:var(--text-secondary);margin-bottom:4px">备注</label>
              <input id="mapNote" placeholder="可选" style="width:100%;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;background:var(--bg-card);color:var(--text-primary);box-sizing:border-box;">
            </div>
          </div>
          <div style="margin-bottom:12px">
            <label style="display:block;font-size:12px;font-weight:500;color:var(--text-secondary);margin-bottom:4px">文件名(每行一个)</label>
            <textarea id="mapFiles" rows="3" placeholder="SCD_20240604_23H2_22631.3593_UL17_US_Win11_X64_Home_NewScripts&#10;RCD_20250318_I17JV2_V10_X64_NewScripts_EC25R06_EC200A_Meig5G_MeigASR_V17" style="width:100%;padding:9px 12px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;font-family:monospace;background:var(--bg-card);color:var(--text-primary);box-sizing:border-box;resize:vertical"></textarea>
          </div>
          <div style="display:flex;gap:8px;">
            <button onclick="saveSnMap()" style="padding:8px 20px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">保存</button>
            <button onclick="hideSnMapForm()" style="padding:8px 20px;background:var(--btn-cancel-bg);border:1px solid var(--btn-cancel-border);color:var(--btn-cancel-text);border-radius:8px;cursor:pointer;font-size:13px;">取消</button>
          </div>
        </div>
        <div id="snMapList"><div style="text-align:center;padding:20px;color:var(--text-muted);font-size:13px">加载中...</div></div>
      </div>
    </div>
  </div>
</div>


<script>
let token = localStorage.getItem('drivers_token') || '';
let devices = [];
let selectedId = null;
const TYPE_NAMES = { handheld:'手持机', tablet:'平板', notebook:'笔记本', industrial:'工控', vehicle:'车载' };
const TYPE_ICONS = { handheld:'📱', tablet:'📟', notebook:'💻', industrial:'⚙️', vehicle:'🚗' };
const TYPE_COLORS = { handheld:'#3b82f6', tablet:'#8b5cf6', notebook:'#10b981', industrial:'#f59e0b', vehicle:'#ef4444' };
const OS_NAMES = { android:'Android', windows:'Windows', linux:'Linux' };
const FILE_TYPES = { firmware:'固件', driver:'驱动', tool:'工具', document:'文档' };

// ── Theme Toggle ──
function toggleTheme() {
  const html = document.documentElement;
  const isWarm = html.getAttribute('data-theme') === 'warm';
  html.setAttribute('data-theme', isWarm ? 'cool' : 'warm');
  document.querySelectorAll('.theme-toggle').forEach(btn => {
    btn.textContent = isWarm ? '❄️' : '☀️';
  });
  localStorage.setItem('drivers_theme', html.getAttribute('data-theme'));
}

(function() {
  const saved = localStorage.getItem('drivers_theme');
  if (saved) {
    document.documentElement.setAttribute('data-theme', saved);
    document.querySelectorAll('.theme-toggle').forEach(btn => {
      btn.textContent = saved === 'warm' ? '☀️' : '❄️';
    });
  }
})();

// ── Login ──
async function login() {
  const err = document.getElementById('loginError');
  const u = document.getElementById('loginUser');
  const p = document.getElementById('loginPass');
  const k = document.getElementById('loginKey');
  if (!u || !p) { err.textContent = '页面异常,请刷新重试'; return; }
  try {
    const r = await fetch('/api/drivers/admin/login', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body:JSON.stringify({username: u.value, password: p.value, admin_key: k ? k.value : ''})
    });
    const data = await r.json();
    if (!r.ok) { err.textContent = data.detail||'登录失败'; return; }
    token = data.token;
    if (k) k.value = '';
    err.textContent = '';
    localStorage.setItem('drivers_token', token);
    showAdmin();
  } catch(e) { err.textContent = '服务器连接失败'; }
}

function logout(message) {
  token = '';
  localStorage.removeItem('drivers_token');
  document.getElementById('adminScreen').style.display = 'none';
  document.getElementById('loginScreen').style.display = 'flex';
  document.querySelector('.theme-toggle-wrap').style.display = '';
  document.getElementById('loginUser').value = '';
  document.getElementById('loginPass').value = '';
  const lk = document.getElementById('loginKey');
  if (lk) lk.value = '';
  const err = document.getElementById('loginError');
  if (err) err.textContent = message || '';
}

// ── Show admin ──
function showAdmin() {
  document.getElementById('loginScreen').style.display = 'none';
  document.getElementById('adminScreen').style.display = 'block';
  document.querySelector('.theme-toggle-wrap').style.display = 'none';
  document.getElementById('userDisplay').textContent = '管理员';
  const active = document.querySelector('.admin-tab.active') || document.querySelector('.admin-tab');
  if (active) switchTab(active.dataset.tab);
}

// Auto-login: 先确认令牌还有效,避免拿过期令牌直接进后台然后满屏报错
if (token) {
  api('GET', '/api/drivers/admin/account')
    .then(() => showAdmin())
    .catch(e => { if (!e.auth) showAdmin(); });
}

// ── API helper ──
async function api(method, path, body) {
  const opts = { method, headers:{'Authorization':`Bearer ${token}`} };
  if (body) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
  const r = await fetch(path, opts);
  const raw = await r.text();
  let data = null;
  try { data = raw ? JSON.parse(raw) : null; } catch (e) { data = null; }
  if (r.status === 401) {
    // 令牌存在服务端内存里,服务重启或入口密钥变更后全部失效,这里必须引导重新登录
    logout('登录已失效,请重新登录');
    const err = new Error('登录已失效');
    err.auth = true;
    throw err;
  }
  if (!r.ok) throw new Error((data && data.detail) || raw || ('请求失败 (HTTP ' + r.status + ')'));
  return data;
}

// ── Load devices ──
async function loadDevices() {
  try {
    const data = await api('GET', '/api/drivers/admin/devices');
    if (!data) return;
    devices = data.devices || [];
    renderSidebar();
    if (selectedId) selectDevice(selectedId);
  } catch(e) { alert(e.message); }
}

function renderSidebar() {
  const list = document.getElementById('deviceList');
  if (!list) return;
  list.innerHTML = devices.map(d => `
    <div class="device-item ${d.id===selectedId?'active':''}" onclick="selectDevice(${d.id})">
      <span>${TYPE_ICONS[d.device_type]||'📦'}</span>
      <div>
        <div class="dname">${d.name}</div>
        <div class="dtype">${TYPE_NAMES[d.device_type]||d.device_type}</div>
      </div>
      <button class="del-btn" onclick="event.stopPropagation();deleteDevice(${d.id})">✕</button>
    </div>
  `).join('');
  if (devices.length === 0) {
    list.innerHTML = '<div style="padding:20px;color:#bbb;text-align:center;font-size:13px;">暂无设备,点击 + 添加</div>';
  }
}
let _reportFilterStatus = '';

function filterReports(el, status) {
  _reportFilterStatus = status;
  document.querySelectorAll('.report-filter').forEach(b => b.classList.toggle('active', b.dataset.status === status));
  loadReports();
}

async function loadReports() {
  const el = document.getElementById('reportsList');
  el.innerHTML = '<div style="color:var(--text-muted);font-size:13px;padding:12px">加载中...</div>';
  try {
    const params = _reportFilterStatus ? `?status=${_reportFilterStatus}` : '';
    const data = await api('GET', `/api/drivers/reports${params}`);
    const reports = data.reports || [];
    if (reports.length === 0) {
      el.innerHTML = '<div style="color:var(--text-muted);font-size:13px;padding:12px">暂无上报记录</div>';
      return;
    }
    const TYPE_LABELS = {
      no_match: '未找到匹配文件',
      parse_error: '文件名截取错误',
      wrong_link: '链接有误',
      wrong_file: '文件不适配SN',
      missing_mapping: '缺少 OS 映射',
      file_not_on_mega: '文件未上传 MEGA',
      suggestion: '改进建议',
      other: '其他',
    };
    const STATUS_BADGE = {
      pending: '<span style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;background:#fee2e2;color:#dc2626">待处理</span>',
      resolved: '<span style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;background:#dcfce7;color:#16a34a">已解决</span>',
      ignored: '<span style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;background:#f1f5f9;color:#94a3b8">已忽略</span>',
    };
    el.innerHTML = reports.map(r => `
      <div style="padding:14px 16px;margin-bottom:8px;border:1px solid var(--border-light);border-radius:8px;background:var(--bg-card)">
        <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:8px">
          <div>
            <strong style="font-size:14px">#${r.id}</strong>
            <span style="margin-left:8px;font-size:12px;font-weight:500;color:var(--text-secondary)">${TYPE_LABELS[r.problem_type]||r.problem_type}</span>
            ${STATUS_BADGE[r.status]||''}
          </div>
          <div style="font-size:11px;color:var(--text-muted)">${r.created_at||''}</div>
        </div>
        <div style="font-size:12px;color:var(--text-secondary);margin-bottom:4px">
          <strong>SN:</strong> ${esc(r.sn)}
          ${r.os_type ? `| <strong>系统:</strong> ${esc(r.os_type)}` : ''}
          ${r.field_name ? `| <strong>字段:</strong> ${esc(r.field_name)}` : ''}
        </div>
        ${r.os_version ? `<div style="font-size:11px;color:var(--text-muted);margin-bottom:2px;word-break:break-all"><strong>${r.field_name ? '字段内容 / 文件名' : 'OS版本'}:</strong> ${esc(r.os_version)}</div>` : ''}
        ${r.matched_filenames ? `<div style="font-size:11px;color:var(--text-muted);margin-bottom:2px;word-break:break-all"><strong>匹配文件:</strong> ${esc(r.matched_filenames)}</div>` : ''}
        ${r.description ? `<div style="font-size:11px;color:var(--text-muted);margin-bottom:2px"><strong>说明:</strong> ${esc(r.description)}</div>` : ''}
        ${r.resolution_note ? `<div style="font-size:11px;color:var(--text-muted);margin-top:4px;padding:4px 8px;background:var(--bg-subtle);border-radius:4px"><strong>处理备注:</strong> ${esc(r.resolution_note)}</div>` : ''}
        ${r.status === 'pending' ? `
        <div style="margin-top:8px;display:flex;gap:6px">
          <input id="resolveNote_${r.id}" placeholder="处理备注(可选)" style="flex:1;padding:6px 10px;border:1px solid var(--border-light);border-radius:6px;font-size:12px">
          <button onclick="resolveReport(${r.id},'resolved')" style="padding:6px 14px;border:none;border-radius:6px;background:#16a34a;color:#fff;font-size:12px;cursor:pointer">解决</button>
          <button onclick="resolveReport(${r.id},'ignored')" style="padding:6px 14px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-card);font-size:12px;cursor:pointer">忽略</button>
          <button onclick="deleteReport(${r.id})" style="padding:6px 14px;border:1px solid #fecaca;border-radius:6px;background:#fef2f2;color:#dc2626;font-size:12px;cursor:pointer">删除</button>
        </div>` : `
        <div style="margin-top:8px;display:flex;gap:6px">
          <button onclick="deleteReport(${r.id})" style="padding:6px 14px;border:1px solid #fecaca;border-radius:6px;background:#fef2f2;color:#dc2626;font-size:12px;cursor:pointer">删除</button>
        </div>`}
      </div>
    `).join('');
  } catch (e) {
    el.innerHTML = `<div style="color:#dc2626;font-size:13px;padding:12px">加载失败: ${e.message}</div>`;
  }
}

async function resolveReport(id, status) {
  const note = document.getElementById(`resolveNote_${id}`)?.value?.trim() || '';
  try {
    await api('PATCH', `/api/drivers/reports/${id}`, { status, note });
    loadReports();
  } catch (e) {
    alert('更新失败: ' + e.message);
  }
}

async function deleteReport(id) {
  if (!confirm('确定删除该上报记录?')) return;
  try {
    await api('DELETE', `/api/drivers/reports/${id}`);
    loadReports();
  } catch (e) {
    alert('删除失败: ' + e.message);
  }
}

// ── OS / SN File Maps ──
let _osMapsData = [];
let _snMapsData = [];

async function loadAllMaps() {
  await Promise.all([loadOsMaps(), loadSnMaps(), loadSettings()]);
}

async function loadSettings() {
  try {
    const data = await api('GET', '/api/drivers/settings');
    if (!data) return;
    const cb = document.getElementById('mapDisplayModeToggle');
    cb.checked = data.map_display_mode === 'mapped_only';
  } catch (e) { /* ignore */ }
}

async function toggleMapDisplayMode() {
  const cb = document.getElementById('mapDisplayModeToggle');
  try {
    await api('PUT', '/api/drivers/settings', { map_display_mode: cb.checked ? 'mapped_only' : 'all' });
  } catch (e) {
    cb.checked = !cb.checked;
    alert('设置失败: ' + e.message);
  }
}

async function loadOsMaps() {
  try {
    const data = await api('GET', '/api/drivers/os-file-maps');
    if (!data) return;
    _osMapsData = data.maps || [];
    const maps = _osMapsData;
    const el = document.getElementById('osMapList');
    if (!maps.length) {
      el.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-muted);font-size:13px">暂无 OS 映射</div>';
      return;
    }
    el.innerHTML = `<table style="width:100%;border-collapse:collapse;font-size:13px">
      <thead><tr style="background:var(--bg-subtle);text-align:left">
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">OS 版本</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">映射文件</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">备注</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">更新时间</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">操作</th>
      </tr></thead>
      <tbody>${maps.map(m => {
        const files = Array.isArray(m.files) ? m.files : [];
        return `<tr style="border-bottom:1px solid var(--border-light)">
          <td style="padding:8px 10px;font-family:monospace;font-size:11px;font-weight:600;max-width:280px;word-break:break-all">${esc(m.os_version)}</td>
          <td style="padding:8px 10px"><div style="max-height:60px;overflow-y:auto;font-family:monospace;font-size:11px;line-height:1.5">${files.map(f => esc(f)).join('<br>')}</div></td>
          <td style="padding:8px 10px;color:var(--text-muted);font-size:12px;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(m.note || '—')}</td>
          <td style="padding:8px 10px;color:var(--text-muted);font-size:11px">${esc(m.updated_at || '').replace('T', ' ').slice(0, 19)}</td>
          <td style="padding:8px 10px;display:flex;gap:4px">
            <button onclick="editOsMap(${m.id})" style="padding:4px 10px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-card);font-size:11px;cursor:pointer">编辑</button>
            <button onclick="deleteOsMap(${m.id})" style="padding:4px 10px;border:1px solid #fecaca;border-radius:6px;background:#fef2f2;color:#dc2626;font-size:11px;cursor:pointer">删除</button>
          </td>
        </tr>`;
      }).join('')}</tbody>
    </table>`;
  } catch (e) {
    document.getElementById('osMapList').innerHTML = `<div style="color:#dc2626;font-size:13px">加载失败: ${esc(e.message)}</div>`;
  }
}

let _osEditId = null;

function showOsMapForm() {
  _osEditId = null;
  document.getElementById('mapOsVersion').value = '';
  document.getElementById('mapOsNote').value = '';
  document.getElementById('mapOsFiles').value = '';
  document.getElementById('osMapForm').style.display = 'block';
  document.getElementById('osMapForm').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function editOsMap(id) {
  const m = _osMapsData.find(x => x.id === id);
  if (!m) return;
  _osEditId = id;
  document.getElementById('mapOsVersion').value = m.os_version || '';
  document.getElementById('mapOsNote').value = m.note || '';
  const files = Array.isArray(m.files) ? m.files : [];
  document.getElementById('mapOsFiles').value = files.join('\n');
  document.getElementById('osMapForm').style.display = 'block';
  document.getElementById('osMapForm').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function hideOsMapForm() {
  document.getElementById('osMapForm').style.display = 'none';
  _osEditId = null;
}

async function saveOsMap() {
  const osVersion = document.getElementById('mapOsVersion').value.trim();
  const note = document.getElementById('mapOsNote').value.trim();
  const filesText = document.getElementById('mapOsFiles').value.trim();
  if (!osVersion) { alert('请输入 OS 版本'); return; }
  const files = filesText.split('\n').map(f => f.trim()).filter(f => f.length > 0);
  if (!files.length) { alert('请输入至少一个文件名'); return; }
  try {
    await api('POST', '/api/drivers/os-file-maps', { os_version: osVersion, files, note });
    hideOsMapForm();
    loadOsMaps();
  } catch (e) {
    alert('保存失败: ' + e.message);
  }
}

async function deleteOsMap(id) {
  if (!confirm('确定删除该 OS 映射?')) return;
  try {
    await api('DELETE', `/api/drivers/os-file-maps/${id}`);
    loadOsMaps();
  } catch (e) {
    alert('删除失败: ' + e.message);
  }
}

async function loadSnMaps() {
  try {
    const data = await api('GET', '/api/drivers/sn-file-maps');
    if (!data) return;
    _snMapsData = data.maps || [];
    const maps = _snMapsData;
    const el = document.getElementById('snMapList');
    if (!maps.length) {
      el.innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-muted);font-size:13px">暂无 SN 映射</div>';
      return;
    }
    el.innerHTML = `<table style="width:100%;border-collapse:collapse;font-size:13px">
      <thead><tr style="background:var(--bg-subtle);text-align:left">
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">SN</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">映射文件</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">备注</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">更新时间</th>
        <th style="padding:8px 10px;border-bottom:1px solid var(--border-light)">操作</th>
      </tr></thead>
      <tbody>${maps.map(m => {
        const files = Array.isArray(m.files) ? m.files : [];
        return `<tr style="border-bottom:1px solid var(--border-light)">
          <td style="padding:8px 10px;font-family:monospace;font-weight:600">${esc(m.sn)}</td>
          <td style="padding:8px 10px"><div style="max-height:60px;overflow-y:auto;font-family:monospace;font-size:11px;line-height:1.5">${files.map(f => esc(f)).join('<br>')}</div></td>
          <td style="padding:8px 10px;color:var(--text-muted);font-size:12px;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(m.note || '—')}</td>
          <td style="padding:8px 10px;color:var(--text-muted);font-size:11px">${esc(m.updated_at || '').replace('T', ' ').slice(0, 19)}</td>
          <td style="padding:8px 10px;display:flex;gap:4px">
            <button onclick="editSnMap(${m.id})" style="padding:4px 10px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg-card);font-size:11px;cursor:pointer">编辑</button>
            <button onclick="deleteSnMap(${m.id})" style="padding:4px 10px;border:1px solid #fecaca;border-radius:6px;background:#fef2f2;color:#dc2626;font-size:11px;cursor:pointer">删除</button>
          </td>
        </tr>`;
      }).join('')}</tbody>
    </table>`;
  } catch (e) {
    document.getElementById('snMapList').innerHTML = `<div style="color:#dc2626;font-size:13px">加载失败: ${esc(e.message)}</div>`;
  }
}

let _snEditId = null;

function showSnMapForm() {
  _snEditId = null;
  document.getElementById('mapSn').value = '';
  document.getElementById('mapNote').value = '';
  document.getElementById('mapFiles').value = '';
  document.getElementById('snMapForm').style.display = 'block';
  document.getElementById('snMapForm').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function editSnMap(id) {
  const m = _snMapsData.find(x => x.id === id);
  if (!m) return;
  _snEditId = id;
  document.getElementById('mapSn').value = m.sn || '';
  document.getElementById('mapNote').value = m.note || '';
  const files = Array.isArray(m.files) ? m.files : [];
  document.getElementById('mapFiles').value = files.join('\n');
  document.getElementById('snMapForm').style.display = 'block';
  document.getElementById('snMapForm').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function hideSnMapForm() {
  document.getElementById('snMapForm').style.display = 'none';
  _snEditId = null;
}

async function saveSnMap() {
  const sn = document.getElementById('mapSn').value.trim();
  const note = document.getElementById('mapNote').value.trim();
  const filesText = document.getElementById('mapFiles').value.trim();
  if (!sn) { alert('请输入 SN'); return; }
  const files = filesText.split('\n').map(f => f.trim()).filter(f => f.length > 0);
  if (!files.length) { alert('请输入至少一个文件名'); return; }
  try {
    await api('POST', '/api/drivers/sn-file-maps', { sn, files, note });
    hideSnMapForm();
    loadSnMaps();
  } catch (e) {
    alert('保存失败: ' + e.message);
  }
}

async function deleteSnMap(id) {
  if (!confirm('确定删除该 SN 映射?')) return;
  try {
    await api('DELETE', `/api/drivers/sn-file-maps/${id}`);
    loadSnMaps();
  } catch (e) {
    alert('删除失败: ' + e.message);
  }
}

async function queryMES() {
  const sn = document.getElementById('mesSnInput').value.trim();
  if (!sn) { alert('请输入 SN'); return; }
  const res = document.getElementById('mesResult');
  res.textContent = '查询中...';
  try {
    const data = await api('POST', '/api/drivers/admin/mes-debug', { sn });
    res.textContent = JSON.stringify(data, null, 2);
  } catch (e) {
    res.textContent = '错误: ' + e.message;
  }
}

// ── MES Query Monitor ──
async function loadMesMonitor() {
  try {
    const d = await api('GET', '/api/drivers/admin/mes-monitoring');
    document.getElementById('mesStatTotal').textContent = d.total_queries ?? '-';
    document.getElementById('mesStatToday').textContent = d.today_queries ?? '-';
    document.getElementById('mesStatCache').textContent = d.cache_hits ?? '-';
    document.getElementById('mesStatAvg').textContent = d.avg_duration_ms ?? '-';
    document.getElementById('mesStatError').textContent = d.error_queries ?? '-';
    document.getElementById('mesStatUnique').textContent = d.unique_sn ?? '-';
    document.getElementById('mesStatPending').textContent = d.pending_reports ?? '-';
    document.getElementById('mesStatMaps').textContent = (d.os_map_count ?? 0) + ' / ' + (d.sn_map_count ?? 0);

    const daily = document.getElementById('mesDaily');
    if (d.daily_queries && d.daily_queries.length) {
      daily.innerHTML = d.daily_queries.map(r =>
        '<div class="dash-row"><span class="name">' + esc(r.date) + '</span><span class="count">' + r.cnt + ' 次</span></div>'
      ).join('');
    } else { daily.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>'; }

    const top = document.getElementById('mesTopSn');
    if (d.top_sn && d.top_sn.length) {
      top.innerHTML = d.top_sn.map((r, i) =>
        '<div class="dash-row"><span class="name">' + (i + 1) + '. ' + esc(r.sn) + '</span><span class="count">' + r.cnt + ' 次</span></div>'
      ).join('');
    } else { top.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>'; }

    const rec = document.getElementById('mesRecent');
    if (d.recent_queries && d.recent_queries.length) {
      rec.innerHTML = d.recent_queries.map(r => {
        const flag = r.status === 'ok' ? 'OK' : 'ERR';
        const cacheTag = r.cached ? ' · cache' : '';
        return '<div class="dash-row"><span class="name">' + esc(r.sn) + '</span><span class="count" style="font-size:11px;font-weight:400;color:var(--text-muted)">' + flag + cacheTag + ' · ' + r.duration_ms + 'ms · ' + (r.created_at || '') + '</span></div>';
      }).join('');
    } else { rec.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>'; }
  } catch (e) {
    if (e.auth) return;
    const grid = document.getElementById('mesDashGrid');
    if (grid) grid.innerHTML = '<div style="color:#dc2626;text-align:center;padding:40px">MES 监控数据加载失败: ' + esc(e.message) + '</div>';
  }
}

// ── Tab switching ──
function switchTab(name) {
  document.querySelectorAll('.admin-tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
  document.getElementById('mesPanel').style.display = name==='mes'?'block':'none';
  document.getElementById('reportsPanel').style.display = name==='reports'?'block':'none';
  document.getElementById('snmapPanel').style.display = name==='snmap'?'block':'none';
  document.getElementById('mesMonPanel').style.display = name==='mesmon'?'block':'none';
  document.getElementById('sysPanel').style.display = name==='sysset'?'block':'none';
  document.getElementById('profilesPanel').style.display = name==='profiles'?'block':'none';
  if (name==='reports') loadReports();
  if (name==='snmap') loadAllMaps();
  if (name==='mesmon') loadMesMonitor();
  if (name==='sysset') { loadAccessCode(); loadAccount(); }
  if (name==='profiles') loadProfiles();
}

// ── Access profiles ──
let pfCatalog = null, pfList = [], pfEditingId = null;

function pfEsc(s) {
  return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}

async function ensurePfCatalog() {
  if (pfCatalog) return pfCatalog;
  const d = await api('GET', '/api/drivers/admin/field-catalog');
  pfCatalog = (d && d.groups) || [];
  return pfCatalog;
}

async function loadProfiles() {
  const box = document.getElementById('profileList');
  try {
    const d = await api('GET', '/api/drivers/admin/profiles');
    if (!d) return;
    pfList = d.profiles || [];
    if (!pfList.length) {
      box.innerHTML = '<div style="padding:32px;text-align:center;color:var(--text-muted);font-size:13px;background:var(--bg-card);border:1px solid var(--border-light);border-radius:10px;">还没有访问码,点击右上角新建。</div>';
      return;
    }
    box.innerHTML = pfList.map(p => {
      const adminTag = p.is_admin ? '<span style="font-size:11px;padding:2px 8px;border-radius:99px;background:#e0f2fe;color:#0369a1;">管理员</span>' : '';
      const offTag = p.enabled ? '' : '<span style="font-size:11px;padding:2px 8px;border-radius:99px;background:#fee2e2;color:#b91c1c;">已停用</span>';
      const count = p.is_admin ? '全部字段' : (p.field_count + ' 个字段');
      return '<div style="display:flex;align-items:center;gap:14px;padding:14px 16px;background:var(--bg-card);border:1px solid var(--border-light);border-radius:10px;margin-bottom:10px;">'
        + '<div style="flex:1;min-width:0;">'
        +   '<div style="display:flex;align-items:center;gap:8px;">'
        +     '<span style="font-family:monospace;font-size:14px;font-weight:600;">' + pfEsc(p.code) + '</span>' + adminTag + offTag
        +   '</div>'
        +   '<div style="font-size:12px;color:var(--text-muted);margin-top:4px;">' + pfEsc(p.name || '-') + ' · ' + count + '</div>'
        + '</div>'
        + '<button onclick="openProfileEditor(' + p.id + ')" style="padding:7px 14px;font-size:12px;border:1px solid var(--border-light);border-radius:7px;background:var(--bg-subtle);cursor:pointer;color:var(--text-secondary);">编辑</button>'
        + '<button onclick="deleteProfile(' + p.id + ')" style="padding:7px 14px;font-size:12px;border:1px solid #fecaca;border-radius:7px;background:#fef2f2;cursor:pointer;color:#b91c1c;">删除</button>'
        + '</div>';
    }).join('');
  } catch (e) {
    box.innerHTML = '<div style="padding:16px;color:#b91c1c;font-size:13px;">读取失败: ' + pfEsc(e.message) + '</div>';
  }
}

function renderPfFields() {
  const box = document.getElementById('pfFields');
  const sel = new Set(Array.from(document.querySelectorAll('.pf-field')).filter(c => c.checked).map(c => c.value));
  if (!box.dataset.built) sel.clear();
  box.innerHTML = (pfCatalog || []).map((g, gi) => {
    const items = (g.fields || []).map(f => {
      const checked = sel.has(f.key) ? ' checked' : '';
      const sens = f.sensitive ? '<span style="font-size:10px;padding:1px 6px;border-radius:99px;background:#fef3c7;color:#92400e;">敏感</span>' : '';
      return '<label style="display:flex;align-items:center;gap:6px;padding:3px 2px;font-size:12px;cursor:pointer;">'
        + '<input type="checkbox" class="pf-field" value="' + pfEsc(f.key) + '"' + checked + ' onchange="updatePfCount()" style="accent-color:#3b82f6;">'
        + '<span>' + pfEsc(f.zh || f.en || f.key) + '</span>'
        + '<span style="color:var(--text-muted);font-size:11px;">' + pfEsc(f.key) + '</span>' + sens
        + '</label>';
    }).join('');
    return '<div style="margin-bottom:12px;">'
      + '<div style="display:flex;align-items:center;gap:8px;margin-bottom:5px;">'
      +   '<span style="font-size:12px;font-weight:600;">' + pfEsc(g.group_zh || g.group) + '</span>'
      +   '<button type="button" onclick="pfGroup(' + gi + ',true)" style="padding:1px 8px;font-size:10px;border:1px solid var(--border-light);border-radius:5px;background:var(--bg-card);cursor:pointer;color:var(--text-muted);">全选</button>'
      +   '<button type="button" onclick="pfGroup(' + gi + ',false)" style="padding:1px 8px;font-size:10px;border:1px solid var(--border-light);border-radius:5px;background:var(--bg-card);cursor:pointer;color:var(--text-muted);">清空</button>'
      + '</div>'
      + '<div style="display:grid;grid-template-columns:1fr 1fr;gap:0 18px;">' + items + '</div>'
      + '</div>';
  }).join('');
  box.dataset.built = '1';
  updatePfCount();
}

function pfGroup(gi, on) {
  const g = (pfCatalog || [])[gi];
  if (!g) return;
  const keys = new Set((g.fields || []).map(f => f.key));
  document.querySelectorAll('.pf-field').forEach(c => { if (keys.has(c.value)) c.checked = on; });
  updatePfCount();
}

function pfSetAll(on) {
  document.querySelectorAll('.pf-field').forEach(c => { c.checked = on; });
  updatePfCount();
}

function updatePfCount() {
  const n = document.querySelectorAll('.pf-field:checked').length;
  const el = document.getElementById('pfCount');
  if (el) el.textContent = '(已选 ' + n + ' / ' + document.querySelectorAll('.pf-field').length + ')';
}

function onPfAdminChange() {
  const on = document.getElementById('pfAdmin').checked;
  document.getElementById('pfFieldWrap').style.display = on ? 'none' : '';
}

function openProfileEditor(id) {
  (async () => {
    try {
      await ensurePfCatalog();
    } catch (e) {
      alert(e.message);
      return;
    }
    pfEditingId = id || null;
    const p = id ? (pfList.find(x => x.id === id) || null) : null;
    document.getElementById('profileModalTitle').textContent = id ? '编辑访问码' : '新建访问码';
    document.getElementById('pfCode').value = p ? p.code : '';
    document.getElementById('pfName').value = p ? (p.name || '') : '';
    document.getElementById('pfAdmin').checked = p ? !!p.is_admin : false;
    document.getElementById('pfEnabled').checked = p ? !!p.enabled : true;
    const fields = document.getElementById('pfFields');
    delete fields.dataset.built;
    fields.innerHTML = '';
    renderPfFields();
    const want = new Set(p ? (p.visible_fields || []) : []);
    document.querySelectorAll('.pf-field').forEach(c => { c.checked = want.has(c.value); });
    updatePfCount();
    onPfAdminChange();
    const m = document.getElementById('profileModal');
    m.style.display = 'flex';
  })();
}

function closeProfileEditor() {
  document.getElementById('profileModal').style.display = 'none';
  pfEditingId = null;
}

async function saveProfile() {
  const code = document.getElementById('pfCode').value.trim();
  const name = document.getElementById('pfName').value.trim();
  const is_admin = document.getElementById('pfAdmin').checked;
  const enabled = document.getElementById('pfEnabled').checked;
  const visible_fields = Array.from(document.querySelectorAll('.pf-field')).filter(c => c.checked).map(c => c.value);
  if (!code) { alert('请填写访问码'); return; }
  if (!is_admin && !visible_fields.length) { alert('请至少勾选一个可见字段'); return; }
  const body = { code, name, is_admin, visible_fields, enabled };
  try {
    if (pfEditingId) await api('PUT', '/api/drivers/admin/profiles/' + pfEditingId, body);
    else await api('POST', '/api/drivers/admin/profiles', body);
    closeProfileEditor();
    await loadProfiles();
  } catch (e) {
    alert(e.message);
  }
}

async function deleteProfile(id) {
  const p = pfList.find(x => x.id === id);
  if (!p) return;
  if (!confirm('确定删除访问码「' + p.code + '」?使用该访问码的用户会立即失去访问权限。')) return;
  try {
    await api('DELETE', '/api/drivers/admin/profiles/' + id);
    await loadProfiles();
  } catch (e) {
    alert(e.message);
  }
}

// ── System settings: public access code ──
async function loadAccessCode() {
  try {
    const d = await api('GET', '/api/drivers/admin/access-code');
    if (!d) return;
    document.getElementById('accessCodeInput').value = d.code || '';
    document.getElementById('accessCodeHint').textContent = d.source === 'db'
      ? '当前访问码来自数据库,可随时在此修改。'
      : '当前为环境变量默认值(mes-2026 或 MES_ACCESS_CODE),保存后改为数据库存储。';
  } catch (e) {
    document.getElementById('accessCodeHint').textContent = '读取失败: ' + e.message;
  }
}

async function saveAccessCode() {
  const input = document.getElementById('accessCodeInput');
  const code = input.value.trim();
  if (code.length < 6) { alert('访问码至少 6 位'); return; }
  if (code.length > 64) { alert('访问码最多 64 位'); return; }
  if (/\s/.test(code)) { alert('访问码不能包含空格'); return; }
  if (!confirm('确认把访问码改为:' + code + ' ?\n修改后已登录的用户需要重新输入新访问码。')) return;
  try {
    await api('PUT', '/api/drivers/admin/access-code', { code });
    alert('已保存,立即生效');
    loadAccessCode();
  } catch (e) {
    alert('保存失败: ' + e.message);
  }
}

// ── System settings: admin password ──
async function loadAccount() {
  try {
    const d = await api('GET', '/api/drivers/admin/account');
    if (d) document.getElementById('adminAccount').textContent = d.username || '-';
  } catch (e) {
    document.getElementById('adminAccount').textContent = '-';
  }
}

async function savePassword() {
  const oldPwd = document.getElementById('oldPwdInput').value;
  const newPwd = document.getElementById('newPwdInput').value;
  const newPwd2 = document.getElementById('newPwd2Input').value;
  const hint = document.getElementById('pwdHint');
  if (!oldPwd) { hint.textContent = '请输入当前密码'; return; }
  if (newPwd.length < 8) { hint.textContent = '新密码至少 8 位'; return; }
  if (newPwd !== newPwd2) { hint.textContent = '两次输入的新密码不一致'; return; }
  if (newPwd === oldPwd) { hint.textContent = '新密码不能与当前密码相同'; return; }
  if (!confirm('确认修改管理员密码?其他已登录的浏览器会被强制退出。')) return;
  try {
    await api('PUT', '/api/drivers/admin/password', { old_password: oldPwd, new_password: newPwd });
    document.getElementById('oldPwdInput').value = '';
    document.getElementById('newPwdInput').value = '';
    document.getElementById('newPwd2Input').value = '';
    hint.style.color = 'var(--os-android)';
    hint.textContent = '密码已修改,下次请用新密码登录。';
  } catch (e) {
    hint.style.color = '';
    hint.textContent = '修改失败: ' + e.message;
  }
}

// ── Device search ──
function filterDevices() {
  const q = document.getElementById('searchInput').value.toLowerCase();
  document.querySelectorAll('.device-item').forEach(el => {
    el.style.display = el.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
}

// ── Announcements ──
function showAnnounceForm() {
  document.getElementById('announceId').value = '';
  document.getElementById('announceTitle').value = '';
  document.getElementById('announceContent').value = '';
  document.getElementById('announceKind').value = '公告';
  document.getElementById('announceActive').checked = true;
  document.getElementById('announceForm').style.display = 'block';
}
function hideAnnounceForm() {
  document.getElementById('announceForm').style.display = 'none';
}

async function loadAnnouncements() {
  try {
    const data = await api('GET', '/api/drivers/admin/announcements');
    const list = data.announcements || [];
    const el = document.getElementById('announceList');
    if (!list.length) { el.innerHTML = '<div class="announce-empty">暂无公告,点击右上角新建</div>'; return; }
    el.innerHTML = list.map(a => `
      <div class="announce-item">
        <div style="display:flex;justify-content:space-between;align-items:center">
          <span><span class="title">${esc(a.kind)}: ${esc(a.title)}</span>
          <span class="badge ${a.active?'on':'off'}">${a.active?'启用':'禁用'}</span></span>
          <span style="display:flex;gap:6px">
            <button onclick="editAnnouncement(${a.id})" style="background:none;border:1px solid var(--border-light);border-radius:6px;padding:4px 10px;cursor:pointer;font-size:12px;color:var(--text-secondary)">编辑</button>
            <button onclick="toggleAnnouncement(${a.id})" style="background:none;border:1px solid var(--border-light);border-radius:6px;padding:4px 10px;cursor:pointer;font-size:12px;color:var(--text-secondary)">${a.active?'禁用':'启用'}</button>
            <button onclick="deleteAnnouncement(${a.id})" style="background:none;border:1px solid #fca5a5;border-radius:6px;padding:4px 10px;cursor:pointer;font-size:12px;color:#dc2626">删除</button>
          </span>
        </div>
        <div class="meta">${a.created_at||''}</div>
        <div class="content">${esc(a.content)}</div>
      </div>
    `).join('');
  } catch(e) { document.getElementById('announceList').innerHTML = '<div class="announce-empty">加载失败: '+e.message+'</div>'; }
}

function editAnnouncement(id) {
  api('GET', '/api/drivers/admin/announcements').then(data => {
    const a = (data.announcements || []).find(i => i.id===id);
    if (!a) return;
    document.getElementById('announceId').value = a.id;
    document.getElementById('announceTitle').value = a.title;
    document.getElementById('announceContent').value = a.content;
    document.getElementById('announceKind').value = a.kind;
    document.getElementById('announceActive').checked = a.active;
    document.getElementById('announceForm').style.display = 'block';
  });
}

async function saveAnnouncement() {
  const id = document.getElementById('announceId').value;
  const title = document.getElementById('announceTitle').value.trim();
  const content = document.getElementById('announceContent').value.trim();
  if (!title || !content) { alert('请填写标题和内容'); return; }
  try {
    if (id) {
      await api('POST', '/api/drivers/admin/announcements', { id: Number(id), title, content, kind: document.getElementById('announceKind').value, active: document.getElementById('announceActive').checked });
    } else {
      await api('POST', '/api/drivers/admin/announcements', { title, content, kind: document.getElementById('announceKind').value, active: document.getElementById('announceActive').checked });
    }
    hideAnnounceForm();
    await loadAnnouncements();
  } catch(e) { alert(e.message); }
}

async function toggleAnnouncement(id) {
  try { await api('POST', `/api/drivers/admin/announcements/toggle/${id}`); await loadAnnouncements(); }
  catch(e) { alert(e.message); }
}
async function deleteAnnouncement(id) {
  if (!confirm('确定删除此公告?')) return;
  try { await api('DELETE', `/api/drivers/admin/announcements/${id}`); await loadAnnouncements(); }
  catch(e) { alert(e.message); }
}

// ── Monitoring dashboard ──
async function loadDashboard() {
  try {
    const d = await api('GET', '/api/drivers/admin/monitoring');
    document.getElementById('statTotalVisits').textContent = d.total_visits;
    document.getElementById('statTodayVisits').textContent = d.today_visits;
    document.getElementById('statTotalDownloads').textContent = d.total_downloads;
    document.getElementById('statTodayDownloads').textContent = d.today_downloads;

    const topDev = document.getElementById('dashTopDevices');
    if (d.top_devices && d.top_devices.length) {
      topDev.innerHTML = d.top_devices.map((r,i) =>
        `<div class="dash-row"><span class="name">${i+1}. ${esc(r.device_name||'未知')}</span><span class="count">${r.cnt}次</span></div>`
      ).join('');
    } else { topDev.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>'; }

    const rv = document.getElementById('dashRecentVisits');
    if (d.recent_visits && d.recent_visits.length) {
      rv.innerHTML = d.recent_visits.map(v =>
        `<div class="dash-row"><span class="name">${esc(v.device_name||v.path||'—')}</span><span class="count" style="font-size:11px;font-weight:400;color:var(--text-muted)">${v.created_at||''}</span></div>`
      ).join('');
    } else { rv.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>'; }

    const rd = document.getElementById('dashRecentDownloads');
    if (d.recent_downloads && d.recent_downloads.length) {
      rd.innerHTML = d.recent_downloads.map(dl =>
        `<div class="dash-row"><span class="name">${esc(dl.title||'—')} (${esc(dl.device_name||'')})</span><span class="count" style="font-size:11px;font-weight:400;color:var(--text-muted)">${dl.created_at||''}</span></div>`
      ).join('');
    } else { rd.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>'; }
  } catch(e) {
    document.getElementById('dashGrid').innerHTML = '<div style="color:#dc2626;text-align:center;padding:40px">监控数据加载失败: '+e.message+'</div>';
  }
}

// ── MEGA Cache Status ──
let _megaTimer = null;

function formatSize(bytes) {
  if (!bytes) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let i = 0;
  let size = bytes;
  while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
  return size.toFixed(i > 0 ? 1 : 0) + ' ' + units[i];
}
async function loadMegaCache() {
  try {
    const d = await api('GET', '/api/drivers/admin/mega-status');
    document.getElementById('megaTotal').textContent = d.total_on_mega.toLocaleString();
    document.getElementById('megaUnique').textContent = (d.unique_files||d.total_on_mega).toLocaleString();
    document.getElementById('megaExported').textContent = d.total.toLocaleString();
    document.getElementById('megaWithLinks').textContent = d.with_links.toLocaleString();
    document.getElementById('megaSize').textContent = formatSize(d.total_size);

    // Progress bar: tracks 链接就绪率 (with_links / unique_files)
    // File index sync happens instantly; links generate on-demand during SN queries.
    const target = d.unique_files || d.total_on_mega;
    const pct = target > 0 ? (d.with_links / target * 100) : 0;
    const fill = document.getElementById('megaProgressFill');
    fill.style.width = Math.min(pct, 100) + '%';
    fill.textContent = pct >= 8 ? pct.toFixed(1) + '%' : '';
    const allIndexed = d.total >= target;
    document.getElementById('megaProgressText').innerHTML =
      '已索引: ' + d.total.toLocaleString() + ' / ' + target.toLocaleString() +
      (allIndexed ? ' ✓' : '') +
      ' · 唯一文件: ' + target.toLocaleString() +
      (d.total_on_mega > target ? ' (含 ' + (d.total_on_mega - target).toLocaleString() + ' 重复)' : '') +
      ' · 已生成链接: ' + d.with_links.toLocaleString() +
      (d.last_update ? ' · 最后更新: ' + d.last_update : '') +
      ' <span style="color:var(--text-muted);font-size:12px">(链接在查询时按需生成)</span>';

    // Extensions
    const extEl = document.getElementById('megaExtensions');
    if (d.extensions && d.extensions.length) {
      extEl.innerHTML = d.extensions.map(e =>
        `<div class="dash-row"><span class="name">.${e.ext.replace('.','')}</span><span class="count">${e.cnt.toLocaleString()} 个</span></div>`
      ).join('');
    } else {
      extEl.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>';
    }

    // Recent imports
    const recEl = document.getElementById('megaRecent');
    if (d.recent && d.recent.length) {
      recEl.innerHTML = d.recent.map(r =>
        `<div class="dash-row"><span class="name" style="font-size:12px">${esc(r.file_name||'')}</span><span class="count" style="font-size:11px;font-weight:400;color:var(--text-muted)">${r.created_at||''}</span></div>`
      ).join('');
    } else {
      recEl.innerHTML = '<div class="dash-row" style="color:var(--text-muted)">暂无数据</div>';
    }

    // No auto-polling needed — index sync is instant, links generated on-demand
    if (_megaTimer) { clearTimeout(_megaTimer); _megaTimer = null; }
  } catch(e) {
    document.getElementById('megaDashGrid').innerHTML =
      '<div style="color:#dc2626;text-align:center;padding:40px">加载失败: '+e.message+'</div>';
    if (_megaTimer) { clearTimeout(_megaTimer); _megaTimer = null; }
  }
}

// ── Device Modal (Add / Edit) ──
function showDeviceModal(device) {
  const isEdit = !!device;
  const overlay = document.getElementById('modalOverlay');
  const content = document.getElementById('modalContent');
  content.innerHTML = `
    <h3>${isEdit ? '编辑设备' : '添加设备'}</h3>
    <label>设备名称</label>
    <input id="modalDeviceName" value="${esc(device?.name||'')}" placeholder="如 I10A Rugged Tablet">
    <label>设备类型</label>
    <select id="modalDeviceType">
      ${Object.entries(TYPE_NAMES).map(([k,v]) =>
        `<option value="${k}" ${device?.device_type===k?'selected':''}>${v}</option>`
      ).join('')}
    </select>
    <label>排序权重(越小越靠前)</label>
    <input id="modalDeviceSort" type="number" value="${device?.sort_order??0}" min="0">
    <label>描述(可选)</label>
    <textarea id="modalDeviceDesc" rows="2">${esc(device?.description||'')}</textarea>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="hideDeviceModal()">取消</button>
      <button class="btn-save" onclick="saveDevice(${isEdit ? device.id : ''})">保存</button>
    </div>
  `;
  overlay.classList.add('open');
}
function hideDeviceModal() {
  document.getElementById('modalOverlay').classList.remove('open');
}
async function saveDevice(id) {
  const name = document.getElementById('modalDeviceName').value.trim();
  const device_type = document.getElementById('modalDeviceType').value;
  const sort_order = parseInt(document.getElementById('modalDeviceSort').value) || 0;
  const description = document.getElementById('modalDeviceDesc').value.trim();
  if (!name) { alert('请输入设备名称'); return; }
  try {
    if (id) {
      await api('PUT', `/api/drivers/admin/devices/${id}`, { name, device_type, sort_order, description });
    } else {
      await api('POST', '/api/drivers/admin/devices', { name, device_type, sort_order, description });
    }
    hideDeviceModal();
    await loadDevices();
  } catch(e) { alert(e.message); }
}

// ── Select device ──
function selectDevice(id) {
  selectedId = id;
  renderSidebar();
  const detail = document.getElementById('deviceDetail');
  const hint = document.getElementById('emptyHint');
  if (!detail || !hint) return;
  const d = devices.find(x => x.id === id);
  if (!d) return;
  hint.style.display = 'none';
  detail.style.display = 'block';
  detail.innerHTML = `
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <div>
        <h2 style="font-size:20px;margin:0">${esc(d.name)}</h2>
        <span style="font-size:13px;color:var(--text-muted)">${TYPE_NAMES[d.device_type]||d.device_type} · 排序 ${d.sort_order}</span>
      </div>
      <div style="display:flex;gap:8px">
        <button onclick="showDeviceModal(devices.find(x=>x.id===${id}))" style="padding:8px 16px;background:var(--bg-subtle);border:1px solid var(--border-light);border-radius:8px;cursor:pointer;font-size:13px;color:var(--text-secondary)">编辑</button>
        <button onclick="deleteDevice(${id})" style="padding:8px 16px;background:#fef2f2;border:1px solid #fca5a5;border-radius:8px;cursor:pointer;font-size:13px;color:#dc2626">删除</button>
      </div>
    </div>
    <div style="color:var(--text-muted);font-size:13px;margin-bottom:16px">${esc(d.description||'无描述')}</div>
    <div id="osSection"></div>
  `;
  loadOSVersions(id);
}

async function loadOSVersions(deviceId) {
  const el = document.getElementById('osSection');
  try {
    const data = await api('GET', `/api/drivers/admin/os?device_id=${deviceId}`);
    const list = data.os_versions || [];
    let html = `
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
        <h3 style="font-size:15px;margin:0">系统版本</h3>
        <button onclick="showOSModal(${deviceId})" style="padding:6px 14px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:12px">+ 添加系统</button>
      </div>
    `;
    if (list.length === 0) {
      html += '<div style="padding:20px;text-align:center;color:var(--text-muted);font-size:13px;background:var(--bg-subtle);border-radius:8px">暂无系统版本</div>';
    } else {
      html += list.map(os => `
        <div class="os-card">
          <div class="os-card-header" onclick="toggleDlSection(${os.id})">
            <span class="os-dot ${os.os_type}"></span>
            <span class="ov">${OS_NAMES[os.os_type]||os.os_type}</span>
            <span style="color:var(--text-muted);font-size:12px;margin-left:4px">${esc(os.version_name)}</span>
            <div class="actions">
              <button onclick="event.stopPropagation();showOSModal(${deviceId},${os.id})">编辑</button>
              <button class="del" onclick="event.stopPropagation();deleteOS(${os.id})">删除</button>
            </div>
          </div>
          <div class="dl-section" id="dlSection${os.id}">
            <div id="dlList${os.id}"><div style="padding:10px;text-align:center;color:var(--text-muted);font-size:12px">加载中...</div></div>
            <button class="add-dl-btn" onclick="showDownloadModal(${os.id})">+ 添加下载链接</button>
          </div>
        </div>
      `).join('');
      // Load downloads for each OS version
      list.forEach(os => loadDownloads(os.id));
    }
    el.innerHTML = html;
  } catch(e) { el.innerHTML = '<div style="color:#dc2626">加载失败: '+e.message+'</div>'; }
}

function toggleDlSection(osId) {
  const el = document.getElementById('dlSection' + osId);
  if (el) el.classList.toggle('open');
}

async function loadDownloads(osVersionId) {
  const el = document.getElementById('dlList' + osVersionId);
  if (!el) return;
  try {
    const data = await api('GET', `/api/drivers/admin/downloads?os_version_id=${osVersionId}`);
    const list = data.downloads || [];
    if (list.length === 0) {
      el.innerHTML = '<div style="padding:10px;text-align:center;color:var(--text-muted);font-size:12px">暂无下载链接</div>';
      return;
    }
    el.innerHTML = list.map(dl => `
      <div class="dl-item">
        <div class="info">
          <div class="title">${FILE_TYPES[dl.file_type]||dl.file_type}: ${esc(dl.title)}</div>
          <div class="meta">${dl.file_size||''}</div>
          <div class="link-text">${esc(dl.mega_link||'')}</div>
        </div>
        <div class="actions">
          <button onclick="showDownloadModal(${dl.os_version_id},${dl.id})">编辑</button>
          <button class="del" onclick="deleteDownload(${dl.id})">删除</button>
        </div>
      </div>
    `).join('');
  } catch(e) {
    el.innerHTML = '<div style="padding:10px;text-align:center;color:#dc2626;font-size:12px">加载失败</div>';
  }
}

// ── Download Modal ──
function showDownloadModal(osVersionId, downloadId) {
  const isEdit = !!downloadId;
  const overlay = document.getElementById('modalOverlay');
  const content = document.getElementById('modalContent');
  let dl = null;
  if (isEdit) {
    api('GET', `/api/drivers/admin/downloads?os_version_id=${osVersionId}`).then(data => {
      dl = (data.downloads||[]).find(x => x.id === downloadId);
      renderDlForm();
    });
  } else {
    renderDlForm();
  }
  function renderDlForm() {
    content.innerHTML = `
      <h3>${isEdit ? '编辑下载链接' : '添加下载链接'}</h3>
      <label>文件类型</label>
      <select id="modalDlType">
        ${Object.entries(FILE_TYPES).map(([k,v]) =>
          `<option value="${k}" ${dl?.file_type===k?'selected':''}>${v}</option>`
        ).join('')}
      </select>
      <label>标题</label>
      <input id="modalDlTitle" value="${esc(dl?.title||'')}" placeholder="如 Windows 10 驱动包">
      <label>MEGA 链接</label>
      <input id="modalDlLink" value="${esc(dl?.mega_link||'')}" placeholder="https://mega.nz/file/...">
      <label>文件大小(可选)</label>
      <input id="modalDlSize" value="${esc(dl?.file_size||'')}" placeholder="如 1.2 GB">
      <label>排序权重(越小越靠前)</label>
      <input id="modalDlSort" type="number" value="${dl?.sort_order??0}" min="0">
      <label>描述(可选)</label>
      <textarea id="modalDlDesc" rows="2">${esc(dl?.description||'')}</textarea>
      <div class="modal-actions">
        <button class="btn-cancel" onclick="hideDeviceModal()">取消</button>
        <button class="btn-save" onclick="saveDownload(${osVersionId},${downloadId||''})">保存</button>
      </div>
    `;
    overlay.classList.add('open');
  }
}

async function saveDownload(osVersionId, downloadId) {
  const file_type = document.getElementById('modalDlType').value;
  const title = document.getElementById('modalDlTitle').value.trim();
  const mega_link = document.getElementById('modalDlLink').value.trim();
  const file_size = document.getElementById('modalDlSize').value.trim();
  const sort_order = parseInt(document.getElementById('modalDlSort').value) || 0;
  const description = document.getElementById('modalDlDesc').value.trim();
  if (!title || !mega_link) { alert('请填写标题和 MEGA 链接'); return; }
  try {
    if (downloadId) {
      await api('PUT', `/api/drivers/admin/downloads/${downloadId}`, { file_type, title, mega_link, file_size, sort_order, description });
    } else {
      await api('POST', '/api/drivers/admin/downloads', { os_version_id: osVersionId, file_type, title, mega_link, file_size, sort_order, description });
    }
    hideDeviceModal();
    await loadDownloads(osVersionId);
  } catch(e) { alert(e.message); }
}

async function deleteDownload(downloadId) {
  if (!confirm('确定删除此下载链接?')) return;
  try {
    await api('DELETE', `/api/drivers/admin/downloads/${downloadId}`);
    if (selectedId) loadOSVersions(selectedId);
  } catch(e) { alert(e.message); }
}

// ── OS Modal ──
function showOSModal(deviceId, osId) {
  const isEdit = !!osId;
  const overlay = document.getElementById('modalOverlay');
  const content = document.getElementById('modalContent');
  let os = null;
  if (isEdit) {
    api('GET', `/api/drivers/admin/os?device_id=${deviceId}`).then(data => {
      os = (data.os_versions||[]).find(x => x.id === osId);
      renderOSForm();
    });
  } else {
    renderOSForm();
  }
  function renderOSForm() {
    content.innerHTML = `
      <h3>${isEdit ? '编辑系统版本' : '添加系统版本'}</h3>
      <label>系统类型</label>
      <select id="modalOSType">
        <option value="android" ${os?.os_type==='android'?'selected':''}>Android</option>
        <option value="windows" ${os?.os_type==='windows'?'selected':''}>Windows</option>
        <option value="linux" ${os?.os_type==='linux'?'selected':''}>Linux</option>
      </select>
      <label>版本名称</label>
      <input id="modalOSVersion" value="${esc(os?.version_name||'')}" placeholder="如 Android 13">
      <label>排序权重</label>
      <input id="modalOSSort" type="number" value="${os?.sort_order??0}" min="0">
      <label>描述(可选)</label>
      <textarea id="modalOSDesc" rows="2">${esc(os?.description||'')}</textarea>
      <div class="modal-actions">
        <button class="btn-cancel" onclick="hideDeviceModal()">取消</button>
        <button class="btn-save" onclick="saveOS(${deviceId},${osId||''})">保存</button>
      </div>
    `;
    overlay.classList.add('open');
  }
}
async function saveOS(deviceId, osId) {
  const os_type = document.getElementById('modalOSType').value;
  const version_name = document.getElementById('modalOSVersion').value.trim();
  const sort_order = parseInt(document.getElementById('modalOSSort').value) || 0;
  const description = document.getElementById('modalOSDesc').value.trim();
  if (!version_name) { alert('请输入版本名称'); return; }
  try {
    if (osId) {
      await api('PUT', `/api/drivers/admin/os/${osId}`, { os_type, version_name, sort_order, description });
    } else {
      await api('POST', '/api/drivers/admin/os', { device_id: deviceId, os_type, version_name, sort_order, description });
    }
    hideDeviceModal();
    await loadOSVersions(deviceId);
  } catch(e) { alert(e.message); }
}
async function deleteOS(osId) {
  if (!confirm('确定删除此系统版本?')) return;
  try {
    await api('DELETE', `/api/drivers/admin/os/${osId}`);
    if (selectedId) loadOSVersions(selectedId);
  } catch(e) { alert(e.message); }
}

// ── Delete device ──
async function deleteDevice(id) {
  if (!confirm('确定删除此设备及其所有系统版本和下载链接?')) return;
  try {
    await api('DELETE', `/api/drivers/admin/devices/${id}`);
    if (selectedId === id) {
      selectedId = null;
      const detail = document.getElementById('deviceDetail');
      const hint = document.getElementById('emptyHint');
      if (detail) detail.style.display = 'none';
      if (hint) hint.style.display = 'block';
    }
    await loadDevices();
  } catch(e) { alert(e.message); }
}

// ── Esc ──
function esc(s) { if (!s) return ''; const d=document.createElement('div'); d.textContent=s; return d.innerHTML; }

// ── Init ──
document.addEventListener('DOMContentLoaded', () => {
  // Login button click
  document.getElementById('loginBtn')?.addEventListener('click', login);
  // Enter key login
  const u = document.getElementById('loginUser');
  const p = document.getElementById('loginPass');
  const k = document.getElementById('loginKey');
  if (u) u.addEventListener('keydown', e => { if (e.key === 'Enter') p?.focus(); });
  if (p) p.addEventListener('keydown', e => { if (e.key === 'Enter') k?.focus(); });
  if (k) k.addEventListener('keydown', e => { if (e.key === 'Enter') login(); });
});
</script>
</body>
</html>