Files
dps-webshop/01-frontend/src/helper/homepage/ItemCard.tsx
2025-06-16 17:22:34 +02:00

83 lines
3.7 KiB
TypeScript

import { AddShoppingCart } from "@mui/icons-material";
import { Box, Card, CardActionArea, CardContent, CardMedia, IconButton, Paper, Rating, Typography } from "@mui/material";
import { useState } from "react";
import { useTranslation } from 'react-i18next';
import { useNavigate } from "react-router-dom";
import ItemWithImage from "../../components/Item";
import { useBasket } from "../BasketProvider";
import "../helper.css";
export default function ItemCard({ item }: { item: ItemWithImage }) {
const { t } = useTranslation();
const navigate = useNavigate()
const { addToBasket } = useBasket();
const handleAddToCart = () => {
addToBasket(item, 1);
console.log(`Added ${1} of ${item.name} to basket`);
};
const handleClick = () => {
navigate(`/product/${item.id}`, { state: { item } });
}
const [imageUrl] = useState<string>(item.image || "/src/assets/default.jpg"); // Fallback-Bild
return (
<Paper elevation={4}>
<Card sx={{height: "100%", width: "100%" }}>
<CardActionArea onClick={handleClick} sx={{ height: "100%" }} component="div">
<CardMedia
component="img"
height="140"
image={imageUrl}
alt={item.name}
onError={(event) => {
event.currentTarget.src = "/src/assets/default.jpg"; // Standardbild setzen
}}
sx={{
objectFit: "contain", // Bild wird skaliert, um vollständig sichtbar zu sein
maxWidth: "100%", // Begrenze die maximale Breite auf den Container
maxHeight: "100%", // Begrenze die maximale Höhe auf den Container
}}
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{item.name}
</Typography>
<Rating name="half-rating" readOnly defaultValue={item.rating /2} precision={0.5} />
<Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
<Typography variant="body2" sx={{ color: 'text.secondary' }} className="item-description">
{(item.price100 / 100 * (1 - item.discount100 / 100)).toFixed(2)}
</Typography>
<IconButton
aria-label={t('addToCart')}
onClick={(event) => {
event.stopPropagation();
handleAddToCart();
}}
>
<AddShoppingCart />
</IconButton>
</Box>
{item.stock > 10 ? (
<Typography variant="body2">
{t('inStock')}
</Typography>
) : item.stock > 0 ? (
<Typography variant="body2" sx={{ color: 'orange' }}>
{t('almostSoldOut')}
</Typography>
) : (
<Typography variant="body2" sx={{ color: 'red' }}>
{t('outOfStock')}
</Typography>
)}
</CardContent>
</CardActionArea>
</Card>
</Paper>
)
}