Spaces:
Running

File size: 46,892 Bytes
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
7e79d39
 
 
 
 
 
 
 
5847da6
7e79d39
 
 
 
 
 
5847da6
7e79d39
 
 
5847da6
7e79d39
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
5847da6
 
7e79d39
5847da6
 
 
 
 
 
 
 
 
7e79d39
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
5847da6
 
7e79d39
5847da6
 
7e79d39
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e79d39
 
 
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
'use client';

import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  formatBytes,
  formatDateVi,
  getFileCategory,
  joinPath,
} from '@/shared/lib/format';
import { useToast } from '@/shared/hooks/useToast';
import { Button } from '@/shared/components/Button';
import { Skeleton } from '@/shared/components/Card';
import { Input, Select } from '@/shared/components/Input';
import { ConfirmModal, Modal } from '@/shared/components/Modal';
import { useWorkspaceStore } from '@/features/workspace';
import {
  Archive,
  ChevronRight,
  ClipboardPaste,
  Copy,
  Download,
  Edit2,
  Eye,
  FileCode,
  FilePlus,
  FileText,
  Folder,
  FolderOutput,
  FolderPlus,
  Home,
  Image as ImageIcon,
  LayoutGrid,
  List,
  RefreshCw,
  Scissors,
  Search,
  Trash2,
  Upload,
  X,
} from 'lucide-react';
import { validateEntryName } from '../schemas/fileSchema';
import { fileService } from '../services/fileService';
import { FileItem, FileSortBy, FileViewMode } from '../types/fileTypes';

function isSupportedArchive(name: string): boolean {
  const lower = name.toLowerCase();
  return (
    lower.endsWith('.zip') ||
    lower.endsWith('.tar.gz') ||
    lower.endsWith('.tgz') ||
    lower.endsWith('.tar')
  );
}

function getArchiveStem(name: string): string {
  const lower = name.toLowerCase();
  if (lower.endsWith('.tar.gz')) return name.slice(0, -7) || 'extracted';
  if (lower.endsWith('.tgz')) return name.slice(0, -4) || 'extracted';
  if (lower.endsWith('.zip')) return name.slice(0, -4) || 'extracted';
  if (lower.endsWith('.tar')) return name.slice(0, -4) || 'extracted';
  return `${name}-extracted`;
}

