File size: 62,238 Bytes
7c5da52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="vi" class="dark">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>XetCloud Studio — Hugging Face Bucket Storage</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://unpkg.com/lucide@latest"></script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
  <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          fontFamily: {
            sans: ['Inter', 'sans-serif'],
            mono: ['JetBrains Mono', 'monospace'],
          },
          colors: {
            space: {
              950: '#05070f',
              900: '#0a0e1a',
              800: '#111827',
              700: '#1e293b',
            }
          }
        }
      }
    }
  </script>
  <style>
    body {
      background-color: #05070f;
      color: #f8fafc;
      overflow-x: hidden;
    }
    /* Ambient Mesh Glow */
    .bg-mesh {
      background-image: 
        radial-gradient(at 15% 10%, rgba(99, 102, 241, 0.16) 0px, transparent 45%),
        radial-gradient(at 85% 15%, rgba(245, 158, 11, 0.12) 0px, transparent 45%),
        radial-gradient(at 50% 85%, rgba(16, 185, 129, 0.10) 0px, transparent 50%);
    }
    .glass {
      background: rgba(15, 23, 42, 0.65);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.08);
    }
    .glass-card {
      background: linear-gradient(145deg, rgba(30, 41, 59, 0.55), rgba(15, 23, 42, 0.75));
      backdrop-filter: blur(16px);
      border: 1px solid rgba(255, 255, 255, 0.07);
      transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .glass-card:hover {
      border-color: rgba(99, 102, 241, 0.45);
      transform: translateY(-2px);
      box-shadow: 0 12px 32px -8px rgba(0, 0, 0, 0.5), 0 0 20px -4px rgba(99, 102, 241, 0.2);
    }
    .drop-active {
      border-color: #6366f1 !important;
      background: rgba(99, 102, 241, 0.12) !important;
      box-shadow: 0 0 35px rgba(99, 102, 241, 0.25);
    }
    /* Custom Scrollbar */
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: #05070f; }
    ::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 9999px; }
    ::-webkit-scrollbar-thumb:hover { background: #475569; }

    @keyframes pulse-slow {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.45; }
    }
    .animate-pulse-slow { animation: pulse-slow 2.5s infinite; }
  </style>
