/* PDP — product detail: image well, info column, reviews. */
function SF_PDP({ go, id, addToCart, wish, toggleWish }) {
  const { PriceTag, StarRating, TrustBadge, Chip, QuantityStepper, Button, ProductCard } = window.SS;
  const product = window.SS_PRODUCTS.find((p) => p.id === id) || window.SS_PRODUCTS[0];
  const similar = window.SS_PRODUCTS.filter((p) => p.category === product.category && p.id !== product.id).slice(0, 4);
  const gallery = (product.images && product.images.length) ? product.images : [product.image];
  const [qty, setQty] = React.useState(1);
  const [added, setAdded] = React.useState(false);
  const [shot, setShot] = React.useState(0);
  const reviews = window.SS_REVIEWS;

  React.useEffect(() => { setShot(0); }, [id]);
  React.useEffect(() => {
    // Warm the browser cache for every shot in this product's gallery so switching
    // images via the arrows is instant instead of waiting on a fresh network fetch.
    gallery.forEach((src) => { const im = new Image(); im.src = src; });
  }, [gallery]);
  const prevShot = () => setShot((s) => (s - 1 + gallery.length) % gallery.length);
  const nextShot = () => setShot((s) => (s + 1) % gallery.length);
  const arrowBtnStyle = {
    all: 'unset', cursor: 'pointer', width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
    borderRadius: '50%', background: 'var(--sf-surface-raised)', boxShadow: 'var(--sf-shadow)', color: 'var(--sf-text)', fontSize: 15,
  };

  const eyebrow = { fontSize: 11, fontWeight: 500, letterSpacing: '.2em', textTransform: 'uppercase', color: 'var(--sf-text-muted)' };

  return (
    <div className="sf-maxw sf-sticky-page-pad sf-pdp-page" style={{ paddingTop: 44, paddingBottom: 96 }}>
      <div className="sf-hide-mobile" style={{ fontSize: 12, color: 'var(--sf-text-faint)', marginBottom: 24 }}>
        <span style={{ cursor: 'pointer' }} onClick={() => go('home')}>Home</span> · <span style={{ cursor: 'pointer', textTransform: 'capitalize' }} onClick={() => go('listing', product.category)}>{product.category}</span> · <span style={{ color: 'var(--sf-text-muted)' }}>{product.name}</span>
      </div>

      <div className="sf-pdp-cols" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56 }}>
        <div>
          <div className="sf-pdp-image" style={{ position: 'relative', borderRadius: 'var(--sf-radius-lg)', overflow: 'hidden', background: 'var(--sf-well)', aspectRatio: '1/1' }}>
            {product.badge && <span style={{ position: 'absolute', top: 16, left: 16, zIndex: 1, padding: '6px 12px', borderRadius: 'var(--sf-radius-pill)', background: 'var(--sf-gold)', color: 'var(--color-ink)', fontSize: 10.5, fontWeight: 500, letterSpacing: '.14em' }}>{product.badge}</span>}
            <img key={shot} src={gallery[shot]} alt={product.name} decoding="async" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', animation: 'sfShotFade 160ms ease' }} />
          </div>
          {gallery.length > 1 && (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 18, marginTop: 16 }}>
              <button aria-label="Previous image" onClick={prevShot} style={arrowBtnStyle}>‹</button>
              <div style={{ display: 'flex', gap: 7 }}>
                {gallery.map((_, i) => (
                  <span key={i} onClick={() => setShot(i)} style={{
                    width: 6, height: 6, borderRadius: '50%', cursor: 'pointer',
                    background: i === shot ? 'var(--sf-gold-hi)' : 'var(--sf-border)',
                  }} />
                ))}
              </div>
              <button aria-label="Next image" onClick={nextShot} style={arrowBtnStyle}>›</button>
            </div>
          )}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={eyebrow}>{product.material}</div>
          <div className="sf-pdp-title" style={{ fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 600, color: 'var(--sf-text)', lineHeight: 1.1 }}>{product.name}</div>
          <StarRating value={product.rating} count={product.ratingCount} size={12} />
          <PriceTag price={product.price} compareAt={product.compareAt} size="lg" />

          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 4 }}>
            <Chip selected>{product.gemstone}</Chip>
            <Chip>{product.occasion}</Chip>
          </div>

          <div style={{ fontSize: 13.5, fontWeight: 300, lineHeight: 1.6, color: 'var(--sf-text-muted)', maxWidth: 440 }}>
            {product.description || `Handpicked statement jewellery — ${product.material.toLowerCase()} finish with ${product.gemstone.toLowerCase()} detailing.`} Ships in {window.SS_SITE.brandName}'s signature gift-ready packaging.
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 8 }} className="sf-hide-mobile">
            <QuantityStepper value={qty} onChange={setQty} />
            <Button variant="gold" size="lg" style={{ flex: 1 }} onClick={() => { addToCart(product.id, qty); setAdded(true); setTimeout(() => setAdded(false), 1800); }}>
              {added ? 'ADDED ✓' : 'ADD TO BAG'}
            </Button>
            <button onClick={() => toggleWish(product.id)} aria-label="Wishlist" style={{ all: 'unset', cursor: 'pointer', width: 52, height: 52, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: '50%', boxShadow: 'inset 0 0 0 1px var(--sf-border)', color: wish[product.id] ? 'var(--sf-sale)' : 'var(--sf-text-muted)', fontSize: 19 }}>
              {wish[product.id] ? '♥' : '♡'}
            </button>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 12, paddingTop: 24, borderTop: '1px solid var(--sf-border-soft)' }}>
            <TrustBadge title="100% Authentic" detail="Every piece checked before it ships." />
            <TrustBadge title="7-Day Easy Returns" detail="Not the one? Send it back, no questions." />
            <TrustBadge title="Free Shipping ₹999+" detail="Delivered pan-India in 3–5 days." />
          </div>
        </div>
      </div>

      <div style={{ marginTop: 80 }}>
        <div style={{ ...eyebrow, color: 'var(--sf-gold-hi)' }}>REVIEWS</div>
        <div className="sf-grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginTop: 20 }}>
          {reviews.map((r) => (
            <div key={r.name} style={{ background: 'var(--sf-surface)', border: '1px solid var(--sf-border-soft)', borderRadius: 'var(--sf-radius)', padding: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <StarRating value={r.rating} />
              <div style={{ fontSize: 13.5, fontWeight: 300, lineHeight: 1.55, color: 'var(--sf-text-muted)' }}>&ldquo;{r.text}&rdquo;</div>
              <div style={{ fontSize: 12, fontWeight: 500, letterSpacing: '.08em', color: 'var(--sf-text)', marginTop: 4 }}>{r.name}</div>
            </div>
          ))}
        </div>
      </div>

      {similar.length > 0 && (
        <div style={{ marginTop: 80 }}>
          <div style={{ ...eyebrow, color: 'var(--sf-gold-hi)' }}>YOU MAY ALSO LIKE</div>
          <div className="sf-grid-4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18, marginTop: 20 }}>
            {similar.map((p) => (
              <ProductCard key={p.id} {...p} wished={!!wish[p.id]} onWish={() => toggleWish(p.id)} onQuickView={() => go('pdp', p.id)} />
            ))}
          </div>
        </div>
      )}

      <div className="sf-sticky-bar" style={{
        alignItems: 'center', gap: 12, padding: '12px 16px', paddingBottom: 'calc(12px + env(safe-area-inset-bottom))',
        background: 'var(--sf-surface-raised)', borderTop: '1px solid var(--sf-border)', boxShadow: 'var(--sf-shadow)',
      }}>
        <QuantityStepper value={qty} onChange={setQty} />
        <Button variant="gold" size="lg" style={{ flex: 1 }} onClick={() => { addToCart(product.id, qty); setAdded(true); setTimeout(() => setAdded(false), 1800); }}>
          {added ? 'ADDED ✓' : 'ADD TO BAG'}
        </Button>
      </div>
    </div>
  );
}
window.SF_PDP = SF_PDP;
