File size: 35,972 Bytes
8af739b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
734142c
7f20600
 
 
 
 
 
 
 
 
2a1df12
467789d
66097e1
 
7f6d612
 
8af739b
66097e1
8af739b
734142c
8af739b
 
 
 
 
ad31128
 
a1cccea
 
734142c
7f20600
72674e4
8af739b
 
 
 
734142c
8af739b
 
 
 
734142c
 
 
8af739b
 
95df94d
8af739b
66097e1
8af739b
 
 
66097e1
7f6d612
8af739b
66097e1
 
 
 
7f20600
95df94d
 
 
 
 
 
 
 
 
 
 
 
66097e1
 
7f20600
66097e1
7f20600
66097e1
7f20600
 
 
66097e1
 
bc139ec
66097e1
 
 
 
 
 
 
 
 
 
 
bc139ec
66097e1
8af739b
 
 
 
 
66097e1
8af739b
 
66097e1
 
8af739b
66097e1
 
8af739b
 
 
 
bc139ec
 
 
66097e1
 
 
 
bc139ec
 
 
56c692f
 
 
 
 
 
8af739b
 
 
 
 
 
 
 
66097e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af739b
 
 
 
 
 
66097e1
8af739b
 
66097e1
8af739b
 
 
 
66097e1
8af739b
66097e1
 
8af739b
 
 
66097e1
 
 
8af739b
 
 
 
66097e1
8af739b
 
 
 
 
 
 
 
 
 
 
66097e1
ff732bb
66097e1
ff732bb
75d362b
8af739b
 
 
 
 
 
 
 
 
 
66097e1
 
 
 
 
 
 
 
 
 
 
bc139ec
8af739b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66097e1
 
 
 
 
8af739b
 
 
 
 
66097e1
8af739b
7f20600
8af739b
 
734142c
 
 
 
8af739b
 
66097e1
8af739b
66097e1
8af739b
66097e1
c6c4e58
 
8af739b
 
 
66097e1
 
8af739b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f20600
 
 
 
66097e1
7f20600
66097e1
 
 
7f20600
 
 
 
 
 
2a1df12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467789d
 
 
 
 
 
 
 
7f20600
 
8af739b
 
734142c
 
66097e1
734142c
 
ad31128
 
a1cccea
 
7f20600
 
734142c
 
 
8af739b
7f6d612
 
 
 
 
 
 
 
 
 
 
 
 
 
7f20600
7f6d612
 
 
 
 
 
7f20600
7f6d612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af739b
7f20600
7f6d612
7f20600
7f6d612
 
 
 
 
 
 
 
7f20600
 
 
 
 
 
7f6d612
7f20600
7f6d612
7f20600
7f6d612
66097e1
7f20600
734142c
7f20600
7f6d612
66097e1
 
 
7f6d612
66097e1
7f6d612
 
66097e1
 
 
7f20600
7f6d612
 
 
 
 
 
 
7f20600
7f6d612
 
7f20600
 
 
 
 
7f6d612
7f20600
 
734142c
7f20600
 
 
7f6d612
7f20600
7f6d612
7f20600
734142c
7f20600
 
7f6d612
734142c
7f6d612
7f20600
734142c
7f6d612
734142c
7f20600
 
 
 
66097e1
7f20600
 
 
66097e1
7f6d612
7f20600
 
 
7f6d612
66097e1
7f20600
 
 
734142c
7f20600
c52a01c
7f20600
 
 
 
75d362b
c52a01c
 
 
 
dbde139
c52a01c
 
 
5de3541
 
 
 
dbde139
 
 
 
 
 
 
 
 
c52a01c
72674e4
dbde139
72674e4
c52a01c
 
 
 
dbde139
 
 
 
c52a01c
 
 
 
dbde139
c52a01c
95df94d
 
de1a703
 
 
d596ecb
de1a703
 
 
95df94d
 
d596ecb
 
95df94d
d596ecb
 
 
95df94d
de1a703
 
d596ecb
 
95df94d
 
 
 
 
 
d596ecb
95df94d
de1a703
 
 
95df94d
de1a703
7f20600
 
 
 
7f6d612
7f20600
7f6d612
7f20600
 
7f6d612
7f20600
 
 
7f6d612
7f20600
 
 
 
 
 
7f6d612
7f20600
 
 
 
 
7f6d612
7f20600
 
7f6d612
7f20600
 
 
 
 
 
7f6d612
7f20600
 
7f6d612
7f20600
 
 
 
 
 
 
 
 
 
