"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Search } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { detectSearchType, isValidBarcode } from "@/lib/openFoodFactsApi"; interface SearchBarProps { initialQuery?: string; className?: string; placeholder?: string; compact?: boolean; // Modo compacto para mobile } export function SearchBar({ initialQuery = "", className = "", placeholder = "Buscar produtos...", compact = false, }: SearchBarProps) { const [query, setQuery] = useState(initialQuery); const [searchType, setSearchType] = useState<"barcode" | "name" | null>(null); const router = useRouter(); // Detectar tipo de busca em tempo real useEffect(() => { const cleaned = query.replace(/\D/g, ""); // Remove tudo que não é número if (cleaned.length >= 8 && cleaned.length <= 13) { setSearchType("barcode"); } else if (query.trim()) { setSearchType("name"); } else { setSearchType(null); } }, [query]); const handleSearch = () => { if (!query.trim()) return; const type = detectSearchType(query); if (type === "barcode") { // Limpar código de barras (remover espaços/caracteres) const cleanBarcode = query.replace(/\D/g, ""); if (isValidBarcode(cleanBarcode)) { // Redirecionar para página do produto router.push(`/produto/${cleanBarcode}`); } else { // Mostrar erro de código inválido alert("Código de barras inválido. Deve ter entre 8 e 13 dígitos."); } } else { // Busca normal por nome router.push(`/resultados?q=${encodeURIComponent(query.trim())}`); } }; const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === "Enter") { handleSearch(); } }; if (compact) { return (