"use client"; import { useState, useEffect, useCallback } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { Search, ArrowLeft, Loader2, Grid, List, SlidersHorizontal, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"; import { searchByName, Product, sortProducts } from "@/lib/openFoodFactsApi"; import { ProductCard } from "@/app/components/ProductCard"; import { ProductCardSkeleton } from "@/app/components/ProductCardSkeleton"; import { FilterSidebar } from "@/app/components/FilterSidebar"; import { FilterBadges } from "@/app/components/FilterBadge"; import { SortDropdown } from "@/app/components/SortDropdown"; import { useProductFilters } from "@/hooks/useProductFilters"; import { detectUserCountry } from "@/lib/geolocation"; import Link from "next/link"; export default function ResultadosPage() { const searchParams = useSearchParams(); const router = useRouter(); const query = searchParams.get("q") || ""; const countryParam = searchParams.get("country") || ""; const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); const [loadingMore, setLoadingMore] = useState(false); const [error, setError] = useState(null); const [page, setPage] = useState(1); const [hasMore, setHasMore] = useState(true); const [detectedCountry, setDetectedCountry] = useState(""); const [viewMode, setViewMode] = useState<"grid" | "list">("grid"); // Hook de filtros const { filters, updateFilters, clearFilters, hasActiveFilters, setTotalResults, setIsLoading, } = useProductFilters(); // Detectar país do usuário useEffect(() => { const detectCountry = async () => { try { const country = await detectUserCountry(true); setDetectedCountry(country.code); } catch { setDetectedCountry("br"); } }; detectCountry(); }, []); const loadProducts = useCallback( async (pageNum: number) => { try { if (pageNum === 1) { setLoading(true); } else { setLoadingMore(true); } setError(null); setIsLoading(true); const countryToUse = detectedCountry || countryParam || "br"; const result = await searchByName(query, countryToUse, pageNum, 20); // Aplicar ordenação se especificada let sortedProducts = result.products; if (filters.sortBy) { sortedProducts = sortProducts( result.products, filters.sortBy, filters.sortOrder || "asc" ); } setProducts((prevProducts) => pageNum === 1 ? sortedProducts : [...prevProducts, ...sortedProducts] ); setHasMore(result.products.length === 20); setPage(pageNum); setTotalResults(result.count || result.products.length); } catch (err) { setError( err instanceof Error ? err.message : "Erro ao buscar produtos" ); } finally { setLoading(false); setLoadingMore(false); setIsLoading(false); } }, [ query, detectedCountry, countryParam, filters.sortBy, filters.sortOrder, setIsLoading, setTotalResults, ] ); useEffect(() => { if (query) { loadProducts(1); } }, [query, countryParam, detectedCountry, loadProducts]); const handleLoadMore = useCallback(() => { loadProducts(page + 1); }, [loadProducts, page]); const handleSortChange = useCallback( (sortBy: string) => { updateFilters({ sortBy: sortBy as | "relevance" | "nutrition_grade" | "name" | "brand" | "energy" | "fat" | "sugars" | "completeness" | "with_images" | "with_nutrition" | "eco_score" | "nova_group", }); }, [updateFilters] ); if (!query) { return (

Nenhuma busca realizada

Digite um termo de busca para encontrar produtos

); } return (
{/* Header */}

Resultados para "{query}"

{!loading && products.length > 0 && (

{products.length} produto{products.length !== 1 ? "s" : ""}{" "} encontrado{products.length !== 1 ? "s" : ""} {detectedCountry && ` em ${detectedCountry}`}

)}
{/* Controles de visualização - Desktop */}
{/* Filtros Mobile */}
{/* Filtros ativos */} {hasActiveFilters && (
{ if (value) { const currentArray = (filters[key as keyof typeof filters] as string[]) || []; updateFilters({ [key]: currentArray.filter((item) => item !== value), }); } else { updateFilters({ [key]: undefined }); } }} onClearAll={clearFilters} />
)} {/* Layout principal */}
{/* Sidebar de filtros - Desktop */}
{/* Conteúdo principal */}
{/* Loading Inicial */} {loading && (
{[...Array(8)].map((_, i) => ( ))}
)} {/* Erro */} {error && !loading && (

Erro ao buscar produtos

{error}

)} {/* Sem Resultados */} {!loading && !error && products.length === 0 && (

Nenhum produto encontrado

Tente ajustar os filtros ou buscar com outros termos

{hasActiveFilters && ( )}
)} {/* Grid de Produtos */} {!loading && products.length > 0 && ( <>
{products.map((product, index) => (
))}
{/* Botão Carregar Mais */} {hasMore && (
)} {/* Contador de Resultados */} {!hasMore && products.length > 0 && (

Todos os {products.length} produto {products.length !== 1 ? "s" : ""} foram carregados

)} )}
); }