import { useState, useEffect, useRef, useCallback, useMemo, useReducer, } from "react"; import { useSearchParams, Link } from "react-router-dom"; import { useTmdbSearch, useTmdbSearchPeople } from "@/hooks/useTmdb"; import { useLibrary } from "@/hooks/useEntries"; import { Input } from "@/components/ui/input"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Button } from "@/components/ui/button"; import { Search, Loader2 } from "lucide-react"; import { EntryCard } from "@/components/entries/EntryCard"; import { getProfileUrl } from "@/lib/media-utils"; type SearchTab = "entries" | "people"; const MAX_EMPTY_PAGES = 4; export function SearchPage() { const [searchParams, setSearchParams] = useSearchParams(); const initialQuery = searchParams.get("q") || ""; const [searchInput, setSearchInput] = useState(initialQuery); const [debouncedQuery, setDebouncedQuery] = useState(initialQuery); const [activeTab, setActiveTab] = useState("entries"); const debounceRef = useRef>(null); useEffect(() => { if (debounceRef.current) clearTimeout(debounceRef.current); debounceRef.current = setTimeout(() => { setDebouncedQuery(searchInput); }, 400); return () => { if (debounceRef.current) clearTimeout(debounceRef.current); }; }, [searchInput]); // Sync debounced query to URL useEffect(() => { if (debouncedQuery) { setSearchParams({ q: debouncedQuery }, { replace: true }); } else { setSearchParams({}, { replace: true }); } }, [debouncedQuery, setSearchParams]); useLibrary(); const { data: searchData, isLoading: searchLoading, fetchNextPage: fetchNextSearch, hasNextPage: hasNextSearch, isFetchingNextPage: fetchingNextSearch, } = useTmdbSearch(debouncedQuery); const peopleQuery = activeTab === "people" ? debouncedQuery : ""; const { data: peopleData, fetchNextPage: fetchNextPeople, hasNextPage: hasNextPeople, isFetchingNextPage: fetchingNextPeople, } = useTmdbSearchPeople(peopleQuery); // Filter entries: only movies & TV (TMDB multi-search sometimes returns "person" results) const searchEntries = useMemo(() => { const seen = new Set(); const all = searchData?.pages.flatMap((p) => p.results) ?? []; return all .filter((entry) => entry.media_type !== "person") .filter((entry) => { const key = `${entry.id}-${entry.media_type}`; if (seen.has(key)) return false; seen.add(key); return true; }); }, [searchData]); const searchPeople = useMemo(() => { const seen = new Set(); const all = peopleData?.pages.flatMap((p) => p.results) ?? []; return all.filter((person) => { if (seen.has(person.id)) return false; seen.add(person.id); return true; }); }, [peopleData]); type SpamAction = | { type: "entry_empty" } | { type: "entry_found" } | { type: "people_empty" } | { type: "people_found" } | { type: "reset_entry" } | { type: "reset_people" } | { type: "reset_all" }; // ── Anti-spam: stop auto-scroll after N consecutive empty pages ── const prevEntryCountRef = useRef(0); const prevPeopleCountRef = useRef(0); const [spam, spamDispatch] = useReducer( (state: { entry: number; people: number }, action: SpamAction) => { switch (action.type) { case "entry_empty": return { ...state, entry: state.entry + 1 }; case "entry_found": return { ...state, entry: 0 }; case "people_empty": return { ...state, people: state.people + 1 }; case "people_found": return { ...state, people: 0 }; case "reset_entry": return { ...state, entry: 0 }; case "reset_people": return { ...state, people: 0 }; case "reset_all": return { entry: 0, people: 0 }; default: return state; } }, { entry: 0, people: 0 }, ); const entryLoadMore = spam.entry >= MAX_EMPTY_PAGES; const peopleLoadMore = spam.people >= MAX_EMPTY_PAGES; // Reset streak on new query useEffect(() => { prevEntryCountRef.current = 0; prevPeopleCountRef.current = 0; spamDispatch({ type: "reset_all" }); }, [debouncedQuery]); // Detect empty entry fetches useEffect(() => { if (fetchingNextSearch || searchEntries.length === 0) return; if (searchEntries.length === prevEntryCountRef.current) { spamDispatch({ type: "entry_empty" }); } else { spamDispatch({ type: "entry_found" }); } prevEntryCountRef.current = searchEntries.length; }, [fetchingNextSearch, searchEntries.length]); // Detect empty people fetches useEffect(() => { if (fetchingNextPeople || searchPeople.length === 0) return; if (searchPeople.length === prevPeopleCountRef.current) { spamDispatch({ type: "people_empty" }); } else { spamDispatch({ type: "people_found" }); } prevPeopleCountRef.current = searchPeople.length; }, [fetchingNextPeople, searchPeople.length]); // ── Infinite scroll sentinels ── const entrySentinelRef = useRef(null); const peopleSentinelRef = useRef(null); const handleEntryIntersect = useCallback( (entries: IntersectionObserverEntry[]) => { if ( entries[0]?.isIntersecting && hasNextSearch && !fetchingNextSearch && !entryLoadMore ) { fetchNextSearch(); } }, [hasNextSearch, fetchingNextSearch, fetchNextSearch, entryLoadMore], ); const handlePeopleIntersect = useCallback( (entries: IntersectionObserverEntry[]) => { if ( entries[0]?.isIntersecting && hasNextPeople && !fetchingNextPeople && !peopleLoadMore ) { fetchNextPeople(); } }, [hasNextPeople, fetchingNextPeople, fetchNextPeople, peopleLoadMore], ); useEffect(() => { const sentinel = entrySentinelRef.current; if (!sentinel) return; const observer = new IntersectionObserver(handleEntryIntersect, { rootMargin: "200px", }); observer.observe(sentinel); return () => observer.disconnect(); }, [handleEntryIntersect]); useEffect(() => { const sentinel = peopleSentinelRef.current; if (!sentinel || activeTab !== "people") return; const observer = new IntersectionObserver(handlePeopleIntersect, { rootMargin: "200px", }); observer.observe(sentinel); return () => observer.disconnect(); }, [handlePeopleIntersect, activeTab]); const isSearching = debouncedQuery.length > 0; return (
{/* Search + Tabs row */}
setSearchInput(e.target.value)} className="pl-10" autoFocus />
{isSearching && ( setActiveTab(v as SearchTab)} > Movies & TV People )}
{isSearching ? (
{/* Movies & TV tab */} {activeTab === "entries" && ( <>

Results for “{debouncedQuery}”

{searchEntries.length === 0 && !searchLoading ? (

No results found.

) : ( <>
{searchEntries.map((entry, index) => (
))}
{/* Sentinel / Load more */}
{fetchingNextSearch ? ( ) : entryLoadMore && hasNextSearch ? ( ) : hasNextSearch ? ( Scroll for more ) : searchEntries.length > 0 ? ( All results loaded ) : null}
)} )} {/* People tab */} {activeTab === "people" && ( <>

People matching “{debouncedQuery}”

{peopleQuery && searchPeople.length === 0 && !peopleData ? (
) : searchPeople.length === 0 && peopleData ? (

No people found.

) : ( <>
{searchPeople.map((person, index) => (
{person.name .split(" ") .map((n) => n[0]) .join("") .slice(0, 2)}
{person.name} {person.known_for_department && ( {person.known_for_department} )} ))}
{/* Sentinel / Load more */}
{fetchingNextPeople ? ( ) : peopleLoadMore && hasNextPeople ? ( ) : hasNextPeople ? ( Scroll for more ) : searchPeople.length > 0 ? ( All results loaded ) : null}
)} )}
) : (
Start typing to search...
)}
); }