import React from 'react'; import type { FoodItem } from '../types'; import { useParams } from 'react-router-dom'; import { AlertCircle } from 'lucide-react'; import Header from '../components/Header'; import { useCart } from '../contexts/CartContext'; import { useFood } from '../contexts/FoodContext'; import CartTab from '../components/CartTab'; import './ItemDetailScreen.css'; const ItemDetailScreen: React.FC = () => { const { itemId } = useParams<{ itemId: string }>(); const { addToCart, updateQuantity, getItemQuantity } = useCart(); const { foodItems, isLoading: isGlobalLoading } = useFood(); const [fetchedItem, setFetchedItem] = React.useState(null); const [isFetching, setIsFetching] = React.useState(false); const contextItem = foodItems.find((i) => i.id === itemId); const item = contextItem || fetchedItem; React.useEffect(() => { if (!contextItem && itemId) { const fetchItem = async () => { setIsFetching(true); try { const response = await fetch(`http://${window.location.hostname}:8080/api/products/${itemId}`); if (response.ok) { const data = await response.json(); // Map backend product to FoodItem type const rawImg = data.imageData?.trim(); const finalImage = rawImg ? (rawImg.startsWith('data:') ? rawImg : `data:image/png;base64,${rawImg}`) : ''; const stallInfo = data.stalls && data.stalls.length > 0 ? data.stalls[0] : null; const mappedItem: FoodItem = { id: data.id.toString(), name: data.name, description: data.description || 'Quality food prepared with care', price: data.price || data.basePrice || 0, category: data.category, image: finalImage, isVeg: data.veg, isPopular: data.active, stock: data.stock, stallId: stallInfo?.id?.toString(), stallName: stallInfo?.name }; setFetchedItem(mappedItem); } } catch (err) { console.error('Error fetching individual product:', err); } finally { setIsFetching(false); } }; fetchItem(); } }, [itemId, contextItem]); if (isGlobalLoading || isFetching || !item) { if (isGlobalLoading || isFetching) { return (

Loading Delights...

); } return (

Item Not Found

Oops! The item you're looking for seems to have vanished.

); } const quantity = getItemQuantity(item.id); const isLimitReached = item.stock !== undefined && quantity >= item.stock && item.stock > 0; return (
{item.image ? ( {item.name} ) : (
🍲
)}
{item.isPopular && Popular} {item.stock === 0 && Sold Out}

{item.name}

R{item.price.toFixed(2)}

Description

{item.longDescription || item.description}

Category {item.category}
Dietary {item.isVeg ? 'Vegetarian' : 'Non-Vegetarian'}
Availability 0 ? 'green' : 'red'}`}> {item.stock && item.stock > 0 ? `In Stock (${item.stock} left)` : 'Out of Stock'}
{isLimitReached && (
You have reached the maximum available quantity ({item.stock}) for this item.
)}
Price R{(item.price * Math.max(1, quantity)).toFixed(2)}
{quantity === 0 ? ( ) : (
{quantity}
)}
); }; export default ItemDetailScreen;