import { useState, useRef, useEffect } from 'react'; interface SearchResult { id: string; slug: string; name: string; brand: string; colorway: string; image: string; lowestPrice: number; shopCount: number; } export default function SearchBar({ large = false }: { large?: boolean }) { const [query, setQuery] = useState(''); const [results, setResults] = useState([]); const [open, setOpen] = useState(false); const ref = useRef(null); const debounceRef = useRef>(); useEffect(() => { if (query.length < 2) { setResults([]); return; } clearTimeout(debounceRef.current); debounceRef.current = setTimeout(async () => { try { const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`); if (res.ok) setResults(await res.json()); } catch {} }, 200); return () => clearTimeout(debounceRef.current); }, [query]); useEffect(() => { const handler = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); }; document.addEventListener('mousedown', handler); return () => document.removeEventListener('mousedown', handler); }, []); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && query.trim().length >= 2) { // Push search event to dataLayer window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'search', search_term: query.trim() }); setOpen(false); window.location.href = `/zoeken?q=${encodeURIComponent(query.trim())}`; } }; const searchUrl = `/zoeken?q=${encodeURIComponent(query.trim())}`; const handleViewAll = () => { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'search', search_term: query.trim() }); }; return (
{ setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onKeyDown={handleKeyDown} placeholder="Zoek sneakers..." className={`w-full bg-transparent text-text placeholder-text-muted outline-none ${large ? 'text-lg' : 'text-sm'}`} aria-label="Zoek sneakers" /> {query && ( )}
{open && results.length > 0 && (
{results.map(s => ( { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ ecommerce: null }); window.dataLayer.push({ event: 'select_item', ecommerce: { items: [{ item_id: s.id, item_name: `${s.brand} ${s.name}`, item_brand: s.brand, price: s.lowestPrice, }] } }); }} >
{s.brand} {s.name}
{s.colorway}{s.shopCount > 0 && ` · ${s.shopCount} ${s.shopCount === 1 ? 'winkel' : 'winkels'}`}
€{s.lowestPrice.toFixed(2).replace('.', ',')}
))} Bekijk alle resultaten
)}
); }