import { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import { Heart, Trash2 } from "lucide-react"; const Favorites = () => { const [favorites, setFavorites] = useState([]); const [sortBy, setSortBy] = useState("dateAdded"); const storedUser = JSON.parse(sessionStorage.getItem("user")); function reloadPage() { const docTimestamp = new Date(performance.timing.domLoading).getTime(); const now = Date.now(); if (now > docTimestamp) { location.reload(); } } const mapCategory = (id) => { return id || "Other"; }; const removeFromFavorites = async (itemID) => { const response = await fetch( "http://localhost:3030/api/product/delFavorite", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userID: storedUser.ID, productID: itemID, }), }, ); const data = await response.json(); if (data.success) { reloadPage(); } if (!response.ok) throw new Error("Failed to remove from favorites"); }; useEffect(() => { const fetchFavorites = async () => { try { const response = await fetch( "http://localhost:3030/api/product/getFavorites", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ userID: storedUser.ID }), }, ); const data = await response.json(); const favoritesData = data.favorites; if (!Array.isArray(favoritesData)) { console.error("Expected an array but got:", favoritesData); return; } const transformed = favoritesData.map((item) => ({ id: item.ProductID, name: item.Name, price: parseFloat(item.Price), categories: [mapCategory(item.Category)], image: item.image_url || "/default-image.jpg", description: item.Description || "", seller: item.SellerName, datePosted: formatDatePosted(item.Date), dateAdded: item.Date || new Date().toISOString(), })); setFavorites(transformed); } catch (error) { console.error("Failed to fetch favorites:", error); } }; fetchFavorites(); }, []); const formatDatePosted = (dateString) => { const postedDate = new Date(dateString); const today = new Date(); const diffInMs = today - postedDate; const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24)); return `${diffInDays}d ago`; }; const sortedFavorites = [...favorites].sort((a, b) => { if (sortBy === "dateAdded") return new Date(b.dateAdded) - new Date(a.dateAdded); if (sortBy === "priceHigh") return b.price - a.price; if (sortBy === "priceLow") return a.price - b.price; return 0; }); return (
Items you save will appear here. Start browsing to add items to your favorites.
Browse Listings${product.price.toFixed(2)}
{product.categories.length > 0 && ({product.description}
Posted {product.datePosted}