import { useState, useEffect, useRef } from 'react' import { sessionsApi, type RecentProject } from '../../api/sessions' import { filesystemApi } from '../../api/filesystem' type Props = { value: string onChange: (path: string) => void } type DirEntry = { name: string; path: string; isDirectory: boolean } export function DirectoryPicker({ value, onChange }: Props) { const [open, setOpen] = useState(false) const [mode, setMode] = useState<'recent' | 'browse'>('recent') const [projects, setProjects] = useState([]) const [browseEntries, setBrowseEntries] = useState([]) const [browsePath, setBrowsePath] = useState('') const [browseParent, setBrowseParent] = useState('') const [loading, setLoading] = useState(false) const ref = useRef(null) // Close on outside click useEffect(() => { if (!open) return const handleClick = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) } document.addEventListener('mousedown', handleClick) return () => document.removeEventListener('mousedown', handleClick) }, [open]) // Load recent projects when opened useEffect(() => { if (!open || mode !== 'recent') return setLoading(true) sessionsApi.getRecentProjects() .then(({ projects }) => setProjects(projects)) .catch(() => setProjects([])) .finally(() => setLoading(false)) }, [open, mode]) const loadBrowseDir = async (path?: string) => { setLoading(true) try { const result = await filesystemApi.browse(path) setBrowsePath(result.currentPath) setBrowseParent(result.parentPath) setBrowseEntries(result.entries) } catch { /* API not available */ } setLoading(false) } const handleSelect = (path: string) => { onChange(path) setOpen(false) setMode('recent') } const switchToBrowse = () => { setMode('browse') loadBrowseDir(value || undefined) } // Find selected project info const selectedProject = projects.find((p) => p.realPath === value) return (
{/* Trigger — shows selected project chip or placeholder */} {value ? ( ) : ( )} {/* Dropdown */} {open && (
{mode === 'recent' ? ( /* Recent projects mode */ <>
Recent
{loading ? (
Loading...
) : projects.length === 0 ? (
No recent projects
) : ( projects.map((project) => { const isSelected = project.realPath === value return ( ) }) )}
{/* Divider + Choose different folder */}
) : ( /* File browser mode */ <>
{browsePath.split('/').filter(Boolean).map((seg, i, arr) => ( / ))}
{loading ? (
Loading...
) : ( <> {browseParent && browseParent !== browsePath && ( )} {browseEntries.length === 0 ? (
No subdirectories
) : browseEntries.map((entry) => ( ))} )}
{/* Use current folder */}
{browsePath}
)}
)}
) }