File size: 51,023 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
<!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>
<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">
    <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>驱动管理后台</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="devices" onclick="switchTab('devices')">📱 设备管理</button>
    <button class="admin-tab" data-tab="announce" onclick="switchTab('announce')">📢 公告管理</button>
    <button class="admin-tab" data-tab="monitor" onclick="switchTab('monitor')">📊 监控面板</button>
    <button class="admin-tab" data-tab="megacache" onclick="switchTab('megacache')">🗄️ MEGA 缓存</button>
    <button class="admin-tab" data-tab="mes" onclick="switchTab('mes')">🔧 MES 调试</button>
  </div>
  <div class="admin-body">
    <!-- Sidebar -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h3>设备列表</h3>
        <button class="add-btn" onclick="showDeviceModal()" title="添加设备">+</button>
      </div>
      <div class="search-wrap"><span class="search-icon">🔍</span><input class="search-input" id="searchInput" oninput="filterDevices()" placeholder="搜索设备..."></div>
      <div class="device-list" id="deviceList"></div>
    </div>
    <!-- Main -->
    <div class="main-content" id="mainContent">
      <div class="empty-hint" id="emptyHint">← 选择一个设备,或添加新设备</div>
      <div id="deviceDetail" style="display:none"></div>
    </div>
    <!-- Announcement Panel -->
    <div id="announcePanel" 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;">公告管理</h3>
        <button onclick="showAnnounceForm()" style="background:var(--btn-save-bg);color:#fff;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:13px;">+ 新建公告</button>
      </div>
      <div id="announceForm" class="announce-form" style="display:none;">
        <input type="hidden" id="announceId">
        <div style="display:flex;gap:10px;margin-bottom:10px;">
          <select id="announceKind" style="padding:9px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;background:var(--bg-card);color:var(--text-primary);">
            <option value="公告">📢 公告</option>
            <option value="更新日志">📝 更新日志</option>
            <option value="重要通知">🔔 重要通知</option>
          </select>
          <input id="announceTitle" placeholder="标题" style="flex:1;padding:9px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;background:var(--bg-card);color:var(--text-primary);">
        </div>
        <textarea id="announceContent" placeholder="公告内容..." rows="3" style="width:100%;padding:9px 14px;border:1px solid var(--input-border);border-radius:8px;font-size:13px;resize:vertical;background:var(--bg-card);color:var(--text-primary);margin-bottom:10px;"></textarea>
        <div style="display:flex;gap:10px;align-items:center;margin-bottom:10px;">
          <label style="display:flex;align-items:center;gap:6px;font-size:13px;color:var(--text-secondary);cursor:pointer;">
            <input type="checkbox" id="announceActive" checked> 启用
          </label>
        </div>
        <div style="display:flex;gap:8px;">
          <button onclick="saveAnnouncement()" style="padding:8px 20px;background:var(--btn-save-bg);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;">保存</button>
          <button onclick="hideAnnounceForm()" 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="announceList"></div>
    </div>
    <!-- Monitor Panel -->
    <div id="monitorPanel" style="display:none;flex:1;overflow-y:auto;padding:24px;">
      <h3 style="font-size:18px;margin-bottom:16px;">监控面板</h3>
      <div class="dash-grid" id="dashGrid">
        <div class="dash-card"><div class="num" id="statTotalVisits">-</div><div class="label">总访问量</div></div>
        <div class="dash-card"><div class="num" id="statTodayVisits">-</div><div class="label">今日访问</div></div>
        <div class="dash-card"><div class="num" id="statTotalDownloads">-</div><div class="label">总下载点击</div></div>
        <div class="dash-card"><div class="num" id="statTodayDownloads">-</div><div class="label">今日下载</div></div>
      </div>
      <div class="dash-section"><h3>热门设备排行</h3><div id="dashTopDevices"><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>最近访问</h3><div id="dashRecentVisits"><div class="dash-row" style="color:var(--text-muted)">暂无数据</div></div></div>
        <div class="dash-section"><h3>最近下载</h3><div id="dashRecentDownloads"><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>
    <!-- MEGA Cache Panel -->
    <div id="megaPanel" 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;">MEGA 缓存状态</h3>
        <button onclick="loadMegaCache()" 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="megaDashGrid">
        <div class="dash-card"><div class="num" id="megaTotal">-</div><div class="label">MEGA 总文件数</div></div>
        <div class="dash-card"><div class="num" id="megaExported">-</div><div class="label">已导出到本地</div></div>
        <div class="dash-card"><div class="num" id="megaWithLinks">-</div><div class="label">有下载链接</div></div>
        <div class="dash-card"><div class="num" id="megaSize">-</div><div class="label">总大小</div></div>
      </div>
      <!-- Progress bar -->
      <div class="dash-section" style="margin-bottom:16px;">
        <h3>导出进度</h3>
        <div id="megaProgressWrap" style="padding:16px 18px;">
          <div id="megaProgressBar" style="height:24px;background:var(--bg-subtle);border-radius:12px;overflow:hidden;">
            <div id="megaProgressFill" style="height:100%;width:0%;background:linear-gradient(90deg,#3b82f6,#8b5cf6);border-radius:12px;transition:width .5s ease;display:flex;align-items:center;justify-content:center;"></div>
          </div>
          <div id="megaProgressText" style="text-align:center;margin-top:6px;font-size:13px;color:var(--text-muted);">加载中...</div>
        </div>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
        <div class="dash-section"><h3>文件类型分布</h3><div id="megaExtensions"><div class="dash-row" style="color:var(--text-muted)">加载中...</div></div></div>
        <div class="dash-section"><h3>最近导入</h3><div id="megaRecent"><div class="dash-row" style="color:var(--text-muted)">加载中...</div></div></div>
      </div>
    </div>
  </div>
