"use client"; import Image from "next/image"; import Link from "next/link"; import { FormEvent, useEffect, useRef, useState } from "react"; import { categoryPath } from "@/lib/category-path"; import { productPath } from "@/lib/product-path"; import { API_URL, STORE_SLUG } from "@/lib/public-api"; type SearchHit = { id: number | string; nameFa: string; nameEn: string; imageUrl?: string | null; price?: number; }; type CategoryHit = { id: number; nameFa: string; nameEn: string; }; export default function HeaderSearch() { const [open, setOpen] = useState(false); const [q, setQ] = useState(""); const [loading, setLoading] = useState(false); const [products, setProducts] = useState([]); const [categories, setCategories] = useState([]); const inputRef = useRef(null); const panelRef = useRef(null); useEffect(() => { if (!open) return; inputRef.current?.focus(); const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [open]); useEffect(() => { if (!open) return; const query = q.trim(); if (query.length < 2) { setProducts([]); setCategories([]); return; } const t = window.setTimeout(async () => { setLoading(true); try { const params = new URLSearchParams({ storeSlug: STORE_SLUG, q: query, limit: "8", }); const res = await fetch(`${API_URL}/public/search?${params}`); if (!res.ok) throw new Error("search failed"); const data = (await res.json()) as { products?: SearchHit[]; categories?: CategoryHit[]; }; setProducts(data.products ?? []); setCategories(data.categories ?? []); } catch { setProducts([]); setCategories([]); } finally { setLoading(false); } }, 280); return () => window.clearTimeout(t); }, [q, open]); function handleSubmit(e: FormEvent) { e.preventDefault(); const query = q.trim(); if (!query) return; setOpen(false); window.location.href = `/products?q=${encodeURIComponent(query)}`; } return ( <> {open ? (
{loading ? (

در حال جستجو...

) : q.trim().length < 2 ? (

حداقل ۲ حرف وارد کنید.

) : !products.length && !categories.length ? (

نتیجه‌ای یافت نشد.

) : (
{categories.length ? (

دسته‌بندی‌ها

    {categories.map((c) => (
  • setOpen(false)} className="block border border-transparent px-2 py-2 text-sm hover:border-line hover:bg-[#f7f7f5]" > {c.nameFa} {c.nameEn ? ( {c.nameEn} ) : null}
  • ))}
) : null} {products.length ? (

محصولات

    {products.map((p) => (
  • setOpen(false)} className="flex items-center gap-3 border border-transparent px-2 py-2 hover:border-line hover:bg-[#f7f7f5]" > {/* eslint-disable-next-line @next/next/no-img-element */} {p.nameFa} {p.nameEn}
  • ))}
) : null}
)}
) : null} ); }