// Auteur : Simon-Pierre Boucher — contact@spboucher.ai "use client"; import { useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { useLang } from "./LangContext"; export interface Suggestion { id: string; adresse: string | null; apt: string | null; municipalite: string | null; typeProp: string; } export default function SearchBox({ onPick, placeholder, }: { /** Si fourni : appelé au choix d'une adresse (le champ se vide) au lieu de naviguer. */ onPick?: (s: Suggestion) => void; placeholder?: string; }) { const { t } = useLang(); const router = useRouter(); const [q, setQ] = useState(""); const [sugg, setSugg] = useState([]); const [open, setOpen] = useState(false); const [searched, setSearched] = useState(false); const timer = useRef | null>(null); const onChange = (value: string) => { setQ(value); if (timer.current) clearTimeout(timer.current); if (value.trim().length < 3) { setSugg([]); setSearched(false); return; } timer.current = setTimeout(async () => { const res = await fetch(`/api/search?q=${encodeURIComponent(value)}`); const data = (await res.json()) as { results: Suggestion[] }; setSugg(data.results); setSearched(true); setOpen(true); }, 200); }; return (
onChange(e.target.value)} onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 200)} placeholder={placeholder ?? t("searchPlaceholder")} className="vp-input text-base" aria-label={placeholder ?? t("searchPlaceholder")} /> {open && sugg.length > 0 && (
    {sugg.map((s) => (
  • ))}
)} {open && searched && sugg.length === 0 && q.trim().length >= 3 && (
{t("searchNoResult")}
)}
); }