// 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, variant = "default", }: { /** Si fourni : appelé au choix d'une adresse (le champ se vide) au lieu de naviguer. */ onPick?: (s: Suggestion) => void; placeholder?: string; /** « hero » : grand champ sur aplat encre (page d'accueil). */ variant?: "default" | "hero"; }) { const { t, lang } = useLang(); const fr = lang === "fr"; 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 input = useRef(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); }; const pick = (s: Suggestion) => { if (onPick) { onPick(s); setQ(""); setSugg([]); setSearched(false); } else { router.push(`/estimation/${s.id}`); } }; const hero = variant === "hero"; return (
onChange(e.target.value)} onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 200)} placeholder={ placeholder ?? (hero ? (fr ? "ex. 861 route Elgin" : "e.g. 861 route Elgin") : t("searchPlaceholder")) } className={ hero ? "min-h-[56px] w-full min-w-0 flex-1 border-0 border-b border-[rgba(245,243,238,0.45)] bg-transparent px-1 py-3 text-[16px] text-[var(--paper-on-ink)] outline-none transition-colors placeholder:text-[rgba(245,243,238,0.45)] focus:border-[var(--accent-bright)] sm:text-[19px]" : "vp-input text-base" } aria-label={placeholder ?? t("searchPlaceholder")} /> {hero && ( )}
{open && sugg.length > 0 && (
    {sugg.map((s, i) => (
  • ))}
)} {open && searched && sugg.length === 0 && q.trim().length >= 3 && (
{t("searchNoResult")}
)}
); }