import { useState, useRef, useEffect, useCallback } from 'react' import { createPortal } from 'react-dom' import { MessageSquare, ChevronDown } from 'lucide-react' import type { SessionSummary } from '../../types/protocol' interface SessionSelectorProps { sessions: SessionSummary[] selectedSessionId: string | null onSelectSession: (sessionId: string) => void } export function SessionSelector({ sessions, selectedSessionId, onSelectSession, }: SessionSelectorProps) { const [isOpen, setIsOpen] = useState(false) const [dropdownPos, setDropdownPos] = useState<{ top: number; right: number }>({ top: 0, right: 0 }) const triggerRef = useRef(null) const dropdownRef = useRef(null) const selected = sessions.find((s) => s.session_id === selectedSessionId) const updatePosition = useCallback(() => { if (triggerRef.current) { const rect = triggerRef.current.getBoundingClientRect() setDropdownPos({ top: rect.bottom + 8, right: window.innerWidth - rect.right, }) } }, []) useEffect(() => { if (isOpen) { updatePosition() window.addEventListener('resize', updatePosition) window.addEventListener('scroll', updatePosition, true) return () => { window.removeEventListener('resize', updatePosition) window.removeEventListener('scroll', updatePosition, true) } } }, [isOpen, updatePosition]) useEffect(() => { if (!isOpen) return const handleClick = (e: MouseEvent) => { const target = e.target as Node if ( dropdownRef.current && !dropdownRef.current.contains(target) && triggerRef.current && !triggerRef.current.contains(target) ) { setIsOpen(false) } } document.addEventListener('mousedown', handleClick) return () => document.removeEventListener('mousedown', handleClick) }, [isOpen]) useEffect(() => { if (!isOpen) return const handleKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setIsOpen(false) } document.addEventListener('keydown', handleKey) return () => document.removeEventListener('keydown', handleKey) }, [isOpen]) if (sessions.length === 0) return null return ( <> {isOpen && sessions.length > 1 && createPortal(
{sessions.map((s, index) => { const isActive = s.session_id === selectedSessionId return ( ) })}
, document.body )} ) }