/* Marketplace-style PDP variant (inspired by Argentine marketplace conventions)
   Distinct from main RC PDP: yellow CTA, green shipping/installments,
   3-col layout, lots of trust signals.
*/

const MarketplaceProductPage = ({ id, onNavigate, onAdd, pdp = {} }) => {
  const { PRODUCTS, CATEGORIES, ARS } = window.RC_DATA;
  const product = PRODUCTS.find((p) => p.id === id);
  const [qty, setQty] = React.useState(1);
  const [gallery, setGallery] = React.useState(0);
  const [added, setAdded] = React.useState(false);

  if (!product) return (
    <div className="container" style={{ padding: 60 }}>Producto no encontrado.</div>
  );

  const cat = CATEGORIES.find((c) => c.id === product.cat);
  const related = PRODUCTS.filter((p) => p.cat === product.cat && p.id !== product.id).slice(0, 3);
  const discount = product.was ? Math.round((product.was - product.price) / product.was * 100) : 0;
  const installments = 12;
  const installmentValue = Math.round(product.price / installments);
  const transferPrice = Math.round(product.price * 0.85);

  const handleAdd = (e) => {
    onAdd({ ...product, qty });
    setAdded(true);
    setTimeout(() => setAdded(false), 1500);
    const btn = e?.currentTarget;
    if (btn?.animate) {
      btn.animate(
        [
          { transform: 'scale(1)', offset: 0 },
          { transform: 'scale(1.3)', offset: 0.4 },
          { transform: 'scale(0.94)', offset: 0.7 },
          { transform: 'scale(1)', offset: 1 },
        ],
        { duration: 800, easing: 'cubic-bezier(.34, 1.56, .64, 1)' }
      );
    }
  };

  const imgs = product.images?.length ? product.images : [product.image];

  // Marketplace palette — light gray bg, yellow CTA, green for benefits
  const MP_GREEN = '#00A650';
  const MP_BLUE  = '#3483FA';
  const MP_YELLOW = '#FFE600';

  return (
    <div style={{ background: '#EBEBEB', minHeight: '60vh', paddingBottom: 40 }} data-pdp-style="marketplace">
      {/* Top breadcrumb */}
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '14px 20px 10px', fontSize: 13, color: '#666' }}>
        <a href="#" onClick={(e) => { e.preventDefault(); onNavigate('/'); }} style={{ color: MP_BLUE }}>Volver al listado</a>
        <span style={{ margin: '0 10px', color: '#999' }}>|</span>
        <a href="#" onClick={(e) => { e.preventDefault(); onNavigate(`/categoria/${cat?.slug || ''}`); }} style={{ color: '#666' }}>
          {cat?.name || 'Productos'}
        </a>
        <span style={{ margin: '0 6px', color: '#bbb' }}>›</span>
        <span>{product.brand}</span>
      </div>

      {/* Main card — white */}
      <div style={{
        maxWidth: 1200, margin: '0 auto',
        background: '#FFF',
        borderRadius: 6,
        boxShadow: '0 1px 2px rgba(0,0,0,0.10)',
        padding: '20px 20px 0',
      }}>
        {/* Status: condition + sales */}
        <div style={{ fontSize: 13, color: '#666', marginBottom: 6 }}>
          Nuevo  <span style={{ margin: '0 4px', color: '#bbb' }}>|</span>  +{product.sold || 222} vendidos
        </div>

        {/* 3-col grid: gallery | info | buy box */}
        <div className="mp-pdp-grid" style={{
          display: 'grid',
          gridTemplateColumns: '60px 1fr 320px',
          columnGap: 20,
          alignItems: 'start',
        }}>
          {/* Thumbs */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {imgs.slice(0, 6).map((img, i) => (
              <button key={i} onClick={() => setGallery(i)}
                onMouseEnter={() => setGallery(i)}
                style={{
                  width: 48, height: 48, padding: 0,
                  border: '2px solid ' + (gallery === i ? MP_BLUE : '#E0E0E0'),
                  borderRadius: 4, background: '#FFF',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  overflow: 'hidden', cursor: 'pointer',
                }}>
                {img ? (
                  <img src={img} alt="" style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', padding: 2 }}/>
                ) : (
                  <span style={{ fontSize: 9, color: '#999' }}>{i + 1}</span>
                )}
              </button>
            ))}
          </div>

          {/* Main image */}
          <div style={{
            background: '#FFF',
            aspectRatio: '1/1',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: 'relative', overflow: 'hidden',
          }}>
            {imgs[gallery] && (
              <img src={imgs[gallery]} alt={product.name}
                style={{ maxWidth: '85%', maxHeight: '85%', objectFit: 'contain' }}/>
            )}
            {discount > 0 && (
              <span style={{
                position: 'absolute', top: 12, left: 12,
                background: MP_GREEN, color: '#FFF',
                fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 3,
                letterSpacing: '0.02em',
              }}>{discount}% OFF</span>
            )}
          </div>

          {/* Right column: title + price + buy box */}
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {/* Title block */}
            <h1 style={{
              fontSize: 22, fontWeight: 600,
              color: '#333', lineHeight: 1.25,
              letterSpacing: '-0.005em',
              margin: 0,
            }}>{product.name}</h1>

            {/* Rating + sold */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6, fontSize: 13 }}>
              <span style={{ color: '#3483FA', fontWeight: 600 }}>{Number(product.rating || 4.7).toFixed(1)}</span>
              <span style={{ display: 'inline-flex', gap: 1, color: '#3483FA' }}>
                {[1, 2, 3, 4, 5].map((n) => (
                  <svg key={n} width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z"/>
                  </svg>
                ))}
              </span>
              <a href="#" style={{ color: '#3483FA', fontSize: 13, marginLeft: 2 }}>({product.reviews || 74})</a>
            </div>

            {/* Price */}
            <div style={{ marginTop: 18 }}>
              {product.was && (
                <div style={{ fontSize: 13, color: '#999', textDecoration: 'line-through' }}>
                  $ {product.was.toLocaleString('es-AR')}
                </div>
              )}
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span style={{ fontSize: 36, fontWeight: 300, color: '#333', letterSpacing: '-0.01em', lineHeight: 1.1 }}>
                  $ {product.price.toLocaleString('es-AR')}
                </span>
                {discount > 0 && (
                  <span style={{ fontSize: 16, color: MP_GREEN, fontWeight: 500 }}>{discount}% OFF</span>
                )}
              </div>
              <div style={{ fontSize: 14, color: MP_GREEN, marginTop: 4 }}>
                en {installments}x ${installmentValue.toLocaleString('es-AR')} sin interés
              </div>
              <a href="#" style={{ fontSize: 13, color: MP_BLUE, marginTop: 2, display: 'inline-block' }}>
                Ver los medios de pago
              </a>
            </div>

            {/* Shipping */}
            <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid #EEE' }}>
              <div style={{ fontSize: 15, color: MP_GREEN, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name="truck" size={18} strokeWidth={1.6}/>
                Envío gratis
              </div>
              <div style={{ fontSize: 13, color: '#666', marginTop: 4 }}>
                Conocé los tiempos y las formas de envío.
              </div>
              <a href="#" style={{ fontSize: 13, color: MP_BLUE, marginTop: 4, display: 'inline-block' }}>
                Calcular cuándo llega
              </a>
            </div>

            {/* Stock */}
            <div style={{ marginTop: 16, fontSize: 18, fontWeight: 600, color: '#333' }}>
              Stock disponible
            </div>
            <div style={{ fontSize: 13, color: '#666', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
              Cantidad:
              <select value={qty} onChange={(e) => setQty(Number(e.target.value))}
                style={{
                  border: '1px solid #DDD', borderRadius: 4,
                  padding: '4px 8px', fontSize: 13, background: '#FFF', cursor: 'pointer',
                }}>
                {[1, 2, 3, 4, 5, 6].map(n => <option key={n} value={n}>{n} unidad{n > 1 ? 'es' : ''}</option>)}
              </select>
              <span style={{ color: '#999' }}>(+50 disponibles)</span>
            </div>

            {/* Buttons */}
            <button style={{
              marginTop: 22, width: '100%',
              padding: '14px 16px',
              background: MP_BLUE, color: '#FFF',
              border: 'none', borderRadius: 6,
              fontSize: 16, fontWeight: 600,
              cursor: 'pointer',
            }}>
              Comprar ahora
            </button>
            <button onClick={handleAdd} className={added ? 'btn-add-zoom' : ''} style={{
              marginTop: 10, width: '100%',
              padding: '14px 16px',
              background: '#E3EDFB', color: MP_BLUE,
              border: 'none', borderRadius: 6,
              fontSize: 16, fontWeight: 600,
              cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              {added ? <><Icon name="check" size={16}/> Agregado</> : 'Agregar al carrito'}
            </button>

            {/* Vendor */}
            <div style={{ marginTop: 22, paddingTop: 16, borderTop: '1px solid #EEE', fontSize: 13, lineHeight: 1.6 }}>
              <div style={{ color: '#666' }}>
                Vendido por <a href="#" style={{ color: MP_BLUE, fontWeight: 600 }}>RC POWERCLEAN</a>
              </div>
              <div style={{ color: MP_GREEN, fontSize: 12, fontWeight: 600, marginTop: 2 }}>
                MercadoLíder Platinum
              </div>
              <div style={{ color: '#999', fontSize: 12 }}>+10mil ventas</div>
            </div>

            {/* Guarantees */}
            <div style={{ marginTop: 18, fontSize: 13, lineHeight: 1.7 }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', color: '#666' }}>
                <Icon name="rotate" size={16} strokeWidth={1.6}/>
                <span>Devolución gratis. Tenés 30 días desde que lo recibís.</span>
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', color: '#666', marginTop: 8 }}>
                <Icon name="shield" size={16} strokeWidth={1.6}/>
                <span>Compra Protegida. Recibí el producto que esperabas o te devolvemos tu dinero.</span>
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', color: '#666', marginTop: 8 }}>
                <Icon name="award" size={16} strokeWidth={1.6}/>
                <span>12 meses de garantía de fábrica.</span>
              </div>
            </div>
          </div>
        </div>

        {/* Spacer at bottom of card */}
        <div style={{ height: 20 }}/>
      </div>

      {/* Lower card: características */}
      <div style={{
        maxWidth: 1200, margin: '14px auto 0',
        background: '#FFF',
        borderRadius: 6,
        boxShadow: '0 1px 2px rgba(0,0,0,0.10)',
        padding: '28px 32px',
      }}>
        <h2 style={{ fontSize: 22, fontWeight: 600, color: '#333', margin: '0 0 18px', letterSpacing: '-0.005em' }}>
          Características del producto
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }}>
          {(() => {
            const s = product.specs || {};
            const rows = product.cat === 'hidro' ? [
              ['Motor', (s['Motor'] || 'Eléctrico universal') + ' · Monofásico 220V'],
              ['Presión', s['Presión'] || s['Bares'] || '150 bar'],
              ['Caudal', s['Caudal'] || s['Flujo'] || '450 L/h'],
              ['Potencia', s['Potencia'] || s['Power'] || '2.200 W'],
              ['Marca', product.brand || 'Powerclean'],
              ['Modelo', product.sku || product.id],
            ] : Object.entries(s).slice(0, 6);
            return rows.map(([k, v], i) => (
              <div key={k} style={{
                display: 'grid', gridTemplateColumns: '140px 1fr',
                padding: '12px 16px',
                background: i % 2 === 0 ? '#FAFAFA' : '#FFF',
                fontSize: 14,
              }}>
                <div style={{ color: '#999', fontWeight: 400 }}>{k}</div>
                <div style={{ color: '#333', fontWeight: 600 }}>{v}</div>
              </div>
            ));
          })()}
        </div>
      </div>

      {/* Description */}
      <div style={{
        maxWidth: 1200, margin: '14px auto 0',
        background: '#FFF',
        borderRadius: 6,
        boxShadow: '0 1px 2px rgba(0,0,0,0.10)',
        padding: '28px 32px',
      }}>
        <h2 style={{ fontSize: 22, fontWeight: 600, color: '#333', margin: '0 0 18px', letterSpacing: '-0.005em' }}>
          Descripción
        </h2>
        <div style={{ fontSize: 15, lineHeight: 1.6, color: '#333', maxWidth: 720 }}>
          <p style={{ margin: '0 0 14px' }}>
            <strong>{product.name}</strong> — Equipo profesional fabricado bajo estándares industriales,
            ideal para uso intensivo en talleres, lavaderos, empresas de limpieza y obras.
          </p>
          <p style={{ margin: '0 0 14px' }}>
            Motor eléctrico monofásico 220V, alta presión y caudal sostenido. Bomba con pistones
            cerámicos de alta durabilidad. Estructura reforzada y manija ergonómica para traslado.
          </p>
          <p style={{ margin: '0 0 14px' }}>
            <strong>Garantía oficial 12 meses</strong>. Servicio técnico propio en Haedo,
            con repuestos originales en stock y asesoramiento por WhatsApp.
          </p>
          <p style={{ margin: 0, color: '#666' }}>
            Envío gratis a CABA y GBA en 48hs. Al interior por Andreani o transporte a cotizar.
          </p>
        </div>
      </div>

      {/* Related */}
      <div style={{
        maxWidth: 1200, margin: '14px auto 0',
        background: '#FFF',
        borderRadius: 6,
        boxShadow: '0 1px 2px rgba(0,0,0,0.10)',
        padding: '28px 32px',
      }}>
        <h2 style={{ fontSize: 22, fontWeight: 600, color: '#333', margin: '0 0 18px', letterSpacing: '-0.005em' }}>
          Productos relacionados
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {related.map((p) => {
            const pInst = Math.round(p.price / 12);
            return (
              <a key={p.id} href="#" onClick={(e) => { e.preventDefault(); onNavigate(`/producto/${p.id}`); }}
                style={{
                  background: '#FFF', border: '1px solid #EEE', borderRadius: 6,
                  padding: 14, textDecoration: 'none', color: 'inherit',
                  display: 'flex', flexDirection: 'column',
                }}>
                <div style={{ aspectRatio: '1/1', background: '#FFF', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }}>
                  {p.image && <img src={p.image} alt="" style={{ maxWidth: '85%', maxHeight: '85%', objectFit: 'contain' }}/>}
                </div>
                <div style={{ fontSize: 18, fontWeight: 400, color: '#333', letterSpacing: '-0.005em' }}>
                  $ {p.price.toLocaleString('es-AR')}
                </div>
                <div style={{ fontSize: 13, color: MP_GREEN, marginTop: 2 }}>
                  en 12x ${pInst.toLocaleString('es-AR')} sin interés
                </div>
                <div style={{ fontSize: 13, color: MP_GREEN, fontWeight: 600, marginTop: 6 }}>
                  Envío gratis
                </div>
                <div style={{ fontSize: 13, color: '#666', marginTop: 8, lineHeight: 1.35,
                  display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                }}>
                  {p.name}
                </div>
              </a>
            );
          })}
        </div>
      </div>

      {/* Responsive */}
      <style>{`
        @media (max-width: 900px) {
          [data-pdp-style="marketplace"] .mp-pdp-grid {
            grid-template-columns: 1fr !important;
          }
        }
      `}</style>
    </div>
  );
};

Object.assign(window, { MarketplaceProductPage });
