import { DriveLsEntry } from "@/lib/drive_types"
import { DriveDirectoryClient } from "./DriveDirectoryClient"
import { DriveHeader } from "./DriveHeader"
import type { StorageData } from "@/lib/storage"
import { Auth_get_user } from "@/lib/auth"

interface DriveDirectoryViewProps {
  path: string
  files: DriveLsEntry[]
  storageData: StorageData
}

// Generate breadcrumbs from path
function generateBreadcrumbs(currentPath: string) {
  if (currentPath === '/') {
    return [{ name: 'Root', path: '/drive' }]
  }
  
  const parts = currentPath.split('/').filter(Boolean)
  const breadcrumbs = [{ name: 'Root', path: '/drive' }]
  
  let accumulatedPath = ''
  parts.forEach((part, _index) => {
    accumulatedPath += '/' + part
    breadcrumbs.push({
      name: decodeURIComponent(part), // Decode URL encoded characters
      path: '/drive' + accumulatedPath
    })
  })
  
  return breadcrumbs
}

// Sort files: directories first, then files, all alphabetically
function sortFiles(files: DriveLsEntry[]): DriveLsEntry[] {
  return [...files].sort((a, b) => {
    // Directories first, then files
    if (a.type === "dir" && b.type === "file") return -1;
    if (a.type === "file" && b.type === "dir") return 1;
    
    // Both same type, sort alphabetically by name (case-insensitive)
    const aName = a.path.split('/').pop() || a.path;
    const bName = b.path.split('/').pop() || b.path;
    return aName.toLowerCase().localeCompare(bName.toLowerCase());
  });
}

export async function DriveDirectoryView({ path, files, storageData }: DriveDirectoryViewProps) {
  const sortedFiles = sortFiles(files)
  const breadcrumbs = generateBreadcrumbs(path)
  const userAuth = await Auth_get_user()
  
  return (
    <div className="container mx-auto p-6 space-y-6">
      <DriveHeader />
      <DriveDirectoryClient 
        path={path} 
        files={sortedFiles} 
        breadcrumbs={breadcrumbs}
        storageData={storageData}
        userAuth={userAuth}
      />
    </div>
  )
}