8af739b
7f20600
7f6d612
7f20600
 
66097e1
7f20600
 
66097e1
 
 
 
 
 
 
 
7f6d612
66097e1
 
 
 
7f6d612
66097e1
7f6d612
 
66097e1
7f6d612
 
66097e1
 
 
 
 
 
 
7f6d612
66097e1
 
 
7f6d612
66097e1
 
 
 
 
 
7f6d612
66097e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
734142c
8af739b
734142c
8af739b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c52a01c
 
8af739b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f20600
 
 
8af739b
 
 
7f20600
8af739b
 
 
7f20600
8af739b
 
 
 
7f20600
8af739b
 
 
 
 
7f20600
8af739b
7f20600
8af739b
 
 
 
7f20600
8af739b
 
7f20600
8af739b
 
 
 
 
 
7f20600
8af739b
 
 
 
 
 
 
 
 
 
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
'use client'

import React, { useState, useEffect } from 'react'
import {
  X,
  Minus,
  Square,
  CaretLeft,
  CaretRight,
  House,
  MagnifyingGlass,
  Folder as FolderIcon,
  File,
  Image as ImageIcon,
  FilePdf,
  FileDoc,
  FileText,
  Upload,
  Download,
  Trash,
  Plus,
  Eye,
  Users,
  Globe,
  Code,
  AppWindow,
  Desktop,
  DownloadSimple,
  Flask,
  DeviceMobile,
  Function,
  Calendar as CalendarIcon,
  Clock as ClockIcon,
  Sparkle,
  Lightning,
  Brain,
  Lock,
  Key,
  List
} from '@phosphor-icons/react'
import { motion, AnimatePresence } from 'framer-motion'
import { FilePreview } from './FilePreview'
import Window from './Window'

interface FileManagerProps {
  currentPath: string
  onNavigate: (path: string) => void
  onClose: () => void
  onMinimize?: () => void
  onMaximize?: () => void
  onFocus?: () => void
  zIndex?: number
  onOpenFlutterApp?: (appFile: any) => void
  onOpenApp?: (appId: string) => void
  onOpenTextFile?: (fileData: { content: string, fileName: string, filePath: string, passkey: string }) => void
}

interface FileItem {
  name: string
  type: 'folder' | 'file' | 'flutter_app'
  size?: number
  modified?: string
  path: string
  extension?: string
  dartCode?: string
  dependencies?: string[]
  pubspecYaml?: string
}