export function FileExplorerView() {
  const { activeZone, openFileInEditor } = useWorkspaceStore();
  const { pushToast } = useToast();

  const [currentPath, setCurrentPath] = useState('');
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [sortBy, setSortBy] = useState<FileSortBy>('name');
  const [viewMode, setViewMode] = useState<FileViewMode>('list');
  const [dragActive, setDragActive] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [downloadingName, setDownloadingName] = useState<string | null>(null);

  // Selection & Clipboard
  const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());
  const [clipboard, setClipboard] = useState<{
    mode: 'copy' | 'move';
    paths: string[];
    zone: string;
  } | null>(null);
  const [pasting, setPasting] = useState(false);

  // Modals
  const [newFileOpen, setNewFileOpen] = useState(false);
  const [newFileName, setNewFileName] = useState('');
  const [newFolderOpen, setNewFolderOpen] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [renameTarget, setRenameTarget] = useState<FileItem | null>(null);
  const [renameValue, setRenameValue] = useState('');
  const [deleteTarget, setDeleteTarget] = useState<FileItem | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
  const [bulkDeleting, setBulkDeleting] = useState(false);

  // Compress & Extract Modals
  const [compressOpen, setCompressOpen] = useState(false);
  const [compressName, setCompressName] = useState('archive.zip');
  const [compressing, setCompressing] = useState(false);
  const [extractTarget, setExtractTarget] = useState<FileItem | null>(null);
  const [extractDestDir, setExtractDestDir] = useState('');
  const [extracting, setExtracting] = useState(false);

  // Quick Preview Modal
  const [previewItem, setPreviewItem] = useState<FileItem | null>(null);
  const [previewText, setPreviewText] = useState('');
  const [previewImageUrl, setPreviewImageUrl] = useState<string | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);

  const loadFiles = useCallback(
    async (targetPath = currentPath) => {
      if (!activeZone) return;
      setLoading(true);
      setSelectedNames(new Set());
      try {
        const list = await fileService.listFiles(activeZone, targetPath);
        setFiles(list || []);
        setCurrentPath(targetPath);
      } catch (err: unknown) {
        pushToast(err instanceof Error ? err.message : 'Không thể tải danh sách tệp', 'error');
      } finally {
        setLoading(false);
      }
    },
    [activeZone, currentPath, pushToast],
  );

  useEffect(() => {
    if (activeZone) {
      setSearch('');
      setClipboard((prev) => (prev && prev.zone === activeZone ? prev : null));
      void loadFiles('');
    }
  }, [activeZone]);

  useEffect(() => {
    return () => {
      if (previewImageUrl) URL.revokeObjectURL(previewImageUrl);
    };
  }, [previewImageUrl]);

  const sortedAndFiltered = useMemo(() => {
    const q = search.trim().toLowerCase();
    const filtered = q ? files.filter((f) => f.name.toLowerCase().includes(q)) : [...files];
    filtered.sort((a, b) => {
      if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
      if (sortBy === 'size') return b.size - a.size;
      if (sortBy === 'modified') return (b.modified || '').localeCompare(a.modified || '');
      return a.name.localeCompare(b.name);
    });
    return filtered;
  }, [files, search, sortBy]);

  const allVisibleSelected =
    sortedAndFiltered.length > 0 &&
    sortedAndFiltered.every((item) => selectedNames.has(item.name));

  const toggleSelectItem = (name: string) => {
    setSelectedNames((prev) => {
      const next = new Set(prev);
      if (next.has(name)) next.delete(name);
      else next.add(name);
      return next;
    });
  };

  const toggleSelectAll = () => {
    if (allVisibleSelected) {
      setSelectedNames(new Set());
    } else {
      setSelectedNames(new Set(sortedAndFiltered.map((item) => item.name)));
    }
  };

  const getSelectedRelPaths = (): string[] =>
    Array.from(selectedNames).map((name) => joinPath(currentPath, name));

  const handleStageClipboard = (mode: 'copy' | 'move') => {
    if (!activeZone || selectedNames.size === 0) return;
    const paths = getSelectedRelPaths();
    setClipboard({ mode, paths, zone: activeZone });
    setSelectedNames(new Set());
    pushToast(
      `Đã lưu ${paths.length} mục vào bộ nhớ tạm (${mode === 'copy' ? 'Sao chép' : 'Di chuyển'}).`,
      'info',
    );
  };

  const handlePasteClipboard = async () => {
    if (!activeZone || !clipboard || clipboard.zone !== activeZone) return;
    setPasting(true);
    try {
      const res = await fileService.transferFiles(
        activeZone,
        clipboard.paths,
        currentPath,
        clipboard.mode,
      );
      pushToast(
        `${clipboard.mode === 'copy' ? 'Đã sao chép' : 'Đã di chuyển'} ${res.processed} mục.`,
        'success',
      );
      if (clipboard.mode === 'move') {
        setClipboard(null);
      }
      await loadFiles(currentPath);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi dán tệp', 'error');
    } finally {
      setPasting(false);
    }
  };

  const handleOpenCompressModal = () => {
    if (selectedNames.size === 0) return;
    const first = Array.from(selectedNames)[0];
    setCompressName(selectedNames.size === 1 ? `${first}.zip` : 'archive.zip');
    setCompressOpen(true);
  };

  const handleCompressSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeZone || selectedNames.size === 0) return;
    const paths = getSelectedRelPaths();
    setCompressing(true);
    try {
      const res = await fileService.compressFiles(
        activeZone,
        paths,
        compressName.trim() || 'archive.zip',
        currentPath,
      );
      setCompressOpen(false);
      setSelectedNames(new Set());
      pushToast(`Đã nén ${res.files_count} tệp thành "${res.path}".`, 'success');
      await loadFiles(currentPath);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi nén tệp', 'error');
    } finally {
      setCompressing(false);
    }
  };

  const handleOpenExtractModal = (item: FileItem) => {
    setExtractTarget(item);
    setExtractDestDir(currentPath);
  };

  const handleExtractSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeZone || !extractTarget) return;
    setExtracting(true);
    try {
      const res = await fileService.extractArchive(
        activeZone,
        joinPath(currentPath, extractTarget.name),
        extractDestDir.trim(),
      );
      setExtractTarget(null);
      pushToast(
        `Đã giải nén ${res.extracted_count} mục vào ${res.dest_dir ? `./${res.dest_dir}` : 'thư mục gốc'}.`,
        'success',
      );
      await loadFiles(currentPath);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi giải nén tệp', 'error');
    } finally {
      setExtracting(false);
    }
  };

  const handleBulkDeleteConfirm = async () => {
    if (!activeZone || selectedNames.size === 0) return;
    setBulkDeleting(true);
    try {
      const res = await fileService.bulkDelete(activeZone, getSelectedRelPaths());
      setBulkDeleteOpen(false);
      setSelectedNames(new Set());
      pushToast(`Đã xoá ${res.deleted} mục.`, 'success');
      await loadFiles(currentPath);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi xoá hàng loạt', 'error');
    } finally {
      setBulkDeleting(false);
    }
  };

  const handleUploadFiles = async (fileList: FileList | File[]) => {
    if (!activeZone || fileList.length === 0) return;
    setUploading(true);
    let okCount = 0;
    for (let i = 0; i < fileList.length; i++) {
      const f = fileList[i];
      try {
        await fileService.uploadFile(activeZone, currentPath, f);
        okCount++;
      } catch (err: unknown) {
        pushToast(
          `Upload ${f.name} lỗi: ${err instanceof Error ? err.message : 'Thất bại'}`,
          'error',
        );
      }
    }
    setUploading(false);
    if (fileInputRef.current) fileInputRef.current.value = '';
    if (okCount > 0) {
      pushToast(`Đã tải lên ${okCount} tệp.`, 'success');
      await loadFiles(currentPath);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      void handleUploadFiles(e.dataTransfer.files);
    }
  };

  const handleCreateFile = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeZone) return;
    const check = validateEntryName(newFileName, 'Tên tệp');
    if (!check.ok || !check.data) {
      pushToast(check.error || 'Tên tệp không hợp lệ', 'error');
      return;
    }
    const target = joinPath(currentPath, check.data);
    try {
      await fileService.writeFile(activeZone, target, '');
      setNewFileOpen(false);
      setNewFileName('');
      pushToast(`Đã tạo tệp ${check.data}`, 'success');
      await loadFiles(currentPath);
      openFileInEditor(target);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi tạo tệp', 'error');
    }
  };

  const handleCreateFolder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeZone) return;
    const check = validateEntryName(newFolderName, 'Tên thư mục');
    if (!check.ok || !check.data) {
      pushToast(check.error || 'Tên thư mục không hợp lệ', 'error');
      return;
    }
    const target = joinPath(currentPath, check.data);
    try {
      await fileService.mkdir(activeZone, target);
      setNewFolderOpen(false);
      setNewFolderName('');
      pushToast(`Đã tạo thư mục ${check.data}`, 'success');
      await loadFiles(currentPath);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi tạo thư mục', 'error');
    }
  };

  const handleRenameSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!activeZone || !renameTarget) return;
    const check = validateEntryName(renameValue, 'Tên mới');
    if (!check.ok || !check.data) {
      pushToast(check.error || 'Tên mới không hợp lệ', 'error');
      return;
    }
    const oldPath = joinPath(currentPath, renameTarget.name);
    try {
      await fileService.renameFile(activeZone, oldPath, check.data);
      setRenameTarget(null);
      setRenameValue('');
      pushToast('Đã đổi tên thành công.', 'success');
      await loadFiles(currentPath);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi đổi tên', 'error');
    }
  };

  const handleDeleteConfirm = async () => {
    if (!activeZone || !deleteTarget) return;
    setDeleting(true);
    try {
      await fileService.deleteFile(activeZone, joinPath(currentPath, deleteTarget.name));
      pushToast(`Đã xoá ${deleteTarget.name}`, 'success');
      setDeleteTarget(null);
      await loadFiles(currentPath);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi xoá tệp', 'error');
    } finally {
      setDeleting(false);
    }
  };

  const handleDownload = async (item: FileItem) => {
    if (!activeZone) return;
    setDownloadingName(item.name);
    try {
      const blob = await fileService.downloadBlob(activeZone, joinPath(currentPath, item.name));
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = item.is_dir ? `${item.name}.zip` : item.name;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (err: unknown) {
      pushToast(err instanceof Error ? err.message : 'Lỗi tải xuống', 'error');
    } finally {
      setDownloadingName(null);
    }
  };

  const handleCopyPath = async (item: FileItem) => {
    const full = joinPath(currentPath, item.name);
    try {
      await navigator.clipboard.writeText(full);
      pushToast(`Đã sao chép: ${full}`, 'info');
    } catch {
      pushToast('Không thể sao chép vào clipboard', 'error');
    }
  };

  const handleQuickPreview = async (item: FileItem) => {
    if (!activeZone || item.is_dir) return;
    const cat = getFileCategory(item.name, false);
    const fullPath = joinPath(currentPath, item.name);
    if (previewImageUrl) {
      URL.revokeObjectURL(previewImageUrl);
      setPreviewImageUrl(null);
    }
    setPreviewText('');
    setPreviewItem(item);
    setPreviewLoading(true);
    try {
      if (cat === 'image') {
        const blob = await fileService.downloadBlob(activeZone, fullPath);
        setPreviewImageUrl(URL.createObjectURL(blob));
      } else {
        const res = await fileService.readFile(activeZone, fullPath);
        setPreviewText((res.content || '').slice(0, 12000));
      }
    } catch (err: unknown) {
      setPreviewText(err instanceof Error ? err.message : 'Không thể xem trước tệp này.');
    } finally {
      setPreviewLoading(false);
    }
  };

  const renderIcon = (item: FileItem) => {
    const cat = getFileCategory(item.name, item.is_dir);
    if (cat === 'dir') return <Folder className="w-4 h-4 text-amber-500 flex-shrink-0" aria-hidden="true" />;
    if (cat === 'image') return <ImageIcon className="w-4 h-4 text-emerald-500 flex-shrink-0" aria-hidden="true" />;
    if (cat === 'code') return <FileCode className="w-4 h-4 text-accent flex-shrink-0" aria-hidden="true" />;
    if (cat === 'archive') return <Archive className="w-4 h-4 text-sky-500 flex-shrink-0" aria-hidden="true" />;
    return <FileText className="w-4 h-4 text-ink-2 flex-shrink-0" aria-hidden="true" />;
  };

  const handleOpenItem = (item: FileItem) => {
    const target = joinPath(currentPath, item.name);
    if (item.is_dir) {
      void loadFiles(target);
      return;
    }
    const cat = getFileCategory(item.name, false);
    if (cat === 'image') void handleQuickPreview(item);
    else openFileInEditor(target);
  };

  const pathSegments = currentPath ? currentPath.split('/').filter(Boolean) : [];

  return (
    <div
      onDragOver={(e) => {
        e.preventDefault();
        setDragActive(true);
      }}
      onDragLeave={(e) => {
        if (!e.currentTarget.contains(e.relatedTarget as Node)) setDragActive(false);
      }}
      onDrop={handleDrop}
      className="relative flex-1 flex flex-col h-full bg-canvas overflow-hidden"
    >
      {dragActive && (
        <div className="absolute inset-3 z-40 rounded-2xl border-2 border-dashed border-accent bg-accent/10 backdrop-blur-sm flex flex-col items-center justify-center gap-2 pointer-events-none">
          <Upload className="w-8 h-8 text-accent" aria-hidden="true" />
          <p className="text-sm font-bold text-ink-1">
            Thả tệp vào đây để tải lên /{currentPath}
          </p>
        </div>
      )}

      {/* Action & Breadcrumb Header */}
      <div className="border-b border-line px-4 sm:px-6 py-2.5 bg-surface-1/70 flex flex-col gap-2.5 flex-shrink-0">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <nav aria-label="Đường dẫn thư mục" className="flex items-center gap-1 text-xs overflow-x-auto">
            <button
              type="button"
              onClick={() => void loadFiles('')}
              className={`inline-flex items-center gap-1.5 px-2.5 py-1 min-h-[34px] rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
                currentPath === ''
                  ? 'bg-accent/10 text-accent font-semibold'
                  : 'text-ink-2 hover:bg-surface-2'
              }`}
            >
              <Home className="w-3.5 h-3.5" aria-hidden="true" />
              <span className="font-mono">{activeZone}</span>
            </button>
            {pathSegments.map((seg, idx) => {
              const target = pathSegments.slice(0, idx + 1).join('/');
              const isLast = idx === pathSegments.length - 1;
              return (
                <React.Fragment key={target}>
                  <ChevronRight className="w-3.5 h-3.5 text-ink-3 flex-shrink-0" aria-hidden="true" />
                  <button
                    type="button"
                    onClick={() => void loadFiles(target)}
                    className={`px-2 py-1 min-h-[34px] rounded-lg font-mono focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
                      isLast
                        ? 'bg-surface-2 text-ink-1 font-semibold'
                        : 'text-ink-2 hover:bg-surface-2'
                    }`}
                  >
                    {seg}
                  </button>
                </React.Fragment>
              );
            })}
          </nav>

          <div className="flex flex-wrap items-center gap-1.5">
            <input
              ref={fileInputRef}
              type="file"
              multiple
              onChange={(e) => e.target.files && void handleUploadFiles(e.target.files)}
              className="hidden"
              aria-label="Chọn tệp để tải lên"
            />
            <Button size="sm" variant="secondary" onClick={() => setNewFileOpen(true)}>
              <FilePlus className="w-3.5 h-3.5" aria-hidden="true" />
              <span className="hidden sm:inline">Tạo File</span>
            </Button>
            <Button size="sm" variant="secondary" onClick={() => setNewFolderOpen(true)}>
              <FolderPlus className="w-3.5 h-3.5" aria-hidden="true" />
              <span className="hidden sm:inline">Thư mục</span>
            </Button>
            <Button
              size="sm"
              variant="primary"
              loading={uploading}
              onClick={() => fileInputRef.current?.click()}
            >
              <Upload className="w-3.5 h-3.5" aria-hidden="true" />
              <span>{uploading ? 'Đang tải...' : 'Upload'}</span>
            </Button>
            <button
              type="button"
              onClick={() => void loadFiles(currentPath)}
              aria-label="Làm mới danh sách tệp"
              className="p-2 min-h-[36px] min-w-[36px] flex items-center justify-center rounded-lg border border-line bg-surface-2 hover:bg-surface-3 text-ink-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
            >
              <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} aria-hidden="true" />
            </button>
          </div>
        </div>

        {/* Search, Sort & View Controls */}
        <div className="flex flex-wrap items-center gap-2">
          <div className="flex-1 min-w-[180px]">
            <Input
              aria-label="Lọc tệp trong thư mục"
              placeholder="Tìm nhanh theo tên tệp hoặc thư mục..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              leftIcon={<Search className="w-3.5 h-3.5" />}
              className="min-h-[36px] text-xs"
            />
          </div>
          <div className="w-36">
            <Select
              aria-label="Sắp xếp theo"
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as FileSortBy)}
              className="min-h-[36px] py-1 text-xs"
            >
              <option value="name">Tên (A → Z)</option>
              <option value="size">Kích thước</option>
              <option value="modified">Ngày sửa</option>
            </Select>
          </div>
          <div className="flex items-center bg-surface-2 border border-line rounded-lg p-0.5">
            <button
              type="button"
              onClick={() => setViewMode('list')}
              aria-label="Chế độ danh sách"
              aria-pressed={viewMode === 'list'}
              className={`p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
                viewMode === 'list' ? 'bg-accent text-on-accent' : 'text-ink-2 hover:text-ink-1'
              }`}
            >
              <List className="w-3.5 h-3.5" aria-hidden="true" />
            </button>
            <button
              type="button"
              onClick={() => setViewMode('grid')}
              aria-label="Chế độ lưới"
              aria-pressed={viewMode === 'grid'}
              className={`p-1.5 min-h-[32px] min-w-[32px] flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent ${
                viewMode === 'grid' ? 'bg-accent text-on-accent' : 'text-ink-2 hover:text-ink-1'
              }`}
            >
              <LayoutGrid className="w-3.5 h-3.5" aria-hidden="true" />
            </button>
          </div>
        </div>

        {/* Bulk Selection & Clipboard Bar */}
        {(selectedNames.size > 0 || (clipboard && clipboard.zone === activeZone)) && (
          <div className="flex flex-wrap items-center justify-between gap-2 pt-1 border-t border-line/70">
            <div className="flex flex-wrap items-center gap-1.5">
              {selectedNames.size > 0 ? (
                <>
                  <span className="text-xs font-mono font-semibold text-accent px-2 py-1 rounded-md bg-accent/10 border border-accent/30">
                    Đã chọn {selectedNames.size} mục
                  </span>
                  <Button
                    size="sm"
                    variant="secondary"
                    onClick={() => handleStageClipboard('copy')}
                  >
                    <Copy className="w-3.5 h-3.5" aria-hidden="true" />
                    <span>Sao chép</span>
                  </Button>
                  <Button
                    size="sm"
                    variant="secondary"
                    onClick={() => handleStageClipboard('move')}
                  >
                    <Scissors className="w-3.5 h-3.5" aria-hidden="true" />
                    <span>Di chuyển</span>
                  </Button>
                  <Button
                    size="sm"
                    variant="secondary"
                    onClick={handleOpenCompressModal}
                  >
                    <Archive className="w-3.5 h-3.5" aria-hidden="true" />
                    <span>Nén ZIP</span>
                  </Button>
                  <Button
                    size="sm"
                    variant="danger"
                    onClick={() => setBulkDeleteOpen(true)}
                  >
                    <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                    <span>Xoá ({selectedNames.size})</span>
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={() => setSelectedNames(new Set())}
                  >
                    <X className="w-3.5 h-3.5" aria-hidden="true" />
                    <span>Bỏ chọn</span>
                  </Button>
                </>
              ) : (
                <button
                  type="button"
                  onClick={toggleSelectAll}
                  className="text-xs font-medium text-ink-2 hover:text-ink-1 px-2 py-1 rounded-lg hover:bg-surface-2"
                >
                  {allVisibleSelected ? 'Bỏ chọn tất cả' : 'Chọn tất cả'}
                </button>
              )}
            </div>

            {clipboard && clipboard.zone === activeZone && (
              <div className="flex flex-wrap items-center gap-1.5">
                <span className="text-xs text-ink-2 font-mono">
                  Clipboard ({clipboard.mode === 'copy' ? 'Copy' : 'Move'}: {clipboard.paths.length} mục)
                </span>
                <Button
                  size="sm"
                  variant="primary"
                  loading={pasting}
                  onClick={() => void handlePasteClipboard()}
                >
                  <ClipboardPaste className="w-3.5 h-3.5" aria-hidden="true" />
                  <span>Dán vào /{currentPath}</span>
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => setClipboard(null)}
                >
                  <X className="w-3.5 h-3.5" aria-hidden="true" />
                  <span>Huỷ</span>
                </Button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Directory Content */}
      <div className="flex-1 overflow-y-auto p-4 sm:p-6">
        {loading ? (
          <div className="space-y-2">
            <Skeleton className="h-11 w-full" />
            <Skeleton className="h-11 w-full" />
            <Skeleton className="h-11 w-full" />
            <Skeleton className="h-11 w-full" />
          </div>
        ) : sortedAndFiltered.length === 0 ? (
          <div className="rounded-2xl border border-dashed border-line bg-surface-1/50 p-12 text-center space-y-2">
            <Folder className="w-10 h-10 mx-auto text-ink-3" aria-hidden="true" />
            <p className="text-xs sm:text-sm font-medium text-ink-2">
              {search ? 'Không tìm thấy tệp phù hợp.' : 'Thư mục trống. Kéo-thả tệp vào đây hoặc bấm Upload.'}
            </p>
          </div>
        ) : viewMode === 'grid' ? (
          <div className="space-y-3">
            <div className="flex items-center justify-between text-xs text-ink-3">
              <label className="inline-flex items-center gap-2 cursor-pointer text-ink-2">
                <input
                  type="checkbox"
                  checked={allVisibleSelected}
                  onChange={toggleSelectAll}
                  className="rounded border-line-strong text-accent focus:ring-accent"
                />
                <span>Chọn tất cả ({sortedAndFiltered.length})</span>
              </label>
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
              {sortedAndFiltered.map((item) => {
                const selected = selectedNames.has(item.name);
                const archiveItem = !item.is_dir && isSupportedArchive(item.name);
                return (
                  <div
                    key={item.name}
                    className={`group relative rounded-xl border p-3 flex flex-col justify-between gap-3 transition-colors ${
                      selected
                        ? 'border-accent bg-accent/10'
                        : 'border-line bg-surface-1 hover:border-accent/50'
                    }`}
                  >
                    <input
                      type="checkbox"
                      checked={selected}
                      onChange={() => toggleSelectItem(item.name)}
                      aria-label={`Chọn ${item.name}`}
                      className="absolute top-2.5 right-2.5 rounded border-line-strong text-accent focus:ring-accent cursor-pointer"
                    />
                    <button
                      type="button"
                      onClick={() => handleOpenItem(item)}
                      className="text-left space-y-2 pr-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded-lg"
                    >
                      <div className="w-9 h-9 rounded-lg bg-surface-2 flex items-center justify-center">
                        {renderIcon(item)}
                      </div>
                      <div className="font-mono text-xs font-semibold text-ink-1 truncate">
                        {item.name}
                      </div>
                      <div className="text-[11px] font-mono tabular-nums text-ink-3">
                        {item.is_dir ? 'Thư mục' : formatBytes(item.size)}
                      </div>
                    </button>
                    <div className="flex items-center justify-end gap-1 pt-1 border-t border-line/60">
                      {archiveItem && (
                        <button
                          type="button"
                          onClick={() => handleOpenExtractModal(item)}
                          aria-label={`Giải nén ${item.name}`}
                          title="Giải nén"
                          className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-sky-500 hover:bg-surface-2"
                        >
                          <FolderOutput className="w-3.5 h-3.5" aria-hidden="true" />
                        </button>
                      )}
                      {!item.is_dir && (
                        <button
                          type="button"
                          onClick={() => void handleQuickPreview(item)}
                          aria-label={`Xem nhanh ${item.name}`}
                          className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-accent hover:bg-surface-2"
                        >
                          <Eye className="w-3.5 h-3.5" aria-hidden="true" />
                        </button>
                      )}
                      <button
                        type="button"
                        onClick={() => void handleDownload(item)}
                        aria-label={`Tải ${item.name}`}
                        className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-ink-1 hover:bg-surface-2"
                      >
                        <Download className="w-3.5 h-3.5" aria-hidden="true" />
                      </button>
                      <button
                        type="button"
                        onClick={() => setDeleteTarget(item)}
                        aria-label={`Xoá ${item.name}`}
                        className="p-1.5 min-h-[30px] min-w-[30px] rounded-md text-ink-3 hover:text-rose-500 hover:bg-rose-500/10"
                      >
                        <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ) : (
          <div className="rounded-2xl border border-line bg-surface-1 overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-line bg-surface-2/60 text-[11px] font-mono uppercase tracking-wider text-ink-3">
                  <th className="pl-4 pr-2 py-2.5 w-8">
                    <input
                      type="checkbox"
                      checked={allVisibleSelected}
                      onChange={toggleSelectAll}
                      aria-label="Chọn tất cả tệp"
                      className="rounded border-line-strong text-accent focus:ring-accent cursor-pointer"
                    />
                  </th>
                  <th className="px-3 py-2.5">Tên</th>
                  <th className="px-4 py-2.5 hidden sm:table-cell">Kích thước</th>
                  <th className="px-4 py-2.5 hidden md:table-cell">Cập nhật</th>
                  <th className="px-4 py-2.5 text-right">Thao tác</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line text-xs">
                {sortedAndFiltered.map((item) => {
                  const selected = selectedNames.has(item.name);
                  const archiveItem = !item.is_dir && isSupportedArchive(item.name);
                  return (
                    <tr
                      key={item.name}
                      className={selected ? 'bg-accent/10' : 'hover:bg-surface-2/60'}
                    >
                      <td className="pl-4 pr-2 py-2.5">
                        <input
                          type="checkbox"
                          checked={selected}
                          onChange={() => toggleSelectItem(item.name)}
                          aria-label={`Chọn ${item.name}`}
                          className="rounded border-line-strong text-accent focus:ring-accent cursor-pointer"
                        />
                      </td>
                      <td className="px-3 py-2.5">
                        <button
                          type="button"
                          onClick={() => handleOpenItem(item)}
                          className="flex items-center gap-2.5 min-h-[34px] text-left font-mono font-medium text-ink-1 hover:text-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded"
                        >
                          {renderIcon(item)}
                          <span className="truncate max-w-[200px] sm:max-w-md">{item.name}</span>
                        </button>
                      </td>
                      <td className="px-4 py-2.5 font-mono tabular-nums text-ink-2 hidden sm:table-cell">
                        {item.is_dir ? '—' : formatBytes(item.size)}
                      </td>
                      <td className="px-4 py-2.5 font-mono tabular-nums text-ink-3 hidden md:table-cell">
                        {formatDateVi(item.modified)}
                      </td>
                      <td className="px-4 py-2.5">
                        <div className="flex items-center justify-end gap-1">
                          {archiveItem && (
                            <button
                              type="button"
                              onClick={() => handleOpenExtractModal(item)}
                              aria-label={`Giải nén ${item.name}`}
                              title="Giải nén"
                              className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-sky-500 hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
                            >
                              <FolderOutput className="w-3.5 h-3.5" aria-hidden="true" />
                            </button>
                          )}
                          {!item.is_dir && (
                            <button
                              type="button"
                              onClick={() => void handleQuickPreview(item)}
                              aria-label={`Xem nhanh ${item.name}`}
                              className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-accent hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
                            >
                              <Eye className="w-3.5 h-3.5" aria-hidden="true" />
                            </button>
                          )}
                          <button
                            type="button"
                            onClick={() => void handleCopyPath(item)}
                            aria-label={`Sao chép đường dẫn ${item.name}`}
                            className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
                          >
                            <Copy className="w-3.5 h-3.5" aria-hidden="true" />
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              setRenameTarget(item);
                              setRenameValue(item.name);
                            }}
                            aria-label={`Đổi tên ${item.name}`}
                            className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
                          >
                            <Edit2 className="w-3.5 h-3.5" aria-hidden="true" />
                          </button>
                          <button
                            type="button"
                            onClick={() => void handleDownload(item)}
                            disabled={downloadingName === item.name}
                            aria-label={`Tải xuống ${item.name}`}
                            className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-ink-1 hover:bg-surface-3 disabled:opacity-40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
                          >
                            <Download className="w-3.5 h-3.5" aria-hidden="true" />
                          </button>
                          <button
                            type="button"
                            onClick={() => setDeleteTarget(item)}
                            aria-label={`Xoá ${item.name}`}
                            className="p-1.5 min-h-[34px] min-w-[34px] flex items-center justify-center rounded-lg text-ink-3 hover:text-rose-500 hover:bg-rose-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
                          >
                            <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Create File Modal */}
      <Modal open={newFileOpen} onClose={() => setNewFileOpen(false)} title="Tạo tệp mới">
        <form onSubmit={handleCreateFile} className="space-y-4">
          <Input
            label="Tên tệp"
            required
            autoFocus
            value={newFileName}
            onChange={(e) => setNewFileName(e.target.value)}
            placeholder="vd: server.js, .env, main.py"
          />
          <div className="flex justify-end gap-2">
            <Button variant="secondary" size="sm" onClick={() => setNewFileOpen(false)}>
              Huỷ
            </Button>
            <Button type="submit" size="sm">
              Tạo &amp; Mở Editor
            </Button>
          </div>
        </form>
      </Modal>

      {/* Create Folder Modal */}
      <Modal open={newFolderOpen} onClose={() => setNewFolderOpen(false)} title="Tạo thư mục mới">
        <form onSubmit={handleCreateFolder} className="space-y-4">
          <Input
            label="Tên thư mục"
            required
            autoFocus
            value={newFolderName}
            onChange={(e) => setNewFolderName(e.target.value)}
            placeholder="vd: src, config, logs"
          />
          <div className="flex justify-end gap-2">
            <Button variant="secondary" size="sm" onClick={() => setNewFolderOpen(false)}>
              Huỷ
            </Button>
            <Button type="submit" size="sm">
              Tạo thư mục
            </Button>
          </div>
        </form>
      </Modal>

      {/* Rename Modal */}
      <Modal
        open={Boolean(renameTarget)}
        onClose={() => setRenameTarget(null)}
        title={`Đổi tên: ${renameTarget?.name || ''}`}
      >
        <form onSubmit={handleRenameSubmit} className="space-y-4">
          <Input
            label="Tên mới"
            required
            autoFocus
            value={renameValue}
            onChange={(e) => setRenameValue(e.target.value)}
          />
          <div className="flex justify-end gap-2">
            <Button variant="secondary" size="sm" onClick={() => setRenameTarget(null)}>
              Huỷ
            </Button>
            <Button type="submit" size="sm">
              Lưu tên mới
            </Button>
          </div>
        </form>
      </Modal>

      {/* Quick Preview Modal */}
      <Modal
        open={Boolean(previewItem)}
        onClose={() => setPreviewItem(null)}
        title={`Xem nhanh: ${previewItem?.name || ''}`}
        maxWidthClass="max-w-2xl"
      >
        {previewLoading ? (
          <div className="space-y-2">
            <Skeleton className="h-48 w-full" />
          </div>
        ) : previewImageUrl ? (
          <div className="flex flex-col items-center gap-3">
            <img
              src={previewImageUrl}
              alt={previewItem?.name || 'Ảnh xem trước'}
              className="max-h-[60vh] rounded-xl border border-line object-contain bg-surface-2"
            />
          </div>
        ) : (
          <div className="space-y-3">
            <pre className="p-4 rounded-xl bg-surface-2 border border-line text-xs font-mono text-ink-1 overflow-auto max-h-[55vh] whitespace-pre-wrap break-words">
              {previewText || '(Tệp trống)'}
            </pre>
            {previewItem && (
              <div className="flex justify-end">
                <Button
                  size="sm"
                  onClick={() => {
                    const target = joinPath(currentPath, previewItem.name);
                    setPreviewItem(null);
                    openFileInEditor(target);
                  }}
                >
                  Mở trong Editor
                </Button>
              </div>
            )}
          </div>
        )}
      </Modal>

      <ConfirmModal
        open={Boolean(deleteTarget)}
        onClose={() => setDeleteTarget(null)}
        onConfirm={handleDeleteConfirm}
        title="Xoá mục đã chọn"
        description={`Bạn có chắc muốn xoá ${deleteTarget?.is_dir ? 'thư mục' : 'tệp'} "${deleteTarget?.name}"?`}
        confirmLabel="Xoá"
        danger
        loading={deleting}
      />

      {/* Compress Modal */}
      <Modal
        open={compressOpen}
        onClose={() => setCompressOpen(false)}
        title={`Nén ${selectedNames.size} mục thành ZIP`}
      >
        <form onSubmit={handleCompressSubmit} className="space-y-4">
          <Input
            label="Tên file ZIP đầu ra"
            required
            autoFocus
            value={compressName}
            onChange={(e) => setCompressName(e.target.value)}
            placeholder="archive.zip"
            helperText={`Sẽ lưu tại /${currentPath}`}
            className="font-mono"
          />
          <div className="flex justify-end gap-2">
            <Button variant="secondary" size="sm" onClick={() => setCompressOpen(false)}>
              Huỷ
            </Button>
            <Button type="submit" size="sm" loading={compressing}>
              Nén ngay
            </Button>
          </div>
        </form>
      </Modal>

      {/* Extract Archive Modal */}
      <Modal
        open={Boolean(extractTarget)}
        onClose={() => setExtractTarget(null)}
        title={`Giải nén: ${extractTarget?.name || ''}`}
      >
        <form onSubmit={handleExtractSubmit} className="space-y-4">
          <Input
            label="Thư mục đích trong Zone (để trống = thư mục gốc Zone)"
            autoFocus
            value={extractDestDir}
            onChange={(e) => setExtractDestDir(e.target.value)}
            placeholder="vd: dist, app/public"
            className="font-mono"
          />
          {extractTarget && (
            <button
              type="button"
              onClick={() =>
                setExtractDestDir(joinPath(currentPath, getArchiveStem(extractTarget.name)))
              }
              className="text-xs font-mono text-accent hover:underline"
            >
              + Giải nén vào thư mục con ./{joinPath(currentPath, getArchiveStem(extractTarget.name))}
            </button>
          )}
          <div className="flex justify-end gap-2">
            <Button variant="secondary" size="sm" onClick={() => setExtractTarget(null)}>
              Huỷ
            </Button>
            <Button type="submit" size="sm" loading={extracting}>
              Giải nén ngay
            </Button>
          </div>
        </form>
      </Modal>

      {/* Bulk Delete Confirmation */}
      <ConfirmModal
        open={bulkDeleteOpen}
        onClose={() => setBulkDeleteOpen(false)}
        onConfirm={handleBulkDeleteConfirm}
        title="Xoá hàng loạt"
        description={`Bạn có chắc muốn xoá vĩnh viễn ${selectedNames.size} mục đang chọn?`}
        confirmLabel={`Xoá ${selectedNames.size} mục`}
        danger
        loading={bulkDeleting}
      />
    </div>
  );
}