"use client"; import { useState, useEffect, useRef } from "react"; import { useRouter } from "next/navigation"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSearch, faCaretLeft, faCaretRight, } from "@fortawesome/free-solid-svg-icons"; import { search } from "@/api/searchApi"; import "./searchPage.css"; import MovieCard from "@/components/MovieCard"; import TvShowCard from "@/components/TvShowCard"; const SearchPage = () => { const [query, setQuery] = useState(""); const [results, setResults] = useState({ films: [], tv_series: [] }); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [debouncedQuery, setDebouncedQuery] = useState(""); const [loadingDelay, setLoadingDelay] = useState(null); const router = useRouter(); const timeoutRef = useRef(null); const moviesRef = useRef(null); const seriesRef = useRef(null); useEffect(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(() => { if (debouncedQuery) { handleSearch(); } }, 200); return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, [debouncedQuery]); const handleSearch = async () => { setLoading(true); setError(null); try { const data = await search(debouncedQuery); setResults(data); } catch (err) { setError("Failed to fetch search results."); } finally { if (loadingDelay) { clearTimeout(loadingDelay); } setLoadingDelay(setTimeout(() => setLoading(false), 800)); } }; const handleChange = (e) => { setQuery(e.target.value); setDebouncedQuery(e.target.value); }; const handleItemClick = (path) => { router.push(path); }; const scroll = (ref, direction) => { if (ref.current) { const scrollAmount = direction === "left" ? -400 : 400; ref.current.scrollBy({ left: scrollAmount, behavior: "smooth" }); } }; return (
{loading && (
)}
{error &&
{error}
}
{results.films.length > 0 && (

Films

    {results.films.map((film, index) => (
  • handleItemClick(`/movie/${encodeURIComponent(film)}`) } >
  • ))}
)} {results.tv_series.length > 0 && (

TV Series

    {results.tv_series.map((series, index) => (
  • handleItemClick(`/tvshow/${encodeURIComponent(series)}`) } >
  • ))}
)}
); }; export default SearchPage;