</head>
<body class="min-h-screen bg-mesh font-sans antialiased selection:bg-indigo-500 selection:text-white flex flex-col">

  <!-- TOP NAVBAR -->
  <header class="sticky top-0 z-30 glass border-b border-white/10">
    <div class="max-w-[1600px] mx-auto px-4 sm:px-8 h-16 flex items-center justify-between gap-4">
      <!-- Brand -->
      <div class="flex items-center gap-3.5">
        <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 via-purple-500 to-amber-500 p-[1px] shadow-lg shadow-indigo-500/20">
          <div class="w-full h-full bg-space-900 rounded-[11px] flex items-center justify-center">
            <span class="text-xl">🤗</span>
          </div>
        </div>
        <div>
          <div class="flex items-center gap-2">
            <h1 class="font-bold text-base sm:text-lg tracking-tight bg-gradient-to-r from-white via-slate-200 to-indigo-300 bg-clip-text text-transparent">
              XetCloud Studio
            </h1>
            <span class="hidden sm:inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-mono font-semibold uppercase tracking-wider bg-indigo-500/15 text-indigo-300 border border-indigo-500/30">
              HF Xet Engine
            </span>
          </div>
          <p class="text-xs text-slate-400 font-mono" id="bucketBadge">bucket: loading...</p>
        </div>
      </div>

      <!-- Global Search -->
      <div class="flex-1 max-w-md hidden md:block">
        <div class="relative">
          <i data-lucide="search" class="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none"></i>
          <input
            id="searchInput"
            type="text"
            placeholder="Tìm kiếm nhanh file hoặc thư mục... (Ctrl + K)"
            class="w-full bg-slate-900/80 border border-white/10 focus:border-indigo-500/70 rounded-xl pl-10 pr-12 py-2 text-sm text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 transition"
          />
          <kbd class="absolute right-3 top-1/2 -translate-y-1/2 text-[10px] font-mono text-slate-400 bg-slate-800 px-1.5 py-0.5 rounded border border-white/10">⌘K</kbd>
        </div>
      </div>

      <!-- Status & Actions -->
      <div class="flex items-center gap-2.5">
        <!-- Health Pill -->
        <div id="healthBadge" class="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-xl bg-slate-900/90 border border-white/10 text-xs font-medium text-slate-300">
          <span id="healthDot" class="w-2 h-2 rounded-full bg-amber-400 animate-pulse"></span>
          <span id="healthText">Checking CLI...</span>
        </div>

        <!-- Upload Trigger Button -->
        <button onclick="openUploadModal()" class="flex items-center gap-2 px-3.5 py-2 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-white font-medium text-xs sm:text-sm shadow-lg shadow-indigo-600/25 transition active:scale-95">
          <i data-lucide="upload-cloud" class="w-4 h-4"></i>
          <span>Tải lên</span>
        </button>

        <!-- API Key Config Button -->
        <button onclick="openAuthModal()" id="authBtn" class="flex items-center gap-2 px-3 py-2 rounded-xl bg-slate-900/90 hover:bg-slate-800 border border-white/10 text-xs sm:text-sm text-slate-300 transition" title="Cấu hình API Key">
          <i data-lucide="key-round" class="w-4 h-4 text-amber-400"></i>
          <span id="authStatusText" class="hidden lg:inline">API Key</span>
        </button>

        <!-- Refresh -->
        <button onclick="loadFiles(true)" class="p-2 rounded-xl bg-slate-900/90 hover:bg-slate-800 border border-white/10 text-slate-300 hover:text-white transition" title="Làm mới (R)">
          <i data-lucide="refresh-cw" id="refreshIcon" class="w-4 h-4"></i>
        </button>
      </div>
    </div>
  </header>

  <!-- MAIN WORKSPACE -->
  <div class="max-w-[1600px] w-full mx-auto px-4 sm:px-8 py-6 flex-1 grid grid-cols-1 lg:grid-cols-12 gap-6">

    <!-- LEFT SIDEBAR: STORAGE STATS & QUICK FILTERS -->
    <aside class="lg:col-span-3 space-y-5">
      <!-- Storage Overview Card -->
      <div class="glass rounded-2xl p-5 relative overflow-hidden">
        <div class="absolute -right-8 -top-8 w-32 h-32 bg-indigo-500/15 rounded-full blur-2xl pointer-events-none"></div>
        <div class="flex items-center justify-between mb-4">
          <span class="text-xs font-semibold uppercase tracking-wider text-slate-400">Dung lượng Bucket</span>
          <span class="px-2 py-0.5 text-[11px] font-mono rounded-md bg-emerald-500/15 text-emerald-300 border border-emerald-500/30">Active</span>
        </div>
        <div class="flex items-baseline gap-2 mb-1">
          <span id="statTotalSize" class="text-3xl font-extrabold tracking-tight text-white">0 B</span>
          <span class="text-xs text-slate-400 font-mono">/ 10 GiB max upload</span>
        </div>
        <p class="text-xs text-slate-400 mb-4">Tổng cộng <strong id="statTotalFiles" class="text-slate-200">0</strong> tệp tin trên đám mây</p>

        <!-- Category Breakdown Bar -->
        <div class="w-full h-2 rounded-full bg-slate-800 overflow-hidden flex gap-0.5 mb-4">
          <div id="barVideo" class="bg-rose-500 h-full transition-all duration-500" style="width: 0%"></div>
          <div id="barImage" class="bg-indigo-500 h-full transition-all duration-500" style="width: 0%"></div>
          <div id="barArchive" class="bg-amber-500 h-full transition-all duration-500" style="width: 0%"></div>
          <div id="barOther" class="bg-emerald-500 h-full transition-all duration-500" style="width: 0%"></div>
        </div>

        <div class="grid grid-cols-2 gap-2 text-xs">
          <div class="flex items-center gap-2 text-slate-300">
            <span class="w-2 h-2 rounded-full bg-rose-500"></span>
            <span>Video:</span>
            <span id="countVideo" class="font-mono text-slate-400 ml-auto">0</span>
          </div>
          <div class="flex items-center gap-2 text-slate-300">
            <span class="w-2 h-2 rounded-full bg-indigo-500"></span>
            <span>Hình ảnh:</span>
            <span id="countImage" class="font-mono text-slate-400 ml-auto">0</span>
          </div>
          <div class="flex items-center gap-2 text-slate-300">
            <span class="w-2 h-2 rounded-full bg-amber-500"></span>
            <span>Nén/Archive:</span>
            <span id="countArchive" class="font-mono text-slate-400 ml-auto">0</span>
          </div>
          <div class="flex items-center gap-2 text-slate-300">
            <span class="w-2 h-2 rounded-full bg-emerald-500"></span>
            <span>Tài liệu/Khác:</span>
            <span id="countOther" class="font-mono text-slate-400 ml-auto">0</span>
          </div>
        </div>
      </div>

      <!-- Navigation / Category Filter -->
      <div class="glass rounded-2xl p-3 space-y-1">
        <div class="px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-slate-400">Bộ lọc thông minh</div>
        <button onclick="setCategory('all')" id="nav-all" class="nav-btn w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium bg-indigo-600/20 text-indigo-300 border border-indigo-500/30 transition">
          <span class="flex items-center gap-2.5"><i data-lucide="folder-kanban" class="w-4 h-4"></i> Tất cả tệp tin</span>
          <span id="badge-all" class="text-xs font-mono px-2 py-0.5 rounded-md bg-white/10">0</span>
        </button>
        <button onclick="setCategory('video')" id="nav-video" class="nav-btn w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium text-slate-300 hover:bg-white/5 transition">
          <span class="flex items-center gap-2.5"><i data-lucide="film" class="w-4 h-4 text-rose-400"></i> Video & Media</span>
          <span id="badge-video" class="text-xs font-mono px-2 py-0.5 rounded-md bg-white/5">0</span>
        </button>
        <button onclick="setCategory('image')" id="nav-image" class="nav-btn w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium text-slate-300 hover:bg-white/5 transition">
          <span class="flex items-center gap-2.5"><i data-lucide="image" class="w-4 h-4 text-indigo-400"></i> Hình ảnh</span>
          <span id="badge-image" class="text-xs font-mono px-2 py-0.5 rounded-md bg-white/5">0</span>
        </button>
        <button onclick="setCategory('archive')" id="nav-archive" class="nav-btn w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium text-slate-300 hover:bg-white/5 transition">
          <span class="flex items-center gap-2.5"><i data-lucide="archive" class="w-4 h-4 text-amber-400"></i> File nén (.zip, .tar)</span>
          <span id="badge-archive" class="text-xs font-mono px-2 py-0.5 rounded-md bg-white/5">0</span>
        </button>
        <button onclick="setCategory('doc')" id="nav-doc" class="nav-btn w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium text-slate-300 hover:bg-white/5 transition">
          <span class="flex items-center gap-2.5"><i data-lucide="file-code-2" class="w-4 h-4 text-emerald-400"></i> Tài liệu & Code</span>
          <span id="badge-doc" class="text-xs font-mono px-2 py-0.5 rounded-md bg-white/5">0</span>
        </button>
      </div>

      <!-- Quick Dropzone Card -->
      <div
        id="quickDropzone"
        onclick="openUploadModal()"
        class="glass rounded-2xl p-5 border-2 border-dashed border-indigo-500/30 hover:border-indigo-400/70 transition cursor-pointer group text-center"
      >
        <div class="w-12 h-12 rounded-2xl bg-indigo-500/15 border border-indigo-500/30 flex items-center justify-center mx-auto mb-3 group-hover:scale-110 transition">
          <i data-lucide="cloud-upload" class="w-6 h-6 text-indigo-400"></i>
        </div>
        <p class="text-sm font-semibold text-slate-200 mb-1">Kéo & Thả file vào đây</p>
        <p class="text-xs text-slate-400">Hỗ trợ tải nhiều file cùng lúc qua giao thức Xet tốc độ cao</p>
      </div>
    </aside>

    <!-- RIGHT MAIN EXPLORER -->
    <main class="lg:col-span-9 flex flex-col space-y-4">
      <!-- Explorer Toolbar -->
      <div class="glass rounded-2xl p-3.5 sm:px-5 flex flex-wrap items-center justify-between gap-3">
        <!-- Breadcrumbs -->
        <div id="breadcrumbs" class="flex items-center gap-1.5 text-sm overflow-x-auto py-1">
          <!-- Populated by JS -->
        </div>

        <!-- Controls: Prefix filter, Sort, View switcher -->
        <div class="flex items-center gap-2 ml-auto">
          <!-- Mobile search -->
          <div class="relative md:hidden">
            <input
              id="mobileSearchInput"
              type="text"
              placeholder="Lọc tên file..."
              class="w-36 bg-slate-900/90 border border-white/10 rounded-xl px-3 py-1.5 text-xs text-slate-100 focus:outline-none"
            />
          </div>

          <!-- Sort Dropdown -->
          <select id="sortSelect" onchange="renderExplorer()" class="bg-slate-900/90 border border-white/10 rounded-xl px-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:border-indigo-500 cursor-pointer">
            <option value="date_desc">Mới nhất trước</option>
            <option value="size_desc">Dung lượng giảm dần</option>
            <option value="size_asc">Dung lượng tăng dần</option>
            <option value="name_asc">Tên A → Z</option>
          </select>

          <!-- View Switcher -->
          <div class="flex items-center bg-slate-900/90 p-1 rounded-xl border border-white/10">
            <button onclick="setViewMode('grid')" id="viewGridBtn" class="p-1.5 rounded-lg bg-indigo-600 text-white transition" title="Chế độ Lưới">
              <i data-lucide="layout-grid" class="w-4 h-4"></i>
            </button>
            <button onclick="setViewMode('list')" id="viewListBtn" class="p-1.5 rounded-lg text-slate-400 hover:text-white transition" title="Chế độ Danh sách">
              <i data-lucide="list" class="w-4 h-4"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- Active Upload Queue Banner (Hidden when idle) -->
      <div id="uploadQueuePanel" class="hidden glass rounded-2xl p-4 border border-indigo-500/40 space-y-3">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2 text-sm font-semibold text-indigo-300">
            <i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i>
            <span>Tiến trình tải lên Hugging Face Bucket</span>
          </div>
          <span id="uploadQueueSummary" class="text-xs font-mono text-slate-400">0/0 hoàn tất</span>
        </div>
        <div id="uploadQueueList" class="space-y-2 max-h-44 overflow-y-auto pr-1"></div>
      </div>

      <!-- File Explorer Container -->
      <div id="explorerContainer" class="glass rounded-2xl p-5 flex-1 min-h-[480px] flex flex-col justify-between relative">
        <!-- Loading Skeleton -->
        <div id="loadingSkeleton" class="hidden grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
          <div class="h-36 rounded-2xl bg-slate-800/50 animate-pulse border border-white/5"></div>
          <div class="h-36 rounded-2xl bg-slate-800/50 animate-pulse border border-white/5"></div>
          <div class="h-36 rounded-2xl bg-slate-800/50 animate-pulse border border-white/5"></div>
          <div class="h-36 rounded-2xl bg-slate-800/50 animate-pulse border border-white/5"></div>
          <div class="h-36 rounded-2xl bg-slate-800/50 animate-pulse border border-white/5"></div>
          <div class="h-36 rounded-2xl bg-slate-800/50 animate-pulse border border-white/5"></div>
        </div>

        <!-- Folders + Files Dynamic Area -->
        <div id="explorerContent" class="space-y-6"></div>

        <!-- Empty State -->
        <div id="emptyState" class="hidden my-auto py-16 text-center">
          <div class="w-16 h-16 rounded-3xl bg-slate-800/80 border border-white/10 flex items-center justify-center mx-auto mb-4 text-slate-400">
            <i data-lucide="folder-open" class="w-8 h-8"></i>
          </div>
          <h3 class="text-base font-semibold text-slate-200 mb-1">Không tìm thấy tệp tin nào</h3>
          <p class="text-xs text-slate-400 max-w-sm mx-auto mb-5">Thư mục này đang trống hoặc không có tệp nào khớp với bộ lọc tìm kiếm hiện tại.</p>
          <button onclick="openUploadModal()" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-semibold transition">
            <i data-lucide="plus" class="w-4 h-4"></i> Tải tệp đầu tiên lên
          </button>
        </div>

        <!-- Footer Status Bar -->
        <div class="mt-6 pt-3 border-t border-white/5 flex items-center justify-between text-[11px] text-slate-400 font-mono">
          <span id="explorerFooterLeft">Sẵn sàng</span>
          <span id="explorerFooterRight">Xet Storage Engine • Go REST API</span>
        </div>
      </div>
    </main>
  </div>

  <!-- ================= MODALS ================= -->

  <!-- 1. UPLOAD MODAL -->
  <div id="uploadModal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/75 backdrop-blur-sm p-4">
    <div class="glass w-full max-w-lg rounded-3xl p-6 border border-white/15 shadow-2xl relative animate-in fade-in zoom-in-95 duration-200">
      <div class="flex items-center justify-between mb-5">
        <div class="flex items-center gap-3">
          <div class="w-10 h-10 rounded-2xl bg-indigo-500/20 border border-indigo-500/30 flex items-center justify-center text-indigo-400">
            <i data-lucide="upload-cloud" class="w-5 h-5"></i>
          </div>
          <div>
            <h3 class="text-base font-bold text-white">Tải tệp lên Bucket</h3>
            <p class="text-xs text-slate-400">Truyền tải trực tiếp qua giao thức Hugging Face Xet</p>
          </div>
        </div>
        <button onclick="closeUploadModal()" class="p-1.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-400 hover:text-white transition">
          <i data-lucide="x" class="w-4 h-4"></i>
        </button>
      </div>

      <div class="space-y-4">
        <!-- Target Folder / Prefix -->
        <div>
          <label class="block text-xs font-medium text-slate-300 mb-1.5">Thư mục đích trên Bucket (tùy chọn)</label>
          <div class="relative">
            <i data-lucide="folder-git-2" class="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2"></i>
            <input
              id="uploadFolderInput"
              type="text"
              placeholder="Ví dụ: videos/2026 hoặc để trống lưu ở gốc"
              class="w-full bg-slate-900/90 border border-white/10 focus:border-indigo-500 rounded-xl pl-10 pr-4 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none font-mono"
            />
          </div>
        </div>

        <!-- File Drop Area -->
        <label
          id="modalDropzone"
          class="flex flex-col items-center justify-center p-8 border-2 border-dashed border-white/15 hover:border-indigo-500/60 rounded-2xl bg-slate-900/50 cursor-pointer transition"
        >
          <input id="fileInput" type="file" multiple class="hidden" onchange="handleFileSelect(this.files)" />
          <i data-lucide="file-up" class="w-10 h-10 text-indigo-400 mb-2.5"></i>
          <span class="text-sm font-medium text-slate-200">Nhấn để chọn file hoặc kéo thả vào đây</span>
          <span class="text-xs text-slate-400 mt-1">Hỗ trợ chọn nhiều file cùng lúc (Tối đa 10 GiB/file)</span>
        </label>

        <!-- Selected Files Preview -->
        <div id="selectedFilesList" class="hidden space-y-1.5 max-h-40 overflow-y-auto pr-1"></div>

        <div class="flex items-center justify-end gap-2.5 pt-2">
          <button onclick="closeUploadModal()" class="px-4 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-xs font-medium text-slate-300 transition">
            Hủy
          </button>
          <button id="startUploadBtn" onclick="startBatchUpload()" class="px-5 py-2.5 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-xs font-semibold text-white shadow-lg shadow-indigo-600/30 transition flex items-center gap-2">
            <i data-lucide="sparkles" class="w-4 h-4"></i>
            <span>Bắt đầu tải lên</span>
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 2. MEDIA PREVIEW & FILE INSPECTOR MODAL -->
  <div id="previewModal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/80 backdrop-blur-md p-4">
    <div class="glass w-full max-w-4xl rounded-3xl overflow-hidden border border-white/15 shadow-2xl flex flex-col max-h-[90vh]">
      <!-- Modal Header -->
      <div class="px-6 py-4 border-b border-white/10 flex items-center justify-between gap-4">
        <div class="flex items-center gap-3 min-w-0">
          <div id="previewIconBox" class="w-9 h-9 rounded-xl bg-indigo-500/20 flex items-center justify-center text-indigo-400 shrink-0">
            <i data-lucide="file" class="w-5 h-5"></i>
          </div>
          <div class="min-w-0">
            <h3 id="previewTitle" class="text-sm sm:text-base font-bold text-white truncate">filename.mp4</h3>
            <p id="previewSubtitle" class="text-xs text-slate-400 font-mono truncate">46.7 MB • 2026-09-15</p>
          </div>
        </div>
        <div class="flex items-center gap-2 shrink-0">
          <button id="previewCopyCurlBtn" class="px-3 py-1.5 rounded-xl bg-white/5 hover:bg-white/10 text-xs font-mono text-slate-300 flex items-center gap-1.5 transition" title="Copy lệnh cURL tải file">
            <i data-lucide="terminal" class="w-3.5 h-3.5"></i> cURL
          </button>
          <button id="previewDownloadBtn" class="px-3.5 py-1.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-xs font-semibold text-white flex items-center gap-1.5 transition">
            <i data-lucide="download" class="w-3.5 h-3.5"></i> Tải xuống
          </button>
          <button id="previewDeleteBtn" class="p-1.5 rounded-xl bg-rose-500/15 hover:bg-rose-500/30 text-rose-400 transition" title="Xóa tệp tin">
            <i data-lucide="trash-2" class="w-4 h-4"></i>
          </button>
          <button onclick="closePreviewModal()" class="p-1.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-400 hover:text-white transition">
            <i data-lucide="x" class="w-4 h-4"></i>
          </button>
        </div>
      </div>

      <!-- Preview Body -->
      <div id="previewBody" class="p-6 flex-1 overflow-auto flex items-center justify-center bg-space-950/60 min-h-[320px]">
        <!-- Dynamic video / image / text / metadata card -->
      </div>
    </div>
  </div>

  <!-- 3. API KEY AUTH MODAL -->
  <div id="authModal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/75 backdrop-blur-sm p-4">
    <div class="glass w-full max-w-md rounded-3xl p-6 border border-white/15 shadow-2xl">
      <div class="flex items-center justify-between mb-4">
        <div class="flex items-center gap-3">
          <div class="w-10 h-10 rounded-2xl bg-amber-500/20 border border-amber-500/30 flex items-center justify-center text-amber-400">
            <i data-lucide="shield-check" class="w-5 h-5"></i>
          </div>
          <div>
            <h3 class="text-base font-bold text-white">Xác thực API Key</h3>
            <p class="text-xs text-slate-400">Bảo vệ kết nối tới Go Bucket Server</p>
          </div>
        </div>
        <button onclick="closeAuthModal()" class="p-1.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-400 hover:text-white">
          <i data-lucide="x" class="w-4 h-4"></i>
        </button>
      </div>

      <p class="text-xs text-slate-300 mb-4 leading-relaxed">
        Nhập khóa <code class="text-amber-300 font-mono">API_KEY</code> được cấu hình trong file <code class="text-indigo-300 font-mono">.env</code> của server. Khóa được lưu cục bộ trên trình duyệt của bạn.
      </p>

      <div class="space-y-4">
        <div class="relative">
          <i data-lucide="key" class="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2"></i>
          <input
            id="apiKeyInput"
            type="password"
            placeholder="Nhập API_KEY..."
            class="w-full bg-slate-900 border border-white/15 focus:border-amber-400 rounded-xl pl-10 pr-10 py-2.5 text-sm text-white font-mono focus:outline-none"
          />
          <button type="button" onclick="toggleApiKeyVisibility()" class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white">
            <i data-lucide="eye" class="w-4 h-4"></i>
          </button>
        </div>

        <div class="flex justify-end gap-2">
          <button onclick="closeAuthModal()" class="px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-xs text-slate-300">Đóng</button>
          <button onclick="saveApiKey()" class="px-5 py-2 rounded-xl bg-amber-500 hover:bg-amber-400 text-slate-950 font-semibold text-xs transition">
            Lưu & Kết nối
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- TOAST CONTAINER -->
  <div id="toastContainer" class="fixed bottom-5 right-5 z-50 flex flex-col gap-2.5 max-w-sm w-full pointer-events-none"></div>

  <!-- APPLICATION SCRIPT -->
  <script>
    // --- STATE ---
    const state = {
      apiKey: localStorage.getItem('hf_bucket_api_key') || 'thtuanit207',
      bucket: 'TwanAPI/ThTuan',
      files: [],        // [{ path, name, folder, size, updatedAt, ext, category }]
      currentFolder: '', // '' is root
      category: 'all',
      search: '',
      viewMode: localStorage.getItem('hf_view_mode') || 'grid',
      selectedUploadFiles: [],
    };

    // --- UTILITIES ---
    function formatBytes(bytes) {
      if (!bytes || bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    function getFileCategory(filename) {
      const ext = (filename.split('.').pop() || '').toLowerCase();
      if (['mp4', 'mkv', 'webm', 'mov', 'avi', 'mp3', 'wav', 'flac', 'ogg'].includes(ext)) return 'video';
      if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico'].includes(ext)) return 'image';
      if (['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz'].includes(ext)) return 'archive';
      return 'doc';
    }

    function getCategoryMeta(cat, ext) {
      switch (cat) {
        case 'video':
          return { icon: 'film', color: 'text-rose-400', bg: 'bg-rose-500/15', border: 'border-rose-500/30', label: ext.toUpperCase() || 'MEDIA' };
        case 'image':
          return { icon: 'image', color: 'text-indigo-400', bg: 'bg-indigo-500/15', border: 'border-indigo-500/30', label: ext.toUpperCase() || 'IMG' };
        case 'archive':
          return { icon: 'archive', color: 'text-amber-400', bg: 'bg-amber-500/15', border: 'border-amber-500/30', label: ext.toUpperCase() || 'ARCHIVE' };
        default:
          return { icon: 'file-code-2', color: 'text-emerald-400', bg: 'bg-emerald-500/15', border: 'border-emerald-500/30', label: ext.toUpperCase() || 'FILE' };
      }
    }

    function showToast(message, type = 'info', detail = '') {
      const container = document.getElementById('toastContainer');
      const el = document.createElement('div');
      const colors = {
        success: 'border-emerald-500/40 bg-emerald-950/90 text-emerald-200',
        error: 'border-rose-500/40 bg-rose-950/90 text-rose-200',
        info: 'border-indigo-500/40 bg-slate-900/95 text-slate-200',
      };
      const icons = {
        success: 'check-circle-2',
        error: 'alert-triangle',
        info: 'sparkles',
      };
      el.className = `pointer-events-auto glass px-4 py-3 rounded-2xl border shadow-xl flex items-start gap-3 transition-all duration-300 ${colors[type] || colors.info}`;
      el.innerHTML = `
        <i data-lucide="${icons[type] || 'info'}" class="w-5 h-5 shrink-0 mt-0.5"></i>
        <div class="min-w-0 flex-1">
          <p class="text-xs font-semibold">${message}</p>
          ${detail ? `<p class="text-[11px] opacity-80 font-mono truncate mt-0.5">${detail}</p>` : ''}
        </div>
      `;
      container.appendChild(el);
      lucide.createIcons({ nodes: [el] });
      setTimeout(() => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(8px)';
        setTimeout(() => el.remove(), 300);
      }, 4200);
    }

    // --- API CALLS ---
    async function checkHealth() {
      try {
        const res = await fetch('/health');
        const data = await res.json();
        const dot = document.getElementById('healthDot');
        const txt = document.getElementById('healthText');
        if (data.ok) {
          state.bucket = data.bucket || state.bucket;
          document.getElementById('bucketBadge').textContent = `hf://buckets/${state.bucket}`;
          dot.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-[0_0_8px_#34d399]';
          txt.textContent = `hf CLI v${data.version}`;
        } else {
          dot.className = 'w-2 h-2 rounded-full bg-rose-500';
          txt.textContent = 'CLI Offline';
        }
      } catch (e) {
        document.getElementById('healthDot').className = 'w-2 h-2 rounded-full bg-rose-500';
        document.getElementById('healthText').textContent = 'Server Offline';
      }
    }

    async function loadFiles(showToastOnSuccess = false) {
      const refreshIcon = document.getElementById('refreshIcon');
      const skeleton = document.getElementById('loadingSkeleton');
      const content = document.getElementById('explorerContent');
      refreshIcon?.classList.add('animate-spin');
      if (state.files.length === 0) {
        skeleton.classList.remove('hidden');
        content.classList.add('hidden');
      }

      try {
        const res = await fetch('/api/files', {
          headers: { 'X-API-Key': state.apiKey }
        });
        const data = await res.json();

        if (res.status === 401) {
          showToast('API Key không hợp lệ hoặc bị thiếu', 'error', 'Vui lòng nhập API_KEY của bạn');
          openAuthModal();
          return;
        }
        if (!res.ok) {
          throw new Error(data.detail || data.error || 'Lỗi tải danh sách file');
        }

        state.bucket = data.bucket || state.bucket;
        document.getElementById('bucketBadge').textContent = `hf://buckets/${state.bucket}`;

        // Parse structured items if provided by backend, else fallback to entries
        if (Array.isArray(data.items)) {
          state.files = data.items.map(item => normalizeFileItem(item.path, item.size || 0, item.updated_at || ''));
        } else if (Array.isArray(data.entries)) {
          state.files = data.entries.map(line => normalizeFileItem(line, 0, ''));
        } else {
          state.files = [];
        }

        updateStats();
        renderExplorer();
        if (showToastOnSuccess) {
          showToast('Đã đồng bộ dữ liệu Bucket', 'success', `${state.files.length} tệp tin hiện có`);
        }
      } catch (err) {
        showToast('Không thể tải danh sách tệp', 'error', err.message);
      } finally {
        refreshIcon?.classList.remove('animate-spin');
        skeleton.classList.add('hidden');
        content.classList.remove('hidden');
      }
    }

    function normalizeFileItem(rawPath, size, updatedAt) {
      const cleanPath = rawPath.replace(/\\/g, '/').replace(/^\/+/, '');
      const parts = cleanPath.split('/');
      const name = parts.pop();
      const folder = parts.join('/');
      const ext = name.includes('.') ? name.split('.').pop().toLowerCase() : '';
      const category = getFileCategory(name);
      return { path: cleanPath, name, folder, size, updatedAt, ext, category };
    }

    function updateStats() {
      const totalSize = state.files.reduce((acc, f) => acc + (f.size || 0), 0);
      document.getElementById('statTotalSize').textContent = formatBytes(totalSize);
      document.getElementById('statTotalFiles').textContent = state.files.length;

      const counts = { video: 0, image: 0, archive: 0, doc: 0 };
      const sizes = { video: 0, image: 0, archive: 0, doc: 0 };
      state.files.forEach(f => {
        counts[f.category] = (counts[f.category] || 0) + 1;
        sizes[f.category] = (sizes[f.category] || 0) + (f.size || 1);
      });

      document.getElementById('countVideo').textContent = counts.video;
      document.getElementById('countImage').textContent = counts.image;
      document.getElementById('countArchive').textContent = counts.archive;
      document.getElementById('countOther').textContent = counts.doc;

      document.getElementById('badge-all').textContent = state.files.length;
      document.getElementById('badge-video').textContent = counts.video;
      document.getElementById('badge-image').textContent = counts.image;
      document.getElementById('badge-archive').textContent = counts.archive;
      document.getElementById('badge-doc').textContent = counts.doc;

      const denom = Math.max(totalSize, state.files.length, 1);
      const useSize = totalSize > 0;
      document.getElementById('barVideo').style.width = `${((useSize ? sizes.video : counts.video) / denom) * 100}%`;
      document.getElementById('barImage').style.width = `${((useSize ? sizes.image : counts.image) / denom) * 100}%`;
      document.getElementById('barArchive').style.width = `${((useSize ? sizes.archive : counts.archive) / denom) * 100}%`;
      document.getElementById('barOther').style.width = `${((useSize ? sizes.doc : counts.doc) / denom) * 100}%`;
    }

    // --- RENDERING EXPLORER ---
    function renderBreadcrumbs() {
      const container = document.getElementById('breadcrumbs');
      const parts = state.currentFolder ? state.currentFolder.split('/') : [];
      let html = `
        <button onclick="navigateToFolder('')" class="flex items-center gap-1.5 px-2.5 py-1 rounded-lg ${parts.length === 0 ? 'bg-indigo-500/20 text-indigo-300 font-semibold' : 'text-slate-400 hover:text-white hover:bg-white/5'} transition">
          <i data-lucide="hard-drive" class="w-3.5 h-3.5"></i>
          <span>${state.bucket}</span>
        </button>
      `;
      let acc = '';
      parts.forEach((p, idx) => {
        acc = acc ? `${acc}/${p}` : p;
        const isLast = idx === parts.length - 1;
        html += `
          <i data-lucide="chevron-right" class="w-3.5 h-3.5 text-slate-600 shrink-0"></i>
          <button onclick="navigateToFolder('${acc.replace(/'/g, "\\'")}')" class="px-2.5 py-1 rounded-lg ${isLast ? 'bg-indigo-500/20 text-indigo-300 font-semibold' : 'text-slate-400 hover:text-white hover:bg-white/5'} transition truncate max-w-[160px]">
            ${p}
          </button>
        `;
      });
      container.innerHTML = html;
    }

    function renderExplorer() {
      renderBreadcrumbs();
      const content = document.getElementById('explorerContent');
      const empty = document.getElementById('emptyState');
      const sortBy = document.getElementById('sortSelect').value;
      const q = state.search.trim().toLowerCase();

      // Determine subfolders when in folder navigation mode (only when category === 'all' and no search query)
      const subfolders = new Map();
      const matchingFiles = [];

      state.files.forEach(file => {
        if (state.category !== 'all' && file.category !== state.category) return;
        if (q) {
          if (file.path.toLowerCase().includes(q)) matchingFiles.push(file);
          return;
        }
        if (state.category !== 'all') {
          matchingFiles.push(file);
          return;
        }

        // Hierarchy filtering inside currentFolder
        if (state.currentFolder === '') {
          if (file.folder === '') {
            matchingFiles.push(file);
          } else {
            const topFolder = file.folder.split('/')[0];
            const stat = subfolders.get(topFolder) || { count: 0, size: 0 };
            stat.count += 1;
            stat.size += file.size || 0;
            subfolders.set(topFolder, stat);
          }
        } else if (file.folder === state.currentFolder) {
          matchingFiles.push(file);
        } else if (file.folder.startsWith(state.currentFolder + '/')) {
          const rest = file.folder.slice(state.currentFolder.length + 1);
          const nextFolder = rest.split('/')[0];
          const fullSubPath = `${state.currentFolder}/${nextFolder}`;
          const stat = subfolders.get(fullSubPath) || { name: nextFolder, count: 0, size: 0 };
          stat.count += 1;
          stat.size += file.size || 0;
          subfolders.set(fullSubPath, stat);
        }
      });

      // Sort files
      matchingFiles.sort((a, b) => {
        if (sortBy === 'size_desc') return (b.size || 0) - (a.size || 0);
        if (sortBy === 'size_asc') return (a.size || 0) - (b.size || 0);
        if (sortBy === 'name_asc') return a.name.localeCompare(b.name);
        return (b.updatedAt || '').localeCompare(a.updatedAt || '');
      });

      if (subfolders.size === 0 && matchingFiles.length === 0) {
        content.innerHTML = '';
        empty.classList.remove('hidden');
        document.getElementById('explorerFooterLeft').textContent = '0 mục';
        lucide.createIcons();
        return;
      }

      empty.classList.add('hidden');
      let html = '';

      // 1. Subfolders Section
      if (subfolders.size > 0) {
        html += `
          <div>
            <h4 class="text-xs font-semibold uppercase tracking-wider text-slate-400 mb-3 flex items-center gap-2">
              <i data-lucide="folder" class="w-3.5 h-3.5 text-amber-400"></i> Thư mục (${subfolders.size})
            </h4>
            <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-3.5">
        `;
        for (const [folderPath, info] of subfolders.entries()) {
          const displayName = info.name || folderPath;
          html += `
            <div onclick="navigateToFolder('${folderPath.replace(/'/g, "\\'")}')" class="glass-card rounded-2xl p-4 cursor-pointer flex items-center gap-3.5 group">
              <div class="w-11 h-11 rounded-xl bg-amber-500/15 border border-amber-500/30 flex items-center justify-center text-amber-400 group-hover:scale-105 transition shrink-0">
                <i data-lucide="folder" class="w-5 h-5 fill-amber-400/20"></i>
              </div>
              <div class="min-w-0 flex-1">
                <p class="text-sm font-semibold text-slate-100 truncate group-hover:text-amber-300 transition">${displayName}</p>
                <p class="text-xs text-slate-400 font-mono">${info.count} tệp • ${formatBytes(info.size)}</p>
              </div>
              <i data-lucide="chevron-right" class="w-4 h-4 text-slate-500 group-hover:text-slate-200 transition"></i>
            </div>
          `;
        }
        html += `</div></div>`;
      }

      // 2. Files Section
      if (matchingFiles.length > 0) {
        html += `
          <div>
            <h4 class="text-xs font-semibold uppercase tracking-wider text-slate-400 mb-3 flex items-center gap-2">
              <i data-lucide="files" class="w-3.5 h-3.5 text-indigo-400"></i> Tệp tin (${matchingFiles.length})
            </h4>
        `;

        if (state.viewMode === 'grid') {
          html += `<div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">`;
          matchingFiles.forEach(file => {
            const meta = getCategoryMeta(file.category, file.ext);
            const escapedPath = file.path.replace(/'/g, "\\'");
            html += `
              <div class="glass-card rounded-2xl p-4 flex flex-col justify-between group relative overflow-hidden">
                <div onclick="openPreviewModal('${escapedPath}')" class="cursor-pointer">
                  <div class="flex items-start justify-between gap-3 mb-3">
                    <div class="w-11 h-11 rounded-xl ${meta.bg} border ${meta.border} flex items-center justify-center ${meta.color} shrink-0 group-hover:scale-105 transition">
                      <i data-lucide="${meta.icon}" class="w-5 h-5"></i>
                    </div>
                    <span class="px-2 py-0.5 rounded-md text-[10px] font-mono font-semibold ${meta.bg} ${meta.color} border ${meta.border}">
                      ${meta.label}
                    </span>
                  </div>
                  <h5 class="text-sm font-semibold text-slate-100 truncate group-hover:text-indigo-300 transition" title="${file.path}">
                    ${file.name}
                  </h5>
                  <p class="text-[11px] text-slate-400 font-mono truncate mt-0.5">
                    ${file.folder ? `📁 ${file.folder}` : 'Root'}
                  </p>
                </div>

                <div class="mt-4 pt-3 border-t border-white/5 flex items-center justify-between text-xs text-slate-400">
                  <div class="font-mono text-[11px]">
                    <span class="text-slate-200 font-medium">${formatBytes(file.size)}</span>
                    ${file.updatedAt ? `<span class="text-slate-500"> • ${file.updatedAt.split(' ')[0]}</span>` : ''}
                  </div>
                  <div class="flex items-center gap-1">
                    <button onclick="openPreviewModal('${escapedPath}')" class="p-1.5 rounded-lg hover:bg-white/10 text-slate-300 hover:text-white transition" title="Xem trước / Chi tiết">
                      <i data-lucide="eye" class="w-3.5 h-3.5"></i>
                    </button>
                    <button onclick="downloadFile('${escapedPath}')" class="p-1.5 rounded-lg hover:bg-indigo-500/20 text-indigo-400 hover:text-indigo-300 transition" title="Tải xuống">
                      <i data-lucide="download" class="w-3.5 h-3.5"></i>
                    </button>
                    <button onclick="deleteFile('${escapedPath}')" class="p-1.5 rounded-lg hover:bg-rose-500/20 text-rose-400 hover:text-rose-300 transition" title="Xóa file">
                      <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                    </button>
                  </div>
                </div>
              </div>
            `;
          });
          html += `</div>`;
        } else {
          // Table / List View
          html += `
            <div class="overflow-x-auto rounded-2xl border border-white/10">
              <table class="w-full text-left border-collapse">
                <thead>
                  <tr class="border-b border-white/10 text-[11px] font-semibold uppercase tracking-wider text-slate-400 bg-slate-900/60">
                    <th class="py-3 px-4">Tên tệp</th>
                    <th class="py-3 px-4 hidden md:table-cell">Đường dẫn</th>
                    <th class="py-3 px-4">Kích thước</th>
                    <th class="py-3 px-4 hidden sm:table-cell">Cập nhật</th>
                    <th class="py-3 px-4 text-right">Thao tác</th>
                  </tr>
                </thead>
                <tbody class="divide-y divide-white/5 text-sm">
          `;
          matchingFiles.forEach(file => {
            const meta = getCategoryMeta(file.category, file.ext);
            const escapedPath = file.path.replace(/'/g, "\\'");
            html += `
              <tr class="hover:bg-white/5 transition group">
                <td onclick="openPreviewModal('${escapedPath}')" class="py-3 px-4 cursor-pointer">
                  <div class="flex items-center gap-3">
                    <div class="w-8 h-8 rounded-lg ${meta.bg} border ${meta.border} flex items-center justify-center ${meta.color} shrink-0">
                      <i data-lucide="${meta.icon}" class="w-4 h-4"></i>
                    </div>
                    <span class="font-medium text-slate-100 group-hover:text-indigo-300 transition truncate max-w-[240px]">${file.name}</span>
                  </div>
                </td>
                <td class="py-3 px-4 hidden md:table-cell font-mono text-xs text-slate-400">${file.folder || '/'}</td>
                <td class="py-3 px-4 font-mono text-xs text-slate-200">${formatBytes(file.size)}</td>
                <td class="py-3 px-4 hidden sm:table-cell font-mono text-xs text-slate-400">${file.updatedAt || '—'}</td>
                <td class="py-3 px-4 text-right">
                  <div class="inline-flex items-center gap-1">
                    <button onclick="openPreviewModal('${escapedPath}')" class="p-1.5 rounded-lg hover:bg-white/10 text-slate-300" title="Xem">
                      <i data-lucide="eye" class="w-4 h-4"></i>
                    </button>
                    <button onclick="downloadFile('${escapedPath}')" class="p-1.5 rounded-lg hover:bg-indigo-500/20 text-indigo-400" title="Tải về">
                      <i data-lucide="download" class="w-4 h-4"></i>
                    </button>
                    <button onclick="deleteFile('${escapedPath}')" class="p-1.5 rounded-lg hover:bg-rose-500/20 text-rose-400" title="Xóa">
                      <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                  </div>
                </td>
              </tr>
            `;
          });
          html += `</tbody></table></div>`;
        }
        html += `</div>`;
      }

      content.innerHTML = html;
      const shownSize = matchingFiles.reduce((acc, f) => acc + (f.size || 0), 0);
      document.getElementById('explorerFooterLeft').textContent =
        `Hiển thị ${subfolders.size} thư mục, ${matchingFiles.length} tệp tin (${formatBytes(shownSize)})`;
      lucide.createIcons();
    }

    // --- NAVIGATION & FILTERS ---
    function navigateToFolder(folderPath) {
      state.currentFolder = folderPath;
      state.category = 'all';
      updateNavButtons();
      renderExplorer();
    }

    function setCategory(cat) {
      state.category = cat;
      updateNavButtons();
      renderExplorer();
    }

    function updateNavButtons() {
      ['all', 'video', 'image', 'archive', 'doc'].forEach(c => {
        const btn = document.getElementById(`nav-${c}`);
        if (!btn) return;
        if (c === state.category) {
          btn.className = 'nav-btn w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium bg-indigo-600/20 text-indigo-300 border border-indigo-500/30 transition';
        } else {
          btn.className = 'nav-btn w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-medium text-slate-300 hover:bg-white/5 transition';
        }
      });
    }

    function setViewMode(mode) {
      state.viewMode = mode;
      localStorage.setItem('hf_view_mode', mode);
      const gridBtn = document.getElementById('viewGridBtn');
      const listBtn = document.getElementById('viewListBtn');
      if (mode === 'grid') {
        gridBtn.className = 'p-1.5 rounded-lg bg-indigo-600 text-white transition';
        listBtn.className = 'p-1.5 rounded-lg text-slate-400 hover:text-white transition';
      } else {
        listBtn.className = 'p-1.5 rounded-lg bg-indigo-600 text-white transition';
        gridBtn.className = 'p-1.5 rounded-lg text-slate-400 hover:text-white transition';
      }
      renderExplorer();
    }

    // --- DOWNLOAD & DELETE & PREVIEW ---
    function getDownloadUrl(path, inline = false) {
      const params = new URLSearchParams({
        path: path,
        api_key: state.apiKey,
      });
      if (inline) params.set('inline', '1');
      return `/api/download?${params.toString()}`;
    }

    function downloadFile(path) {
      showToast('Đang chuẩn bị tải xuống từ Hugging Face...', 'info', path);
      const a = document.createElement('a');
      a.href = getDownloadUrl(path, false);
      a.download = path.split('/').pop();
      document.body.appendChild(a);
      a.click();
      a.remove();
    }

    async function deleteFile(path) {
      if (!confirm(`Bạn có chắc chắn muốn xóa tệp "${path}" khỏi Bucket không?`)) return;
      try {
        showToast('Đang xóa tệp trên Bucket...', 'info', path);
        const res = await fetch(`/api/files?path=${encodeURIComponent(path)}`, {
          method: 'DELETE',
          headers: { 'X-API-Key': state.apiKey }
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || data.error || 'Xóa thất bại');
        showToast('Đã xóa tệp thành công', 'success', path);
        closePreviewModal();
        loadFiles(false);
      } catch (err) {
        showToast('Lỗi khi xóa tệp', 'error', err.message);
      }
    }

    function openPreviewModal(path) {
      const file = state.files.find(f => f.path === path);
      if (!file) return;
      const modal = document.getElementById('previewModal');
      const body = document.getElementById('previewBody');
      document.getElementById('previewTitle').textContent = file.name;
      document.getElementById('previewSubtitle').textContent =
        `${formatBytes(file.size)} • ${file.path} ${file.updatedAt ? '• ' + file.updatedAt : ''}`;

      document.getElementById('previewDownloadBtn').onclick = () => downloadFile(file.path);
      document.getElementById('previewDeleteBtn').onclick = () => deleteFile(file.path);
      document.getElementById('previewCopyCurlBtn').onclick = () => {
        const url = `${window.location.origin}/api/download?path=${encodeURIComponent(file.path)}`;
        const cmd = `curl -L "${url}" -H "X-API-Key: ${state.apiKey}" -o "${file.name}"`;
        navigator.clipboard.writeText(cmd);
        showToast('Đã sao chép lệnh cURL vào Clipboard', 'success');
      };

      const streamUrl = getDownloadUrl(file.path, true);
      if (file.category === 'video') {
        body.innerHTML = `
          <video controls autoplay class="max-h-[65vh] w-full rounded-2xl bg-black shadow-2xl outline-none">
            <source src="${streamUrl}" />
            Trình duyệt của bạn không hỗ trợ phát video trực tiếp.
          </video>
        `;
      } else if (file.category === 'image') {
        body.innerHTML = `
          <img src="${streamUrl}" alt="${file.name}" class="max-h-[65vh] rounded-2xl object-contain shadow-2xl" />
        `;
      } else {
        const meta = getCategoryMeta(file.category, file.ext);
        body.innerHTML = `
          <div class="text-center py-10 px-6 max-w-md">
            <div class="w-20 h-20 rounded-3xl ${meta.bg} border ${meta.border} flex items-center justify-center ${meta.color} mx-auto mb-4">
              <i data-lucide="${meta.icon}" class="w-10 h-10"></i>
            </div>
            <h4 class="text-base font-bold text-white mb-1">${file.name}</h4>
            <p class="text-xs text-slate-400 font-mono mb-6">hf://buckets/${state.bucket}/${file.path}</p>
            <div class="glass rounded-2xl p-4 text-left space-y-2 text-xs font-mono mb-6">
              <div class="flex justify-between"><span class="text-slate-400">Kích thước:</span><span class="text-slate-200">${formatBytes(file.size)} (${(file.size || 0).toLocaleString()} bytes)</span></div>
              <div class="flex justify-between"><span class="text-slate-400">Định dạng:</span><span class="text-slate-200">.${file.ext || 'unknown'}</span></div>
              <div class="flex justify-between"><span class="text-slate-400">Cập nhật:</span><span class="text-slate-200">${file.updatedAt || 'N/A'}</span></div>
            </div>
            <button onclick="downloadFile('${file.path.replace(/'/g, "\\'")}')" class="w-full py-3 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-white font-semibold text-xs shadow-lg shadow-indigo-600/30 transition">
              Tải tệp tin này về máy
            </button>
          </div>
        `;
      }

      modal.classList.remove('hidden');
      modal.classList.add('flex');
      lucide.createIcons({ nodes: [modal] });
    }

    function closePreviewModal() {
      const modal = document.getElementById('previewModal');
      const body = document.getElementById('previewBody');
      body.innerHTML = ''; // Stop playing media
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    // --- UPLOAD LOGIC WITH PROGRESS ---
    function openUploadModal(preselectedFiles = null) {
      const modal = document.getElementById('uploadModal');
      document.getElementById('uploadFolderInput').value = state.currentFolder;
      if (preselectedFiles && preselectedFiles.length > 0) {
        handleFileSelect(preselectedFiles);
      } else {
        state.selectedUploadFiles = [];
        renderSelectedFiles();
      }
      modal.classList.remove('hidden');
      modal.classList.add('flex');
    }

    function closeUploadModal() {
      const modal = document.getElementById('uploadModal');
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    function handleFileSelect(fileList) {
      state.selectedUploadFiles = Array.from(fileList);
      renderSelectedFiles();
    }

    function renderSelectedFiles() {
      const container = document.getElementById('selectedFilesList');
      if (state.selectedUploadFiles.length === 0) {
        container.classList.add('hidden');
        container.innerHTML = '';
        return;
      }
      container.classList.remove('hidden');
      container.innerHTML = state.selectedUploadFiles.map((f, idx) => `
        <div class="flex items-center justify-between px-3 py-2 rounded-xl bg-slate-900/90 border border-white/10 text-xs">
          <div class="flex items-center gap-2 min-w-0">
            <i data-lucide="file-check" class="w-4 h-4 text-indigo-400 shrink-0"></i>
            <span class="truncate text-slate-200 font-medium">${f.name}</span>
          </div>
          <span class="font-mono text-slate-400 shrink-0 ml-2">${formatBytes(f.size)}</span>
        </div>
      `).join('');
      lucide.createIcons({ nodes: [container] });
    }

    async function startBatchUpload() {
      if (state.selectedUploadFiles.length === 0) {
        showToast('Vui lòng chọn ít nhất 1 tệp tin', 'error');
        return;
      }
      const folderPrefix = document.getElementById('uploadFolderInput').value.trim().replace(/^\/+|\/+$/g, '');
      const filesToUpload = [...state.selectedUploadFiles];
      closeUploadModal();

      const queuePanel = document.getElementById('uploadQueuePanel');
      const queueList = document.getElementById('uploadQueueList');
      const queueSummary = document.getElementById('uploadQueueSummary');
      queuePanel.classList.remove('hidden');
      queueList.innerHTML = '';

      let completed = 0;
      queueSummary.textContent = `0/${filesToUpload.length} hoàn tất`;

      for (let i = 0; i < filesToUpload.length; i++) {
        const file = filesToUpload[i];
        const remotePath = folderPrefix ? `${folderPrefix}/${file.name}` : file.name;
        const rowId = `upload-row-${Date.now()}-${i}`;

        const row = document.createElement('div');
        row.id = rowId;
        row.className = 'p-3 rounded-xl bg-slate-900/90 border border-white/10 space-y-1.5';
        row.innerHTML = `
          <div class="flex items-center justify-between text-xs">
            <span class="font-medium text-slate-200 truncate max-w-[260px]">${remotePath}</span>
            <span id="${rowId}-status" class="font-mono text-indigo-300">0%</span>
          </div>
          <div class="w-full h-1.5 rounded-full bg-slate-800 overflow-hidden">
            <div id="${rowId}-bar" class="bg-gradient-to-r from-indigo-500 to-amber-400 h-full transition-all duration-200" style="width: 0%"></div>
          </div>
        `;
        queueList.appendChild(row);

        try {
          await uploadSingleFileXHR(file, remotePath, (pct) => {
            const bar = document.getElementById(`${rowId}-bar`);
            const st = document.getElementById(`${rowId}-status`);
            if (bar) bar.style.width = `${pct}%`;
            if (st) st.textContent = pct >= 100 ? 'Đang đồng bộ HF Xet...' : `${pct}%`;
          });
          const st = document.getElementById(`${rowId}-status`);
          if (st) {
            st.textContent = 'Hoàn tất ✓';
            st.className = 'font-mono text-emerald-400';
          }
          completed++;
          queueSummary.textContent = `${completed}/${filesToUpload.length} hoàn tất`;
        } catch (err) {
          const st = document.getElementById(`${rowId}-status`);
          if (st) {
            st.textContent = 'Lỗi ✗';
            st.className = 'font-mono text-rose-400';
          }
          showToast(`Lỗi tải lên ${file.name}`, 'error', err.message);
        }
      }

      showToast(`Đã tải lên ${completed}/${filesToUpload.length} tệp tin!`, 'success');
      await loadFiles(false);
      setTimeout(() => {
        queuePanel.classList.add('hidden');
      }, 4500);
    }

    function uploadSingleFileXHR(file, remotePath, onProgress) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        const formData = new FormData();
        formData.append('file', file);
        formData.append('path', remotePath);

        xhr.upload.addEventListener('progress', (e) => {
          if (e.lengthComputable) {
            const pct = Math.round((e.loaded / e.total) * 100);
            onProgress(pct);
          }
        });

        xhr.addEventListener('load', () => {
          try {
            const res = JSON.parse(xhr.responseText || '{}');
            if (xhr.status >= 200 && xhr.status < 300) {
              resolve(res);
            } else {
              reject(new Error(res.detail || res.error || `HTTP ${xhr.status}`));
            }
          } catch (e) {
            reject(new Error(`HTTP ${xhr.status}`));
          }
        });

        xhr.addEventListener('error', () => reject(new Error('Lỗi kết nối mạng')));
        xhr.open('POST', '/api/upload');
        xhr.setRequestHeader('X-API-Key', state.apiKey);
        xhr.send(formData);
      });
    }

    // --- AUTH MODAL ---
    function openAuthModal() {
      document.getElementById('apiKeyInput').value = state.apiKey;
      const modal = document.getElementById('authModal');
      modal.classList.remove('hidden');
      modal.classList.add('flex');
    }

    function closeAuthModal() {
      const modal = document.getElementById('authModal');
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    function toggleApiKeyVisibility() {
      const input = document.getElementById('apiKeyInput');
      input.type = input.type === 'password' ? 'text' : 'password';
    }

    function saveApiKey() {
      const val = document.getElementById('apiKeyInput').value.trim();
      if (!val) {
        showToast('API Key không được để trống', 'error');
        return;
      }
      state.apiKey = val;
      localStorage.setItem('hf_bucket_api_key', val);
      closeAuthModal();
      showToast('Đã lưu API Key', 'success');
      loadFiles(true);
    }

    // --- GLOBAL DRAG & DROP + SHORTCUTS ---
    window.addEventListener('DOMContentLoaded', () => {
      lucide.createIcons();
      setViewMode(state.viewMode);
      checkHealth();
      loadFiles(false);

      // Search input bindings
      const searchIn = document.getElementById('searchInput');
      const mobileSearchIn = document.getElementById('mobileSearchInput');
      searchIn?.addEventListener('input', (e) => {
        state.search = e.target.value;
        renderExplorer();
      });
      mobileSearchIn?.addEventListener('input', (e) => {
        state.search = e.target.value;
        renderExplorer();
      });

      // Keyboard shortcuts
      window.addEventListener('keydown', (e) => {
        if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
          e.preventDefault();
          searchIn?.focus();
        }
        if (e.key === 'Escape') {
          closeUploadModal();
          closePreviewModal();
          closeAuthModal();
        }
      });

      // Drag and drop on quickDropzone & modalDropzone
      ['quickDropzone', 'modalDropzone'].forEach(id => {
        const zone = document.getElementById(id);
        if (!zone) return;
        zone.addEventListener('dragover', (e) => {
          e.preventDefault();
          zone.classList.add('drop-active');
        });
        zone.addEventListener('dragleave', () => zone.classList.remove('drop-active'));
        zone.addEventListener('drop', (e) => {
          e.preventDefault();
          zone.classList.remove('drop-active');
          if (e.dataTransfer?.files?.length) {
            openUploadModal(e.dataTransfer.files);
          }
        });
      });
    });
  </script>
</body>
</html>