/* global React, SFIcons */
const { ChevronRight: PVChevR, ChevronLeft: PVChevL, Heart: PVHeart, Truck: PVTruck, Box: PVBox, Shield: PVShield, Check: PVCheck, Info: PVInfo } = SFIcons;
const { Button: PVBtn, StockStatus: PVStock, QuantityStepper: PVQty } = window.MADECIDesignSystem_419fb1;
const clpPV = (n) => '$' + Number(n).toLocaleString('es-CL');

const PV_GLYPHS = {
  cerveza:  <><path d="M8 22h8M9 22V9M15 22V9" /><path d="M7 9h10l-1-4H8L7 9Z" /><path d="M10 5V3h4v2" /></>,
  vino:     <><path d="M8 22h8M12 15v7" /><path d="M7 3h10l-1 6a4 4 0 0 1-8 0L7 3Z" /></>,
  agua:     <><path d="M12 3s5 6 5 10a5 5 0 0 1-10 0c0-4 5-10 5-10Z" /></>,
  bebida:   <><path d="M6 4h12l-1.2 15.2A2 2 0 0 1 14.8 21H9.2a2 2 0 0 1-2-1.8L6 4Z" /><path d="M6.4 9h11.2" /></>,
  licor:    <><path d="M9 2h6v5l2 4v9a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2v-9l2-4V2Z" /><path d="M7 13h10" /></>,
  default:  <><rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="9" cy="9" r="2" /><path d="m21 15-5-5L5 21" /></>,
};
function BigGlyph({ category }) {
  const key = (category || '').toLowerCase();
  const match = Object.keys(PV_GLYPHS).find((k) => k !== 'default' && key.includes(k)) || 'default';
  return (
    <svg width="150" height="150" viewBox="0 0 24 24" fill="none" stroke="var(--neutral-300)"
      strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round">{PV_GLYPHS[match]}</svg>
  );
}

const STOCK_LABEL = { in: 'En stock', low: 'Stock bajo', out: 'Agotado', transit: 'En reparto' };

function Spec({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, padding: '11px 0', borderBottom: '1px solid var(--border-subtle)' }}>
      <span style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-muted)' }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, color: 'var(--text-strong)', textAlign: 'right' }}>{value}</span>
    </div>
  );
}

const { ProductCard: PVCard } = window.MADECIDesignSystem_419fb1;

