"use client"; import { useEffect, useRef, useState } from "react"; import { useTranslations } from "next-intl"; import { Search, X, Bot, User } from "lucide-react"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; type SearchResult = { id: string; role: "user" | "assistant"; content: string; createdAt: string; recipeId: string | null; recipeTitle: string | null; }; /** * Search across the user's own AI-chat history. With `recipeId` set, scopes * to that recipe's conversation; omit it to search everything the user has * ever asked (both per-recipe chats and the general cooking assistant). */ export function ChatHistorySearch({ recipeId }: { recipeId?: string }) { const t = useTranslations("chatHistory"); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [results, setResults] = useState([]); const [loading, setLoading] = useState(false); const containerRef = useRef(null); useEffect(() => { function handleClickOutside(e: MouseEvent) { if (containerRef.current && !containerRef.current.contains(e.target as Node)) { setOpen(false); } } document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); useEffect(() => { if (!query.trim()) return; const timeout = setTimeout(() => { setLoading(true); const params = new URLSearchParams({ q: query.trim() }); if (recipeId) params.set("recipeId", recipeId); fetch(`/api/v1/ai/chat-history?${params.toString()}`) .then((res) => (res.ok ? res.json() : null)) .then((json: { data?: SearchResult[] } | null) => setResults(json?.data ?? [])) .catch(() => setResults([])) .finally(() => setLoading(false)); }, 300); return () => clearTimeout(timeout); }, [query, recipeId]); return (
{open && (
setQuery(e.target.value)} placeholder={t("searchPlaceholder")} className="h-8 text-sm" />
{loading &&

{t("searching")}

} {!loading && query.trim() && results.length === 0 && (

{t("noResults")}

)} {!loading && query.trim() && results.map((r) => (
{r.role === "user" ? : } {new Date(r.createdAt).toLocaleDateString()} {r.recipeTitle && !recipeId && ( ยท {r.recipeTitle} )}

{r.content}

))}
)}
); }