export function FileManager({ currentPath, onNavigate, onClose, onOpenFlutterApp, onMinimize, onMaximize, onFocus, zIndex, onOpenApp, onOpenTextFile }: FileManagerProps) {
  const [files, setFiles] = useState<FileItem[]>([])
  const [loading, setLoading] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [uploadModalOpen, setUploadModalOpen] = useState(false)
  const [previewFile, setPreviewFile] = useState<FileItem | null>(null)
  const [sidebarSelection, setSidebarSelection] = useState('public') // Default to public
  const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)

  // Secure Data State
  const [passkey, setPasskey] = useState('')
  const [showPasskeyModal, setShowPasskeyModal] = useState(false)
  const [tempPasskey, setTempPasskey] = useState('')

  // Helper function to check if a file can be edited as text
  const isTextFile = (extension: string): boolean => {
    const textExtensions = [
      'txt', 'md', 'tex', 'json', 'xml', 'html', 'htm', 'css', 'scss', 'sass',
      'js', 'jsx', 'ts', 'tsx', 'py', 'java', 'c', 'cpp', 'h', 'hpp',
      'sh', 'bash', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf',
      'sql', 'php', 'rb', 'go', 'rs', 'swift', 'kt', 'scala',
      'r', 'dart', 'vue', 'svelte', 'astro', 'csv', 'log'
    ]
    return textExtensions.includes(extension.toLowerCase())
  }

  // Load files when path or selection changes
  useEffect(() => {
    if (currentPath === 'Applications') {
      setSidebarSelection('applications')
      setLoading(false)
      setFiles([])
      return
    }

    if (currentPath === 'public' || currentPath.startsWith('public/')) {
      setSidebarSelection('public')
      loadFiles()
    } else if (sidebarSelection === 'secure') {
      if (passkey) {
        loadFiles()
      } else {
        setFiles([])
        setShowPasskeyModal(true)
      }
    } else {
      // Default to public if nothing else matches
      setSidebarSelection('public')
      onNavigate('public')
    }
  }, [currentPath, sidebarSelection, passkey])

  const loadFiles = async () => {
    setLoading(true)
    try {
      let response
      if (sidebarSelection === 'public' || currentPath.startsWith('public')) {
        const publicPath = currentPath === 'public' ? '' : currentPath.replace('public/', '')
        response = await fetch(`/api/public?folder=${encodeURIComponent(publicPath)}`)
      } else if (sidebarSelection === 'secure' && passkey) {
        response = await fetch(`/api/data?key=${encodeURIComponent(passkey)}&folder=${encodeURIComponent(currentPath)}`)
      } else {
        setLoading(false)
        return
      }

      const data = await response.json()

      if (data.error) {
        console.error('Error loading files:', data.error)
        setFiles([])
        if (data.error === 'Invalid passkey' || data.error === 'Access denied') {
          setPasskey('')
          setShowPasskeyModal(true)
        }
        return
      }

      let normalizedFiles = (data.files || []).map((file: any) => ({
        ...file,
        path: file.path || file.name || '',
      }))

      setFiles(normalizedFiles)
    } catch (error) {
      console.error('Error loading files:', error)
      setFiles([])
    } finally {
      setLoading(false)
    }
  }

  const handlePasskeySubmit = () => {
    if (tempPasskey.trim()) {
      setPasskey(tempPasskey.trim())
      setShowPasskeyModal(false)
      setTempPasskey('')
      onNavigate('') // Reset to root of secure drive
    }
  }

  const handleLock = () => {
    setPasskey('')
    setFiles([])
    setShowPasskeyModal(true)
  }

  const handleUpload = async (file: File, targetFolder: string) => {
    const formData = new FormData()
    formData.append('file', file)

    try {
      let response
      if (sidebarSelection === 'public') {
        const publicPath = currentPath === 'public' ? '' : currentPath.replace('public/', '')
        formData.append('folder', publicPath)
        formData.append('uploadedBy', 'User')
        response = await fetch('/api/public', {
          method: 'POST',
          body: formData
        })
      } else if (sidebarSelection === 'secure' && passkey) {
        formData.append('folder', targetFolder)
        formData.append('key', passkey)
        response = await fetch('/api/data', {
          method: 'POST',
          body: formData
        })
      } else {
        alert('Cannot upload here')
        return
      }

      const result = await response.json()
      if (result.success) {
        loadFiles()
        setUploadModalOpen(false)
      } else {
        alert(`Upload failed: ${result.error}`)
      }
    } catch (error) {
      console.error('Error uploading file:', error)
      alert('Failed to upload file')
    }
  }

  const handleDownload = (file: FileItem) => {
    if (sidebarSelection === 'public') {
      window.open(`/api/sessions/download?file=${encodeURIComponent(file.path)}&public=true`, '_blank')
    } else if (sidebarSelection === 'secure' && passkey) {
      window.open(`/api/sessions/download?file=${encodeURIComponent(file.path)}&key=${encodeURIComponent(passkey)}`, '_blank')
    }
  }

  const handlePreview = (file: FileItem) => {
    setPreviewFile(file)
  }

  const handleDelete = async (file: FileItem) => {
    if (!confirm(`Delete ${file.name}?`)) return

    try {
      let response
      if (sidebarSelection === 'secure' && passkey) {
        response = await fetch(`/api/data?key=${encodeURIComponent(passkey)}&path=${encodeURIComponent(file.path)}`, {
          method: 'DELETE'
        })
      } else {
        // Public delete (if allowed) or fallback
        const headers: Record<string, string> = {}
        response = await fetch(`/api/files?path=${encodeURIComponent(file.path)}`, {
          method: 'DELETE'
        })
      }

      const result = await response.json()
      if (result.success) {
        loadFiles()
      } else {
        alert(`Delete failed: ${result.error}`)
      }
    } catch (error) {
      console.error('Error deleting file:', error)
      alert('Failed to delete file')
    }
  }

  const handleCreateFolder = async () => {
    const folderName = prompt('Enter folder name:')
    if (!folderName) return

    // Folder creation for secure data is implicit on upload usually, 
    // but we can implement it if needed. 
    // For now, let's skip explicit empty folder creation for secure data 
    // as our API is simple.
    alert('Folder creation is handled automatically when uploading files.')
  }

  const getFileIcon = (file: FileItem) => {
    if (file.type === 'folder') {
      if (file.path === 'public' || file.name === 'Public Folder') {
        return <Globe size={48} weight="fill" className="text-purple-400" />
      }
      return <FolderIcon size={48} weight="fill" className="text-blue-400" />
    }

    if (file.type === 'flutter_app') {
      return <Code size={48} weight="fill" className="text-cyan-500" />
    }

    const ext = file.extension?.toLowerCase()
    switch (ext) {
      case 'pdf': return <FilePdf size={48} weight="fill" className="text-red-500" />
      case 'doc':
      case 'docx': return <FileDoc size={48} weight="fill" className="text-blue-500" />
      case 'txt':
      case 'md': return <FileText size={48} weight="fill" className="text-gray-600" />
      case 'dart': return <Code size={48} weight="fill" className="text-blue-400" />
      case 'tex': return <Function size={48} weight="fill" className="text-green-600" />
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif': return <ImageIcon size={48} weight="fill" className="text-green-500" />
      default: return <File size={48} weight="regular" className="text-gray-500" />
    }
  }

  const formatFileSize = (bytes?: number) => {
    if (!bytes) return ''
    const units = ['B', 'KB', 'MB', 'GB']
    let size = bytes
    let unitIndex = 0
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024
      unitIndex++
    }
    return `${size.toFixed(1)} ${units[unitIndex]}`
  }

  const filteredFiles = files.filter(file =>
    file.name.toLowerCase().includes(searchQuery.toLowerCase())
  )

  const handleSidebarClick = (item: string) => {
    setSidebarSelection(item)
    if (item === 'applications') {
      onNavigate('Applications')
    } else if (item === 'secure') {
      onNavigate('')
      if (!passkey) {
        setShowPasskeyModal(true)
      }
    } else if (item === 'public') {
      onNavigate('public')
    }
  }

  const applications = [
    { id: 'files', name: 'Finder', icon: <div className="bg-gradient-to-br from-blue-400 to-cyan-200 w-full h-full rounded-xl flex items-center justify-center border border-white/30"><FolderIcon size={32} weight="regular" className="text-blue-900" /></div> },
    { id: 'calendar', name: 'Calendar', icon: <div className="w-full h-full"><CalendarIcon size={48} weight="regular" className="text-red-500" /></div> },
    { id: 'clock', name: 'Clock', icon: <div className="w-full h-full"><ClockIcon size={48} weight="regular" className="text-black" /></div> },
    {
      id: 'gemini', name: 'Gemini', icon: (
        <div className="bg-gradient-to-b from-white to-blue-50 w-full h-full rounded-[22%] flex items-center justify-center shadow-lg border-[0.5px] border-white/50 relative overflow-hidden">
          <div className="absolute inset-0 bg-gradient-to-b from-white/40 to-transparent" />
          <Sparkle size={32} weight="fill" className="text-blue-500 drop-shadow-sm" />
        </div>
      )
    },
    {
      id: 'flutter-editor', name: 'Flutter IDE', icon: (
        <div className="bg-gradient-to-b from-[#54C5F8] to-[#29B6F6] w-full h-full rounded-[22%] flex items-center justify-center shadow-lg border-[0.5px] border-white/20 relative overflow-hidden">
          <div className="absolute inset-0 bg-gradient-to-b from-white/20 to-transparent opacity-50" />
          <DeviceMobile size={32} weight="fill" className="text-white relative z-10 drop-shadow-md" />
          <div className="absolute top-1.5 right-1.5">
            <Lightning size={12} weight="fill" className="text-yellow-300 drop-shadow-md" />
          </div>
        </div>
      )
    },
    {
      id: 'latex-editor', name: 'LaTeX Studio', icon: (
        <div className="bg-gradient-to-b from-slate-700 to-slate-900 w-full h-full rounded-[22%] flex items-center justify-center shadow-lg border-[0.5px] border-white/20 relative overflow-hidden">
          <div className="absolute inset-0 bg-gradient-to-b from-white/10 to-transparent opacity-30" />
          <div className="relative z-10 flex flex-col items-center justify-center">
            <Function size={32} weight="bold" className="text-green-400 drop-shadow-md" />
            <span className="text-[8px] font-black text-gray-300 tracking-widest mt-0.5">TEX</span>
          </div>
        </div>
      )
    },
    {
      id: 'quiz', name: 'Quiz Master', icon: (
        <div className="bg-gradient-to-br from-teal-400 to-emerald-500 w-full h-full rounded-[22%] flex items-center justify-center shadow-lg border-[0.5px] border-white/20 relative overflow-hidden">
          <div className="absolute inset-0 bg-gradient-to-b from-white/20 to-transparent opacity-50" />
          <Brain size={32} weight="fill" className="text-white relative z-10 drop-shadow-md" />
        </div>
      )
    },
  ]

  return (
    <>
      <Window
        id="files"
        title={sidebarSelection === 'secure' ? 'Secure Data' : (currentPath || 'Public Files')}
        isOpen={true}
        onClose={onClose}
        onMinimize={onMinimize}
        onMaximize={onMaximize}
        onFocus={onFocus}
        zIndex={zIndex}
        width={1000}
        height={650}
        x={60}
        y={60}
        className="file-manager-window"
      >
        <div className="flex h-full bg-[#F5F5F5] relative">
          {/* Mobile Sidebar Overlay */}
          <AnimatePresence>
            {mobileSidebarOpen && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="absolute inset-0 bg-black/30 z-20 md:hidden"
                onClick={() => setMobileSidebarOpen(false)}
              />
            )}
          </AnimatePresence>

          {/* Sidebar */}
          <AnimatePresence>
            {(mobileSidebarOpen || typeof window !== 'undefined') && (
              <motion.div
                initial={{ x: -192 }}
                animate={{ x: mobileSidebarOpen ? 0 : (typeof window !== 'undefined' && window.innerWidth >= 768 ? 0 : -192) }}
                className={`${mobileSidebarOpen ? 'absolute z-30 h-full' : 'hidden'} md:relative md:flex w-40 sm:w-48 bg-[#F3F3F3]/95 md:bg-[#F3F3F3]/90 backdrop-blur-xl border-r border-gray-200 pt-3 sm:pt-4 flex-col`}
              >
                <div className="px-3 sm:px-4 mb-2 flex items-center justify-between">
                  <span className="text-[10px] sm:text-xs font-bold text-gray-400">Locations</span>
                  <button
                    onClick={() => setMobileSidebarOpen(false)}
                    className="p-1 hover:bg-gray-200 rounded md:hidden"
                  >
                    <X size={14} />
                  </button>
                </div>
                <nav className="space-y-1 px-1.5 sm:px-2">
                  <button
                    onClick={() => { handleSidebarClick('public'); setMobileSidebarOpen(false); }}
                    className={`w-full flex items-center gap-1.5 sm:gap-2 px-2 py-1.5 rounded-md text-xs sm:text-sm ${sidebarSelection === 'public' ? 'bg-gray-200 text-black' : 'text-gray-600 hover:bg-gray-100'}`}
                  >
                    <Globe size={16} weight="fill" className="text-purple-500 sm:w-[18px] sm:h-[18px]" />
                    <span className="truncate">Public Files</span>
                  </button>
                  <button
                    onClick={() => { handleSidebarClick('secure'); setMobileSidebarOpen(false); }}
                    className={`w-full flex items-center gap-1.5 sm:gap-2 px-2 py-1.5 rounded-md text-xs sm:text-sm ${sidebarSelection === 'secure' ? 'bg-gray-200 text-black' : 'text-gray-600 hover:bg-gray-100'}`}
                  >
                    <Lock size={16} weight="fill" className="text-blue-500 sm:w-[18px] sm:h-[18px]" />
                    <span className="truncate">Secure Data</span>
                  </button>
                  <button
                    onClick={() => { handleSidebarClick('applications'); setMobileSidebarOpen(false); }}
                    className={`w-full flex items-center gap-1.5 sm:gap-2 px-2 py-1.5 rounded-md text-xs sm:text-sm ${sidebarSelection === 'applications' ? 'bg-gray-200 text-black' : 'text-gray-600 hover:bg-gray-100'}`}
                  >
                    <AppWindow size={16} weight="fill" className="text-green-500 sm:w-[18px] sm:h-[18px]" />
                    <span className="truncate">Applications</span>
                  </button>
                </nav>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Main Content */}
          <div className="flex-1 flex flex-col bg-white relative min-w-0">
            {/* Toolbar */}
            <div className="h-10 sm:h-12 bg-white border-b border-gray-200 flex items-center px-2 sm:px-4 gap-2 sm:gap-4 justify-between">
              <div className="flex items-center gap-1 sm:gap-2 min-w-0 flex-1">
                <button
                  onClick={() => setMobileSidebarOpen(true)}
                  className="p-1.5 hover:bg-gray-100 rounded-md md:hidden flex-shrink-0"
                >
                  <List size={18} weight="bold" className="text-gray-600" />
                </button>
                <button
                  onClick={() => {
                    const parent = currentPath.split('/').slice(0, -1).join('/')
                    onNavigate(parent)
                  }}
                  disabled={!currentPath || currentPath === 'Applications'}
                  className="p-1 sm:p-1.5 hover:bg-gray-100 rounded-md disabled:opacity-30 transition-colors flex-shrink-0"
                >
                  <CaretLeft size={16} weight="bold" className="text-gray-600 sm:w-[18px] sm:h-[18px]" />
                </button>
                <span className="text-xs sm:text-sm font-semibold text-gray-700 truncate">
                  {currentPath === '' ? (sidebarSelection === 'secure' ? 'Secure Data' : 'Public') : currentPath}
                </span>
              </div>

              <div className="flex items-center gap-1 sm:gap-2 flex-shrink-0">
                {sidebarSelection === 'secure' && passkey && (
                  <button
                    onClick={handleLock}
                    className="hidden xs:flex items-center gap-1 px-2 sm:px-3 py-1 sm:py-1.5 bg-gray-100 hover:bg-gray-200 rounded-md text-[10px] sm:text-xs font-medium text-gray-600 transition-colors"
                  >
                    <Lock size={12} className="sm:w-3.5 sm:h-3.5" />
                    <span className="hidden sm:inline">Lock</span>
                  </button>
                )}

                {currentPath !== 'Applications' && (
                  <button
                    onClick={() => setUploadModalOpen(true)}
                    className="p-1 sm:p-1.5 hover:bg-gray-100 rounded-md transition-colors"
                    title="Upload File"
                  >
                    <Upload size={16} weight="bold" className="text-gray-600 sm:w-[18px] sm:h-[18px]" />
                  </button>
                )}
                <div className="flex items-center gap-1 sm:gap-2 px-2 sm:px-3 py-1 sm:py-1.5 bg-gray-100 rounded-md w-24 sm:w-32 md:w-48">
                  <MagnifyingGlass size={12} weight="bold" className="text-gray-400 sm:w-3.5 sm:h-3.5 flex-shrink-0" />
                  <input
                    type="text"
                    placeholder="Search"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="bg-transparent text-xs sm:text-sm outline-none w-full placeholder-gray-400 min-w-0"
                  />
                </div>
              </div>
            </div>

            {/* File Grid */}
            <div className="flex-1 overflow-auto p-3 sm:p-6">
              {currentPath === 'Applications' ? (
                <div className="grid grid-cols-3 xs:grid-cols-4 sm:grid-cols-4 md:grid-cols-5 gap-2 sm:gap-4 md:gap-6">
                  {applications.map((app) => (
                    <button
                      key={app.id}
                      onDoubleClick={() => onOpenApp && onOpenApp(app.id)}
                      className="flex flex-col items-center gap-1.5 sm:gap-3 p-2 sm:p-4 hover:bg-blue-50 rounded-xl transition-colors group"
                    >
                      <div className="w-10 h-10 sm:w-14 sm:h-14 md:w-16 md:h-16 flex items-center justify-center drop-shadow-sm group-hover:scale-105 transition-transform">
                        {app.icon}
                      </div>
                      <span className="text-[10px] sm:text-xs md:text-sm font-medium text-gray-700 text-center line-clamp-2">{app.name}</span>
                    </button>
                  ))}
                </div>
              ) : (
                <>
                  {loading ? (
                    <div className="flex items-center justify-center h-full text-gray-400 text-sm">
                      Loading files...
                    </div>
                  ) : filteredFiles.length === 0 ? (
                    <div className="flex items-center justify-center h-full text-gray-400 text-xs sm:text-sm">
                      {searchQuery ? 'No files found' : 'Folder is empty'}
                    </div>
                  ) : (
                    <div className="grid grid-cols-3 xs:grid-cols-4 sm:grid-cols-4 md:grid-cols-5 gap-2 sm:gap-4 md:gap-6">
                      {filteredFiles.map((file) => (
                        <div
                          key={file.path}
                          className="group relative"
                        >
                          <button
                            onDoubleClick={async () => {
                              if (file.type === 'folder') {
                                onNavigate(file.path)
                              } else if (file.type === 'flutter_app' && onOpenFlutterApp) {
                                onOpenFlutterApp(file)
                              } else if (file.extension === 'dart' || file.extension === 'flutter') {
                                // Load the file content and open Flutter IDE with it
                                try {
                                  let fileContent = ''
                                  if (sidebarSelection === 'secure' && passkey) {
                                    const response = await fetch(`/api/data?key=${encodeURIComponent(passkey)}&folder=${encodeURIComponent(currentPath)}`)
                                    const data = await response.json()
                                    const fileData = data.files?.find((f: any) => f.name === file.name)
                                    fileContent = fileData?.content || ''

                                    // Store for auto-save in Flutter IDE
                                    sessionStorage.setItem('currentPasskey', passkey)
                                    sessionStorage.setItem('currentFileName', file.name)
                                  } else if (sidebarSelection === 'public') {
                                    // Load from public folder
                                    const folderPath = currentPath.replace('public/', '').replace('public', '')
                                    const response = await fetch(`/api/public?folder=${encodeURIComponent(folderPath)}`)
                                    if (response.ok) {
                                      const data = await response.json()
                                      const fileData = data.files?.find((f: any) => f.name === file.name)
                                      fileContent = fileData?.content || ''
                                    }
                                  }

                                  console.log('Opening dart file:', file.name, 'Content length:', fileContent.length)

                                  // Open Flutter IDE with the file content
                                  if (onOpenApp) {
                                    // Store the content temporarily for the Flutter IDE to pick up
                                    sessionStorage.setItem('flutterFileContent', fileContent)
                                    sessionStorage.setItem('currentFileName', file.name)
                                    if (passkey) {
                                      sessionStorage.setItem('currentPasskey', passkey)
                                    }
                                    onOpenApp('flutter-editor')
                                  }
                                } catch (error) {
                                  console.error('Error loading file:', error)
                                  alert('Failed to load dart file for editing')
                                }
                              } else if (isTextFile(file.extension || '')) {
                                // Load the file content and open Text Editor with it
                                try {
                                  let fileContent = ''
                                  if (sidebarSelection === 'secure' && passkey) {
                                    const response = await fetch(`/api/data?key=${encodeURIComponent(passkey)}&folder=${encodeURIComponent(currentPath)}`)
                                    const data = await response.json()
                                    const fileData = data.files?.find((f: any) => f.name === file.name)
                                    fileContent = fileData?.content || ''
                                  } else if (sidebarSelection === 'public') {
                                    // Load from public folder
                                    const folderPath = currentPath.replace('public/', '').replace('public', '')
                                    const response = await fetch(`/api/public?folder=${encodeURIComponent(folderPath)}`)
                                    if (response.ok) {
                                      const data = await response.json()
                                      const fileData = data.files?.find((f: any) => f.name === file.name)
                                      fileContent = fileData?.content || ''
                                    }
                                  }

                                  console.log('Opening file:', file.name, 'Content length:', fileContent.length)

                                  // Open Text Editor with the file content
                                  if (onOpenTextFile) {
                                    onOpenTextFile({
                                      content: fileContent,
                                      fileName: file.name,
                                      filePath: currentPath,
                                      passkey: passkey || ''
                                    })
                                  }
                                } catch (error) {
                                  console.error('Error loading file:', error)
                                  alert('Failed to load file for editing')
                                }
                              } else {
                                handlePreview(file)
                              }
                            }}
                            className="flex flex-col items-center gap-1.5 sm:gap-3 p-2 sm:p-4 hover:bg-blue-50 rounded-xl w-full transition-colors"
                          >
                            <div className="w-10 h-10 sm:w-14 sm:h-14 md:w-16 md:h-16 flex items-center justify-center drop-shadow-sm">
                              {getFileIcon(file)}
                            </div>
                            <span className="text-[10px] sm:text-xs md:text-sm font-medium text-gray-700 text-center break-all w-full line-clamp-2">
                              {file.name}
                            </span>
                            {file.size && (
                              <span className="text-[9px] sm:text-xs text-gray-400 hidden sm:block">
                                {formatFileSize(file.size)}
                              </span>
                            )}
                          </button>

                          {file.type === 'file' && (
                            <div className="absolute top-1 right-1 sm:top-2 sm:right-2 hidden group-hover:flex gap-0.5 sm:gap-1 bg-white/90 rounded-lg shadow-sm p-0.5 sm:p-1">
                              <button
                                onClick={(e) => {
                                  e.stopPropagation()
                                  handlePreview(file)
                                }}
                                className="p-1 sm:p-1.5 hover:bg-gray-100 rounded-md text-gray-600"
                                title="Preview"
                              >
                                <Eye size={12} weight="bold" className="sm:w-3.5 sm:h-3.5" />
                              </button>
                              <button
                                onClick={(e) => {
                                  e.stopPropagation()
                                  handleDelete(file)
                                }}
                                className="p-1 sm:p-1.5 hover:bg-red-50 rounded-md text-red-500"
                                title="Delete"
                              >
                                <Trash size={12} weight="bold" className="sm:w-3.5 sm:h-3.5" />
                              </button>
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                </>
              )}
            </div>

            {/* Status Bar */}
            <div className="h-6 sm:h-8 bg-white border-t border-gray-200 flex items-center px-2 sm:px-4 text-[10px] sm:text-xs text-gray-500 font-medium">
              {currentPath === 'Applications'
                ? `${applications.length} items`
                : `${filteredFiles.length} items`
              }
            </div>

            {/* Passkey Modal */}
            <AnimatePresence>
              {showPasskeyModal && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className="absolute inset-0 bg-white/80 backdrop-blur-md z-50 flex items-center justify-center p-4"
                >
                  <motion.div
                    initial={{ scale: 0.9, y: 20 }}
                    animate={{ scale: 1, y: 0 }}
                    className="bg-white p-4 sm:p-8 rounded-2xl shadow-2xl border border-gray-200 w-full max-w-xs sm:max-w-sm text-center"
                  >
                    <div className="w-12 h-12 sm:w-16 sm:h-16 bg-blue-50 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                      <Lock size={24} weight="fill" className="text-blue-500 sm:w-8 sm:h-8" />
                    </div>
                    <h3 className="text-lg sm:text-xl font-bold text-gray-900 mb-1 sm:mb-2">Secure Storage</h3>
                    <p className="text-gray-500 text-xs sm:text-sm mb-4 sm:mb-6">Enter your passkey to access your files.</p>

                    <input
                      type="password"
                      value={tempPasskey}
                      onChange={(e) => setTempPasskey(e.target.value)}
                      onKeyDown={(e) => e.key === 'Enter' && handlePasskeySubmit()}
                      placeholder="Enter Passkey"
                      className="w-full px-3 sm:px-4 py-2 sm:py-3 rounded-xl border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 outline-none mb-3 sm:mb-4 text-center text-base sm:text-lg tracking-widest"
                      autoFocus
                    />

                    <div className="flex gap-2 sm:gap-3">
                      <button
                        onClick={() => {
                          setShowPasskeyModal(false)
                          setSidebarSelection('public')
                          onNavigate('public')
                        }}
                        className="flex-1 px-3 sm:px-4 py-2 sm:py-2.5 bg-gray-100 text-gray-700 rounded-xl text-sm sm:text-base font-medium hover:bg-gray-200 transition-colors"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={handlePasskeySubmit}
                        disabled={!tempPasskey}
                        className="flex-1 px-4 py-2.5 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        Unlock
                      </button>
                    </div>
                  </motion.div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>
      </Window>

      {/* Upload Modal */}
      {uploadModalOpen && (
        <UploadModal
          currentPath={currentPath}
          onUpload={handleUpload}
          onClose={() => setUploadModalOpen(false)}
        />
      )}

      {/* File Preview Modal */}
      {previewFile && (
        <FilePreview
          file={previewFile}
          onClose={() => setPreviewFile(null)}
          onDownload={() => handleDownload(previewFile)}
          passkey={passkey}
          isPublic={sidebarSelection === 'public'}
        />
      )}
    </>
  )
}

// Upload Modal Component
function UploadModal({
  currentPath,
  onUpload,
  onClose
}: {
  currentPath: string
  onUpload: (file: File, folder: string) => void
  onClose: () => void
}) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [targetFolder, setTargetFolder] = useState(currentPath)

  const handleSubmit = () => {
    if (selectedFile) {
      onUpload(selectedFile, targetFolder)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/20 backdrop-blur-sm flex items-center justify-center z-[100]">
      <div className="bg-white rounded-xl shadow-2xl p-6 w-[400px] border border-gray-200">
        <h2 className="text-lg font-semibold mb-4 text-gray-800">Upload File</h2>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2 text-gray-600">Select File</label>
            <input
              type="file"
              onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
              className="w-full p-2 border border-gray-300 rounded-lg text-sm"
            />
          </div>

          <div>
            <label className="block text-sm font-medium mb-2 text-gray-600">Upload to Folder</label>
            <input
              type="text"
              value={targetFolder}
              onChange={(e) => setTargetFolder(e.target.value)}
              placeholder="e.g., homework/math"
              className="w-full p-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
            />
            <p className="text-xs text-gray-400 mt-1">
              Leave empty for root, or enter path like "folder/subfolder"
            </p>
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm font-medium transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={handleSubmit}
              disabled={!selectedFile}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 text-sm font-medium shadow-lg shadow-blue-500/20 transition-all"
            >
              Upload
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}