ProductCard.jsx 2.37 KB
import React from 'react';
import { Link } from 'react-router-dom';
import { useCart } from '../../context/CartContext';
import './product.css';

const ProductCard = ({ product }) => {
  const { addToCart } = useCart();

  const handleAddToCart = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    
    const result = await addToCart(product.id, 1);
    if (result.success) {
      // Show success message or notification
      console.log('Product added to cart');
    }
  };

  const formatPrice = (price) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD'
    }).format(price);
  };

  return (
    <div className="product-card">
      <Link to={`/products/${product.id}`} className="product-link">
        <div className="product-image">
          <img 
            src={product.imageUrl || '/images/placeholder-product.jpg'} 
            alt={product.name}
            onError={(e) => {
              e.target.src = '/images/placeholder-product.jpg';
            }}
          />
          {product.isFeatured && (
            <span className="featured-badge">Featured</span>
          )}
        </div>
        
        <div className="product-info">
          <h3 className="product-name">{product.name}</h3>
          <p className="product-sku">SKU: {product.sku}</p>
          
          <div className="product-pricing">
            <span className="product-price">{formatPrice(product.price)}</span>
            {product.comparePrice && product.comparePrice > product.price && (
              <span className="product-compare-price">
                {formatPrice(product.comparePrice)}
              </span>
            )}
          </div>

          <div className="product-stock">
            {product.availableQuantity > 0 ? (
              <span className="in-stock">
                {product.availableQuantity} in stock
              </span>
            ) : (
              <span className="out-of-stock">Out of stock</span>
            )}
          </div>
        </div>
      </Link>

      <div className="product-actions">
        <button 
          className="btn btn-primary add-to-cart-btn"
          onClick={handleAddToCart}
          disabled={product.availableQuantity === 0}
        >
          {product.availableQuantity === 0 ? 'Out of Stock' : 'Add to Cart'}
        </button>
      </div>
    </div>
  );
};

export default ProductCard;