function ProductView({ product: p, related, onAdd, qtyEnCarrito, onView, onShop, loggedIn, onLogin }) {
  const [qty, setQty] = React.useState(1);
  const [modo, setModo] = React.useState('CJ'); // 'CJ' por caja (default) · 'UN' por unidad
  const esUn = modo === 'UN';
  const [fav, setFav] = React.useState(false);
  const [imgActiva, setImgActiva] = React.useState(0);
  // Cantidad que ya hay en el carrito de este producto (según la unidad elegida).
  const enCarroModo = qtyEnCarrito ? qtyEnCarrito(p.sku, modo) : 0;
  // El selector refleja lo que ya está en el carrito (o 1 si no está); se sincroniza al cambiar de producto o unidad.
  React.useEffect(() => { setQty(enCarroModo > 0 ? enCarroModo : 1); }, [p.id, modo, enCarroModo]);
  // Todas las fotos de la ficha: la principal + las de galería (solo acá).
  const fotos = [p.image, ...(p.galeria || [])].filter(Boolean);
  React.useEffect(() => { setImgActiva(0); }, [p.id]);
  const out = p.stockStatus === 'out';
  // Descuento por volumen (si el producto tiene escala): precio según la cantidad total de unidades.
  const rtu = p.unPorCaja || 1;
  const tieneEscala = Array.isArray(p.escalas) && p.escalas.length > 0;
  const totalUn = esUn ? qty : qty * rtu;
  const puEscala = tieneEscala ? window.MadeciAPI.precioEscala(p.escalas, totalUn) : null;
  const precioMostrado = tieneEscala ? (esUn ? puEscala : puEscala * rtu) : (esUn ? p.unitPrice : p.price);
  const precioBase = tieneEscala ? (esUn ? p.escalas[0].precio : p.escalas[0].precio * rtu) : null;
  const conDescuento = tieneEscala && precioBase != null && precioMostrado < precioBase;
  const specs = [
    ['Categoría', p.category],
    ['Marca', p.brand || '—'],
    ['Formato', p.pack],
    ['Capacidad', p.capacidad || '—'],
    ['Código', p.sku],
    ['Precio unitario', p.unitPrice ? clpPV(p.unitPrice) : '—'],
  ];
  return (
    <div className="sf-shell" style={{ maxWidth: 1280, margin: '0 auto', padding: '24px 24px 72px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)', marginBottom: 18 }}>
        <a onClick={onShop} style={{ cursor: 'pointer' }}>Catálogo</a>
        <PVChevR size={14} /> <span>{p.category}</span>
        <PVChevR size={14} /> <span style={{ color: 'var(--text-strong)' }}>{p.name}</span>
      </div>

      <div className="sf-product-cols" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'start' }}>
        {/* galería: miniaturas + imagen grande */}
        <div style={{ display: 'flex', gap: 14 }}>
          {fotos.length > 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {fotos.map((src, idx) => (
                <button key={idx} onClick={() => setImgActiva(idx)} style={{ width: 62, height: 62, flex: 'none', padding: 4, background: '#fff', border: idx === imgActiva ? '2px solid var(--madeci-red)' : '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', cursor: 'pointer' }}>
                  <img src={src} alt="" loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                </button>
              ))}
            </div>
          )}
          <div style={{ position: 'relative', flex: 1, background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', minHeight: 420, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {p.badge && (
              <span style={{ position: 'absolute', top: 16, left: 16, height: 24, padding: '0 11px', display: 'inline-flex', alignItems: 'center', background: 'var(--madeci-red)', color: '#fff', fontFamily: 'var(--font-display)', fontSize: 11.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', borderRadius: 'var(--radius-xs)' }}>{p.badge}</span>
            )}
            {fotos.length ? (
              <img src={fotos[imgActiva]} alt={p.name} style={{ maxHeight: '86%', maxWidth: '86%', objectFit: 'contain', mixBlendMode: 'multiply' }} />
            ) : (
              <BigGlyph category={p.category} />
            )}
          </div>
        </div>

        {/* info */}
        <div>
          <span className="madeci-eyebrow" style={{ color: 'var(--text-subtle)' }}>{p.category}</span>
          <h1 style={{ fontSize: 38, fontWeight: 800, letterSpacing: '-.02em', lineHeight: 1.05, margin: '8px 0 4px' }}>{p.name}</h1>
          {p.brand && <div style={{ fontFamily: 'var(--font-body)', fontSize: 16, color: 'var(--text-muted)' }}>{p.brand}</div>}

          {loggedIn && tieneEscala && (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: '#ffcf3f', color: '#6b4e00', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13, padding: '6px 12px', borderRadius: 999, marginTop: 18 }}>
              🏷️ Lleva más, ahorra más
            </div>
          )}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: tieneEscala && loggedIn ? 8 : 22 }}>
            {loggedIn ? (
              <React.Fragment>
                {conDescuento && <span style={{ fontFamily: 'var(--font-data)', fontSize: 20, color: 'var(--text-muted)', textDecoration: 'line-through' }}>{clpPV(precioBase)}</span>}
                <span style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 42, color: 'var(--text-strong)', letterSpacing: '-.01em' }}>{clpPV(precioMostrado)}</span>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-muted)' }}>/ {esUn ? 'Unidad' : p.pack}</span>
              </React.Fragment>
            ) : (
              <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--text-subtle)' }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>
                Precio exclusivo para clientes
              </span>
            )}
          </div>
          {loggedIn && !esUn && p.unitPrice && <div style={{ fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-subtle)', marginTop: 2 }}>{clpPV(p.unitPrice)} por unidad · IVA incluido</div>}

          {loggedIn && p.vendeUnidad && (
            <div style={{ display: 'flex', gap: 8, marginTop: 16, maxWidth: 320 }}>
              {[['CJ', 'Por caja', p.pack], ['UN', 'Por unidad', 'Unidad']].map(([m, t, sub]) => {
                const on = modo === m;
                return (
                  <button key={m} onClick={() => setModo(m)} style={{ flex: 1, textAlign: 'left', padding: '10px 13px', border: `1.5px solid ${on ? 'var(--madeci-red)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-sm)', background: on ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer' }}>
                    <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: on ? 'var(--madeci-red-dark)' : 'var(--text-strong)' }}>{t}</span>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-muted)' }}>{sub}</span>
                  </button>
                );
              })}
            </div>
          )}

          {loggedIn ? (
            <div style={{ display: 'flex', gap: 12, marginTop: 20, alignItems: 'center' }}>
              <PVQty value={qty} min={1} onChange={setQty} />
              <PVBtn size="lg" disabled={out} onClick={() => onAdd(p, qty, modo)} style={{ flex: 1 }}>{out ? 'Avisar disponibilidad' : (enCarroModo > 0 ? 'Actualizar carrito' : 'Agregar al carrito')}</PVBtn>
              <button onClick={() => setFav(!fav)} title="Favorito" style={{ width: 48, height: 48, flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)', background: fav ? 'var(--madeci-red-50)' : '#fff', cursor: 'pointer' }}>
                <PVHeart size={20} stroke={fav ? 'var(--madeci-red)' : 'var(--text-muted)'} style={{ fill: fav ? 'var(--madeci-red)' : 'none' }} />
              </button>
            </div>
          ) : (
            <div style={{ marginTop: 22, padding: '18px 20px', background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)' }}>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-muted)', marginBottom: 12 }}>Inicia sesión con tu cuenta comercial para ver precios mayoristas y comprar.</div>
              <PVBtn size="lg" onClick={onLogin}>Iniciar sesión</PVBtn>
            </div>
          )}

          {loggedIn && tieneEscala && (
            <div style={{ marginTop: 18, border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', overflow: 'hidden' }}>
              <div style={{ padding: '10px 14px', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13.5, background: 'var(--neutral-50)', borderBottom: '1px solid var(--border-subtle)' }}>Escalas de precio · por unidad</div>
              {p.escalas.map((t, i) => {
                const on = totalUn >= t.min && totalUn <= t.max;
                const rango = t.max >= 99999 ? `${Math.max(1, t.min)} o más unidades` : `${Math.max(1, t.min)} a ${t.max} unidades`;
                const off = p.escalas[0].precio > t.precio ? Math.round((1 - t.precio / p.escalas[0].precio) * 100) : 0;
                return (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 14px', fontFamily: 'var(--font-body)', fontSize: 14, background: on ? 'var(--status-success-50)' : 'transparent', borderBottom: i < p.escalas.length - 1 ? '1px solid var(--border-subtle)' : 'none' }}>
                    <span style={{ color: on ? 'var(--status-success)' : 'var(--text-body)', fontWeight: on ? 700 : 400 }}>{rango}</span>
                    <span><b style={{ fontFamily: 'var(--font-data)' }}>{clpPV(t.precio)}</b>{off > 0 && <span style={{ color: 'var(--status-success)', fontWeight: 700, fontSize: 12, marginLeft: 8 }}>−{off}%</span>}</span>
                  </div>
                );
              })}
            </div>
          )}

          <div style={{ display: 'flex', gap: 18, marginTop: 20, padding: '14px 16px', background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)' }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-body)' }}><PVTruck size={17} stroke="var(--madeci-red)" /> Despacho express</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--text-body)' }}><PVShield size={17} stroke="var(--madeci-red)" /> Pedido mínimo $30.000</span>
          </div>

          <h3 style={{ fontSize: 17, fontWeight: 700, margin: '30px 0 4px' }}>Ficha técnica</h3>
          <div>{specs.map(([l, v]) => <Spec key={l} label={l} value={v} />)}</div>

          <div style={{ display: 'flex', gap: 9, marginTop: 18, fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-subtle)', alignItems: 'flex-start' }}>
            <PVInfo size={15} style={{ flex: 'none', marginTop: 1 }} /> Beba con moderación · Venta exclusiva a mayores de 18 años.
          </div>
        </div>
      </div>

      {related && related.length > 0 && (
        <section style={{ marginTop: 64 }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20 }}>
            <div>
              <span className="madeci-eyebrow">También en {p.category}</span>
              <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-.015em', margin: '4px 0 0' }}>Productos relacionados</h2>
            </div>
          </div>
          <div className="sf-cols-4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 18 }}>
            {related.map((r) => (
              <div key={r.id} onClick={(e) => { if (e.target.closest('button')) return; onView(r); }} style={{ cursor: 'pointer' }}>
                <PVCard {...r} cartQty={qtyEnCarrito ? { CJ: qtyEnCarrito(r.sku, 'CJ'), UN: qtyEnCarrito(r.sku, 'UN') } : undefined} onAdd={(q, modo) => onAdd(r, q, modo)} />
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { ProductView });
