"use client"; import { useState, useEffect } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { Search, ArrowLeft, Loader2, Filter, 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 (error) { console.warn("Erro ao detectar país:", error); setDetectedCountry("br"); } }; detectCountry(); }, []); useEffect(() => { if (query) { loadProducts(1); } }, [query, countryParam, detectedCountry, filters]); const loadProducts = async (pageNum: number) => { try { if (pageNum === 1) { setLoading(true); } else { setLoadingMore(true); } setError(null); setIsLoading(true); const countryToUse = detectedCountry || countryParam || "br"; // Construir parâmetros de busca com filtros const searchParams = new URLSearchParams({ q: query, country: countryToUse, page: pageNum.toString(), page_size: "20", }); // Adicionar filtros à URL Object.entries(filters).forEach(([key, value]) => { if (value !== undefined && value !== null && value !== "") { if (Array.isArray(value)) { if (value.length > 0) { searchParams.set(key, value.join(",")); } } else if (typeof value === "object" && value !== null) { Object.entries(value).forEach(([rangeKey, rangeValue]) => { if (rangeValue?.min !== undefined) { searchParams.set(`${rangeKey}_min`, rangeValue.min.toString()); } if (rangeValue?.max !== undefined) { searchParams.set(`${rangeKey}_max`, rangeValue.max.toString()); } }); } else { searchParams.set(key, value.toString()); } } }); 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( pageNum === 1 ? sortedProducts : [...products, ...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); } }; const handleLoadMore = () => { loadProducts(page + 1); }; const handleSortChange = (sortBy: string) => { updateFilters({ sortBy: sortBy as any }); }; 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

)} )}
); }