const ProductDetail = ({ product, onClose, onAdd }) => {
  const [selectedSize, setSelectedSize] = React.useState(null);
  const [selectedColor, setSelectedColor] = React.useState(null);
  const [imgIdx, setImgIdx] = React.useState(0);
  const [zoomed, setZoomed] = React.useState(false);
  const [hoverImg, setHoverImg] = React.useState(false);

  React.useEffect(() => {
    setImgIdx(0);
    setSelectedSize(null);
    setSelectedColor(null);
    setZoomed(false);
    setHoverImg(false);
  }, [product]);

  if (!product) return null;

  var hasSizes = product.sizes && product.sizes.length > 0;
  var hasColors = product.colors && product.colors.length > 0;
  var imgs = product.images || [];
  var canAdd = (!hasSizes || selectedSize) && (!hasColors || selectedColor);

  return ReactDOM.createPortal(
    <div style={{ position: 'fixed', inset: 0, zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      onClick={onClose}>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(6px)' }} />
      <div style={{
        position: 'relative', background: 'var(--bg)', border: '1px solid var(--border)',
        maxWidth: '680px', width: '94vw', maxHeight: '92vh', overflow: 'auto',
        WebkitOverflowScrolling: 'touch',
      }} onClick={(e) => e.stopPropagation()}>
        {imgs.length > 0 && (
          <div style={{ background: 'var(--bg-2)', width: '100%' }}>
            <div className="ib-img-wrap" style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px', minHeight: '300px', cursor: 'zoom-in' }}
              onClick={() => setZoomed(true)}
              onMouseEnter={() => setHoverImg(true)}
              onMouseLeave={() => setHoverImg(false)}>
              <img src={imgs[imgIdx]} alt={product.name} style={{ maxWidth: '100%', maxHeight: '500px', objectFit: 'contain' }} />
              <div style={{ position: 'absolute', bottom: '12px', right: '12px',
                fontFamily: 'var(--font-mono)', fontSize: '10px', color: 'var(--text-muted)',
                letterSpacing: '0.08em', textTransform: 'uppercase',
                opacity: hoverImg ? 1 : 0, transition: 'opacity .2s', pointerEvents: 'none' }}
                className="zoom-hint">
                CLICK TO ZOOM
              </div>
            </div>
            {imgs.length > 1 && (
              <div style={{ display: 'flex', gap: '8px', padding: '14px 24px', borderTop: '1px solid var(--border)', overflowX: 'auto' }}>
                {imgs.map((src, i) => (
                  <div key={i} onClick={() => setImgIdx(i)} style={{
                    width: '56px', height: '56px', flexShrink: 0,
                    border: i === imgIdx ? '2px solid var(--amber)' : '1px solid var(--border)',
                    cursor: 'pointer', overflow: 'hidden', transition: 'border .15s',
                  }}>
                    <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
        <div style={{ padding: '36px 32px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: '12px', letterSpacing: '0.1em', color: 'var(--amber-dim)', textTransform: 'uppercase' }}>
              {product.category === 'sticker' ? 'STICKER' : product.type.toUpperCase()}
              {product.kids && ' · KIDS'}
              {product.dimensions && (' · ' + product.dimensions)}
            </div>
            <div onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-muted)', fontSize: '24px', lineHeight: 1, padding: '8px', margin: '-8px', transition: 'color .15s' }}
              onMouseEnter={(e) => e.currentTarget.style.color = 'var(--amber)'}
              onMouseLeave={(e) => e.currentTarget.style.color = 'var(--text-muted)'}>
              &times;
            </div>
          </div>

          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: '36px', fontWeight: 400, color: 'var(--text)', margin: 0, lineHeight: 1.1, letterSpacing: '0.02em', animation: 'ib-glitch-chromatic 55s infinite' }}>
            {product.name}
          </h2>

          <div style={{ fontFamily: 'var(--font-mono)', fontSize: '28px', fontWeight: 700, color: 'var(--amber)', margin: '8px 0 4px' }}>
            ${product.price}
          </div>

          <p style={{ fontSize: '16px', color: 'var(--text)', lineHeight: 1.7, margin: '8px 0' }}>
            {product.description}
          </p>
          {product.detail && (
            <p style={{ fontSize: '15px', color: 'var(--text-2)', lineHeight: 1.6, margin: '0 0 8px' }}>
              {product.detail}
            </p>
          )}

          {hasSizes && (
            <div style={{ margin: '8px 0' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: '12px', color: 'var(--text-muted)', letterSpacing: '0.08em', marginBottom: '10px', textTransform: 'uppercase' }}>Size</div>
              <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                {product.sizes.map((s) => (
                  <button key={s} onClick={() => setSelectedSize(s)} style={{
                    background: selectedSize === s ? 'var(--amber)' : 'transparent',
                    color: selectedSize === s ? 'var(--bg)' : 'var(--text-2)',
                    border: '1px solid ' + (selectedSize === s ? 'var(--amber)' : 'var(--border)'),
                    padding: '8px 16px', fontFamily: 'var(--font-mono)', fontSize: '14px',
                    borderRadius: '2px', transition: 'all .15s', cursor: 'pointer',
                  }}>
                    {s}
                  </button>
                ))}
              </div>
            </div>
          )}
          {hasColors && (
            <div style={{ margin: '8px 0' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: '12px', color: 'var(--text-muted)', letterSpacing: '0.08em', marginBottom: '10px', textTransform: 'uppercase' }}>Color</div>
              <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                {product.colors.map((c) => (
                  <button key={c} onClick={() => setSelectedColor(c)} style={{
                    background: selectedColor === c ? 'var(--amber)' : 'transparent',
                    color: selectedColor === c ? 'var(--bg)' : 'var(--text-2)',
                    border: '1px solid ' + (selectedColor === c ? 'var(--amber)' : 'var(--border)'),
                    padding: '8px 16px', fontFamily: 'var(--font-mono)', fontSize: '14px',
                    borderRadius: '2px', transition: 'all .15s', cursor: 'pointer',
                  }}>
                    {c}
                  </button>
                ))}
              </div>
            </div>
          )}

          <button onClick={() => { if (canAdd) onAdd(product, 1, { sizeId: selectedSize, colorId: selectedColor }); }}
            style={{
              background: canAdd ? 'var(--amber)' : 'var(--bg-3)',
              color: canAdd ? 'var(--bg)' : 'var(--text-muted)',
              border: 'none', padding: '16px 24px',
              fontFamily: 'var(--font-mono)', fontSize: '15px', fontWeight: 700,
              letterSpacing: '0.08em', textTransform: 'uppercase',
              borderRadius: '2px', width: '100%', margin: '12px 0 16px',
              cursor: canAdd ? 'pointer' : 'default',
              animation: canAdd ? 'ib-cta-breathe 3s ease-in-out infinite' : 'none',
            }}>
            {hasSizes && !selectedSize ? 'Select a size' : (hasColors && !selectedColor ? 'Select a color' : 'Add to Cart')}
          </button>

          {product.material && <window.DetailRow label="Material">{product.material}</window.DetailRow>}
          {product.weight && <window.DetailRow label="Weight">{product.weight}</window.DetailRow>}
          {product.features && product.features.length > 0 && (
            <window.DetailRow label="Features">
              <ul style={{ margin: 0, paddingLeft: '18px' }}>
                {product.features.map((f, i) => <li key={i} style={{ marginBottom: '4px' }}>{f}</li>)}
              </ul>
            </window.DetailRow>
          )}
          {product.sourcing && <window.DetailRow label="Sourced From">{product.sourcing}</window.DetailRow>}
          {product.shipping && <window.DetailRow label="Shipping">{product.shipping}</window.DetailRow>}
          {product.made_to_order && (
            <window.DetailRow label="Production">Made to order — no pre-made inventory. Processing time 2-5 business days.</window.DetailRow>
          )}
          {product.note && <window.DetailRow label="Note">{product.note}</window.DetailRow>}
        </div>
      </div>

      {zoomed && imgs.length > 0 && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 10001, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.95)', cursor: 'zoom-out' }}
          onClick={(e) => { e.stopPropagation(); setZoomed(false); }}>
          <img src={imgs[imgIdx].replace(/\?width=\d+/, '?width=1946')} alt={product.name}
            style={{ maxWidth: '95vw', maxHeight: '95vh', objectFit: 'contain' }} />
          <div style={{ position: 'absolute', top: '16px', right: '20px', fontFamily: 'var(--font-mono)', fontSize: '12px', color: 'var(--text-muted)', letterSpacing: '0.08em' }}>
            &#x2715; ESC to close
          </div>
        </div>
      )}
    </div>,
    document.getElementById('overlays')
  );
};

window.ProductDetail = ProductDetail;
