import { useState, useEffect } from 'react'; import { createPortal } from 'react-dom'; import type { PackageSlot } from '../hooks/usePackages'; interface Props { slots: PackageSlot[]; activeId: string; onSwitch: (id: string) => void; onCreate: () => void; onRemove: (id: string) => void; onRename: (id: string, name: string) => void; onDuplicate: (id: string) => void; } interface MenuState { id: string; top: number; left: number; } export function PackageSwitcher({ slots, activeId, onSwitch, onCreate, onRemove, onRename, onDuplicate }: Props) { const [editingId, setEditingId] = useState(null); const [draft, setDraft] = useState(''); const [menu, setMenu] = useState(null); // Close dropdown on any outside click useEffect(() => { if (!menu) return; const handler = () => setMenu(null); document.addEventListener('click', handler); return () => document.removeEventListener('click', handler); }, [menu]); const openMenu = (id: string, e: React.MouseEvent) => { e.stopPropagation(); if (menu?.id === id) { setMenu(null); return; } const rect = e.currentTarget.getBoundingClientRect(); setMenu({ id, top: rect.bottom + 4, left: rect.left }); }; const commitRename = (id: string) => { const name = draft.trim(); if (name) onRename(id, name); setEditingId(null); }; return (
{slots.map(slot => (
slot.id !== activeId && onSwitch(slot.id)} > {editingId === slot.id ? ( setDraft(e.target.value)} onBlur={() => commitRename(slot.id)} onKeyDown={e => { if (e.key === 'Enter') commitRename(slot.id); if (e.key === 'Escape') setEditingId(null); }} onClick={e => e.stopPropagation()} /> ) : ( { e.stopPropagation(); setDraft(slot.name); setEditingId(slot.id); }} > {slot.name} )}
{slots.length > 1 && ( )}
))} {/* Dropdown rendered in a portal to escape overflow clipping */} {menu && createPortal(
e.stopPropagation()} > {slots.length > 1 && ( )}
, document.body )}
); }