import React, { useEffect, useRef, useState } from 'react' import { ChevronDown, Check, Pencil } from 'lucide-react' /** * Header form switcher (the reference builder Radix Select, F:7432-7516): borderless trigger truncated at 150px, list with a check * on the current form, "No forms available" empty state, pencil (rename) shown on hover. * Props: forms [{ id, name }], currentId, currentName, onSelect(id), onRename() (optional). */ export default function FormSwitcher({ forms = [], currentId, currentName = 'Untitled', onSelect, onRename }) { const [open, setOpen] = useState(false) const [focusIdx, setFocusIdx] = useState(-1) const rootRef = useRef(null) const listRef = useRef(null) const list = forms.some((f) => String(f.id) === String(currentId)) || !currentId ? forms : [{ id: currentId, name: currentName }, ...forms] const current = list.find((f) => String(f.id) === String(currentId)) const label = (current && current.name) || currentName || 'Untitled' useEffect(() => { if (!open) return undefined const onDoc = (e) => { if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false) } document.addEventListener('mousedown', onDoc) return () => document.removeEventListener('mousedown', onDoc) }, [open]) useEffect(() => { if (open && listRef.current && focusIdx >= 0) { const el = listRef.current.querySelectorAll('[role="option"]')[focusIdx] if (el) el.focus() } }, [open, focusIdx]) const choose = (id) => { setOpen(false) if (String(id) !== String(currentId) && onSelect) onSelect(id) } const onKeyDown = (e) => { if (e.key === 'Escape') { setOpen(false); return } if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault() if (!open) { setOpen(true); setFocusIdx(Math.max(0, list.findIndex((f) => String(f.id) === String(currentId)))); return } setFocusIdx((i) => { const n = list.length if (!n) return -1 return e.key === 'ArrowDown' ? (i + 1) % n : (i - 1 + n) % n }) } } return (