diff --git a/marketplace/src/pages/ProductSearch.tsx b/marketplace/src/pages/ProductSearch.tsx index 71736b3..d1a6217 100644 --- a/marketplace/src/pages/ProductSearch.tsx +++ b/marketplace/src/pages/ProductSearch.tsx @@ -22,6 +22,7 @@ const ProductSearch = () => { const [maxPrice, setMaxPrice] = useState('') const [minExpiryDays, setMinExpiryDays] = useState(0) const [showAdvancedFilters, setShowAdvancedFilters] = useState(false) + const [sortBy, setSortBy] = useState<'price' | 'distance' | 'expiry'>('price') // Modal state const [selectedGroup, setSelectedGroup] = useState(null) @@ -89,9 +90,28 @@ const ProductSearch = () => { } } - // Sort by min price - return Object.values(groups).sort((a, b) => a.minPriceCents - b.minPriceCents) - }, [products, user?.id]) + // Sort based on selected option + const groupsArray = Object.values(groups) + + switch (sortBy) { + case 'price': + return groupsArray.sort((a, b) => a.minPriceCents - b.minPriceCents) + case 'distance': + return groupsArray.sort((a, b) => { + const minDistA = Math.min(...a.offers.map(o => o.distance_km)) + const minDistB = Math.min(...b.offers.map(o => o.distance_km)) + return minDistA - minDistB + }) + case 'expiry': + return groupsArray.sort((a, b) => { + const minExpiryA = Math.min(...a.offers.map(o => new Date(o.expires_at).getTime())) + const minExpiryB = Math.min(...b.offers.map(o => new Date(o.expires_at).getTime())) + return minExpiryA - minExpiryB + }) + default: + return groupsArray + } + }, [products, user?.id, sortBy]) const handleLocationSelect = (newLat: number, newLng: number) => { setLat(newLat) @@ -237,8 +257,17 @@ const ProductSearch = () => {

{loading ? 'Buscando...' : `${groupedProducts.length} medicamentos (${total} ofertas)`}

-
- Ordenado por: Menor preço +
+ Ordenar por: +