import { useEffect, useRef, useState } from 'react' import { api } from '../utils/api' export default function FoodSearchModal({ title, initialQuery, onSelect, onClose }) { const [q, setQ] = useState(initialQuery || '') const [hits, setHits] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const inputRef = useRef(null) const timer = useRef(null) const runSearch = async (term) => { const query = (term || '').trim() if (query.length < 2) { setHits([]) return } setLoading(true) setError(null) try { setHits(await api.searchBlsFoods(query, 30)) } catch (e) { setError(e.message) setHits([]) } finally { setLoading(false) } } useEffect(() => { inputRef.current?.focus() inputRef.current?.select() if ((initialQuery || '').trim().length >= 2) runSearch(initialQuery) const onKey = (e) => { if (e.key === 'Escape') onClose() } window.addEventListener('keydown', onKey) return () => { window.removeEventListener('keydown', onKey) clearTimeout(timer.current) } }, []) const onChange = (value) => { setQ(value) clearTimeout(timer.current) timer.current = setTimeout(() => runSearch(value), 250) } return (
e.stopPropagation()} style={{ width: '100%', maxWidth: 520, maxHeight: 'min(88vh, 640px)', background: 'var(--surface)', borderRadius: 16, boxShadow: '0 8px 32px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column', }} >

{title || 'Lebensmittel suchen'}

onChange(e.target.value)} />

Suche nach dem Namen. Den BLS-Code brauchst du nicht.

{loading &&

Suche…

} {error &&

{error}

} {!loading && q.trim().length >= 2 && hits.length === 0 && (

Kein Treffer. Anderen Suchbegriff versuchen.

)} {hits.map((h) => ( ))}
) }