</div>

<!-- ─── Modal ─── -->
<div class="modal-overlay" id="modalOverlay">
  <div class="modal" id="modalContent"></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');
  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})
    });
    const data = await r.json();
    if (!r.ok) { err.textContent = data.detail||'登录失败'; return; }
    token = data.token;
    localStorage.setItem('drivers_token', token);
    showAdmin();
  } catch(e) { err.textContent = '服务器连接失败'; }
}

function logout() {
  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 = '';
}

// ── 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 = '管理员';
  loadDevices();
}

// Auto-login
if (token) 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);
  if (r.status === 401) { logout(); return null; }
  const data = await r.json();
  if (!r.ok) throw new Error(data.detail||'请求失败');
  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');
  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>';
  }
}
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;
  }
}

// ── Tab switching ──
function switchTab(name) {
  document.querySelectorAll('.admin-tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
  document.getElementById('mainContent').style.display = name==='devices'?'flex':'none';
  document.getElementById('announcePanel').style.display = name==='announce'?'block':'none';
  document.getElementById('monitorPanel').style.display = name==='monitor'?'block':'none';
  document.getElementById('mesPanel').style.display = name==='mes'?'block':'none';
  document.getElementById('megaPanel').style.display = name==='megacache'?'block':'none';
  // Stop MEGA auto-refresh when leaving tab
  if (name !== 'megacache' && _megaTimer) { clearTimeout(_megaTimer); _megaTimer = null; }
  if (name==='announce') loadAnnouncements();
  if (name==='monitor') loadDashboard();
  if (name==='megacache') loadMegaCache();
}

// ── 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('megaExported').textContent = d.total.toLocaleString();
    document.getElementById('megaWithLinks').textContent = d.with_links.toLocaleString();
    document.getElementById('megaSize').textContent = formatSize(d.total_size);

    // Progress bar
    const pct = d.total_on_mega > 0 ? (d.total / d.total_on_mega * 100) : 0;
    const fill = document.getElementById('megaProgressFill');
    fill.style.width = Math.min(pct, 100) + '%';
    fill.textContent = pct >= 8 ? pct.toFixed(1) + '%' : '';
    const isComplete = d.total >= d.total_on_mega;
    document.getElementById('megaProgressText').textContent =
      d.total.toLocaleString() + ' / ' + d.total_on_mega.toLocaleString() +
      (d.last_update ? ' · 最后更新: ' + d.last_update : '') +
      (isComplete ? ' ✓ 全部导入完成' : ' · 后台自动导入中...');

    // 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>';
    }

    // Auto-refresh: 每 5 秒轮询直到全部导入完成
    if (_megaTimer) clearTimeout(_megaTimer);
    if (!isComplete) {
      _megaTimer = setTimeout(loadMegaCache, 5000);
    } else {
      _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 d = devices.find(x => x.id === id);
  if (!d) return;
  const detail = document.getElementById('deviceDetail');
  const hint = document.getElementById('emptyHint');
  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 style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;background:var(--bg-subtle);border-radius:8px;margin-bottom:6px">
          <div>
            <span style="font-weight:500;font-size:13px">${OS_NAMES[os.os_type]||os.os_type}</span>
            <span style="color:var(--text-muted);font-size:12px;margin-left:8px">${esc(os.version_name)}</span>
          </div>
          <div style="display:flex;gap:6px">
            <button onclick="showOSModal(${deviceId},${os.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="deleteOS(${os.id})" style="background:none;border:1px solid #fca5a5;border-radius:6px;padding:4px 10px;cursor:pointer;font-size:12px;color:#dc2626">删除</button>
          </div>
        </div>
      `).join('');
    }
    el.innerHTML = html;
  } catch(e) { el.innerHTML = '<div style="color:#dc2626">加载失败: '+e.message+'</div>'; }
}

// ── 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;
      document.getElementById('deviceDetail').style.display = 'none';
      document.getElementById('emptyHint').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: show devices by default ──
document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('.admin-tab[data-tab="devices"]')?.click();
  // Login button click
  document.getElementById('loginBtn')?.addEventListener('click', login);
  // Enter key login
  const u = document.getElementById('loginUser');
  const p = document.getElementById('loginPass');
  if (u) u.addEventListener('keydown', e => { if (e.key === 'Enter') p?.focus(); });
  if (p) p.addEventListener('keydown', e => { if (e.key === 'Enter') login(); });
  // Click overlay to close modal
  document.getElementById('modalOverlay')?.addEventListener('click', function(e) {
    if (e.target === this) hideDeviceModal();
  });
});
</script>
</body>
</html>