// components/product-card.jsx — reusable product card

function PriceTag({ p, big, variant }) {
  const C = window.CustomerCommerce;
  const v = variant || (p.variants && p.variants[0]) || '1 kg';
  const now = C ? C.unitPrice(p.price, v) : p.price;
  const was = C ? C.compareAtPrice(p.compareAt, v) : p.compareAt;
  const off = C ? C.discountPercent(now, was) : null;
  return (
    <div className="pc__price" style={big ? { fontSize: '1.4rem' } : undefined}>
      <span className="now">{HAP.formatPrice(now)}</span>
      {was != null && was > now && <span className="was">{HAP.formatPrice(was)}</span>}
      {off != null && <span className="off">−{off}%</span>}
    </div>
  );
}

function Rating({ value, count }) {
  if (value == null || !(count > 0)) return null;
  return (
    <div className="pc__rating">
      {[1, 2, 3, 4, 5].map((i) => (
        <Icon key={i} name="star" size={12} style={{ opacity: value >= i ? 1 : 0.25 }} />
      ))}
      {count != null && <span className="count">({count})</span>}
    </div>
  );
}

function ProductCard({ p, compact }) {
  const store = useStore();
  if (p.missing) {
    return (
      <div className="pc" style={{ opacity: 0.7 }}>
        <div className="pc__media" style={{ background: 'var(--cream)' }} />
        <div className="pc__body">
          <h3 className="pc__title">Unavailable</h3>
          <p style={{ fontSize: '.82rem', color: 'var(--muted)' }}>This saved item is no longer in the catalog.</p>
          <button className="btn btn--ghost btn--sm" onClick={() => store.toggleWishlist(p.id)}>Remove</button>
        </div>
      </div>
    );
  }
  const wished = store.inWishlist(p.id);
  const C = window.CustomerCommerce;
  const stock = C ? C.stockState(p) : p.stock <= 0 ? 'out_of_stock' : 'in_stock';
  const agg = window.CustomerReviews ? window.CustomerReviews.aggregate(p.id) : { count: 0, average: null };
  const off = C ? C.discountPercent(C.unitPrice(p.price, (p.variants && p.variants[0]) || '1 kg'), C.compareAtPrice(p.compareAt, (p.variants && p.variants[0]) || '1 kg')) : null;
  const purchasable = C ? C.isPurchasable(p, 1) : p.stock > 0;

  return (
    <a className="pc" href={'#/products/' + p.slug}>
      <div className="pc__media">
        {p.image
          ? <img src={p.image} alt={p.name} loading="lazy" decoding="async"
                 style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : <image-slot id={`prod-${p.id}`} shape="rect" placeholder={p.name} style={{ background: 'var(--cream)' }}></image-slot>}

        <div className="pc__badges">
          {p.isNew && <span className="tag tag--new">New</span>}
          {off != null && <span className="tag tag--sale">−{off}%</span>}
          {stock === 'low_stock' && <span className="tag tag--soft">Low stock</span>}
          {stock === 'out_of_stock' && <span className="tag tag--out">Sold out</span>}
          {(p.variants || []).length > 1 && <span className="tag tag--soft">{(p.variants || []).length} sizes</span>}
        </div>

        <div className="pc__actions">
          <button
            type="button"
            className={'pc__act' + (wished ? ' is-active' : '')}
            title={wished ? 'Remove from wishlist' : 'Add to wishlist'}
            onClick={(e) => { e.preventDefault(); store.toggleWishlist(p.id); }}
          >
            <Icon name="heart" />
          </button>
          <button
            type="button"
            className="pc__act"
            title="Quick view"
            onClick={(e) => { e.preventDefault(); store.openModal({ kind: 'quickview', productId: p.id }); }}
          >
            <Icon name="eye" />
          </button>
        </div>

        {purchasable && (
          <button
            type="button"
            className="pc__quick"
            onClick={(e) => {
              e.preventDefault();
              store.addToCart(p.id, p.variants[0] || 'One size', 1);
              store.markViewed(p.id);
            }}
          >Quick add</button>
        )}
      </div>

      <div className="pc__body">
        <div className="pc__vendor">{p.vendor}</div>
        <h3 className="pc__title">{p.name}</h3>
        {!compact && <Rating value={agg.average} count={agg.count} />}
        <PriceTag p={p} />
      </div>
    </a>
  );
}

window.ProductCard = ProductCard;
window.PriceTag = PriceTag;
window.Rating = Rating;
