'use client' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' import { ShoppingCart, Star, Eye, X } from 'lucide-react' import Link from 'next/link' import OptimizedImage from '@/components/ui/OptimizedImage' import { motion } from 'framer-motion' import { cartManager } from '@/lib/cart' import { toast } from 'sonner' import { useRouter } from 'next/navigation' import { Product } from '@/types' import { useState, useEffect } from 'react' interface ProductReviewStats { averageRating: number totalReviews: number } interface ProductCardProps { product: Product index: number } export default function ProductCard({ product, index }: ProductCardProps) { const router = useRouter() const [isQuickViewOpen, setIsQuickViewOpen] = useState(false) const [reviewStats, setReviewStats] = useState({ averageRating: 0, totalReviews: 0 }) // Fetch review statistics for the product useEffect(() => { const fetchReviewStats = async () => { try { const response = await fetch(`/api/reviews?productId=${product.id}&limit=1000`) const data = await response.json() if (response.ok && data.reviews) { const reviews = data.reviews const totalReviews = reviews.length if (totalReviews > 0) { const sum = reviews.reduce((acc: number, review: any) => acc + review.rating, 0) const averageRating = sum / totalReviews setReviewStats({ averageRating: Math.round(averageRating * 10) / 10, // Round to 1 decimal totalReviews }) } } } catch (error) { console.error('Failed to fetch review stats:', error) } } fetchReviewStats() }, [product.id]) const getDiscountedPrice = (price: number, discount: number) => { return price - (price * discount / 100) } // Helper function to calculate per kg price const getPerKgPrice = (price: number, weight: string | null, discount: number = 0) => { if (!weight) return null // Extract numeric value from weight string (e.g., "1kg", "500g", "2.5 kg") const weightMatch = weight.toLowerCase().match(/(\d+(?:\.\d+)?)\s*(kg|g|gram|kilos?)/i) if (!weightMatch) return null const value = parseFloat(weightMatch[1]) const unit = weightMatch[2].toLowerCase() // Convert to kg let weightInKg = value if (unit.startsWith('g')) { weightInKg = value / 1000 } const finalPrice = discount > 0 ? getDiscountedPrice(price, discount) : price return Math.round(finalPrice / weightInKg) } const handleAddToCart = (e: React.MouseEvent) => { e.preventDefault() e.stopPropagation() console.log('Add to cart clicked for:', product.name) // Debug log if (product.stock === 0) { toast.error('Product is out of stock') return } try { const success = cartManager.addToCart(product, 1) if (success) { console.log('Item added successfully') // Debug log toast.success(`${product.name} added to cart!`) } else { toast.error('Not enough stock available') } } catch (error) { console.error('Error adding to cart:', error) toast.error('Failed to add to cart') } } const handleCardClick = () => { router.push(`/products/${product.slug}`) } const handleViewDetails = (e: React.MouseEvent) => { e.stopPropagation() setIsQuickViewOpen(true) } return (
{ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault() handleCardClick() } }} aria-label={`View details for ${product.name}`} >
{/* Per kg price badge - Top Left */} {getPerKgPrice(product.price, product.weight, product.discount) && ( ₹{getPerKgPrice(product.price, product.weight, product.discount)}/kg )} {/* Discount badge - Top Left, below per kg badge if both exist */} {product.discount > 0 && ( {product.discount}% OFF )} {/* Dynamic Rating Display */} {reviewStats.totalReviews > 0 ? (
{reviewStats.averageRating} ({reviewStats.totalReviews})
) : (
No reviews
)} {product.stock === 0 && (
Out of Stock
)} {product.category.name}
{product.name}

{product.name}

{product.description || 'Premium quality product from Padmaaja Rasooi Pvt. Ltd.'}
{product.discount > 0 ? ( <> ₹{getDiscountedPrice(product.price, product.discount).toFixed(2)} ₹{product.price.toFixed(2)} ) : ( ₹{product.price.toFixed(2)} )}
{/* Stock: 0 ? 'text-green-600' : 'text-red-600'}>{product.stock} */}
{/* Quick View Dialog */} {product.name}
{/* Product Image */}
{product.discount > 0 && ( {product.discount}% OFF )}
{/* Additional Images if available */} {product.images.length > 1 && (
{product.images.slice(1, 5).map((image, idx) => (
))}
)}
{/* Product Details */}

Product Details

{product.description || 'Premium quality product from Padmaaja Rasooi Pvt. Ltd.'}

{/* Category and Brand */}
Category

{product.category?.name}

Brand

{product.brand || 'Padmaaja Rasooi'}

{product.weight && (
Weight

{product.weight}

)} {product.origin && (
Origin

{product.origin}

)}
{/* Pricing */}
{product.discount > 0 ? ( <> ₹{getDiscountedPrice(product.price, product.discount).toFixed(2)} ₹{product.price.toFixed(2)} ) : ( ₹{product.price.toFixed(2)} )}
{/* Per kg price in quick view */} {getPerKgPrice(product.price, product.weight, product.discount) && (
Per kg: ₹{getPerKgPrice(product.price, product.weight, product.discount)}/kg
)} {/* Stock Status */}
Availability: 0 ? 'text-green-600' : 'text-red-600'}`}> {product.stock > 0 ? `In Stock (${product.stock} available)` : 'Out of Stock'}
{/* Action Buttons */}
{/* Dynamic Rating in Quick View */}
{[...Array(5)].map((_, i) => ( 0 && i < Math.round(reviewStats.averageRating) ? 'text-yellow-400 fill-current' : 'text-gray-300' }`} /> ))}
{reviewStats.totalReviews > 0 ? `${reviewStats.averageRating} (${reviewStats.totalReviews} reviews)` : 'No reviews yet' }
) }