// Cart full page
function CartScreen({ navigate, cart, updateQty, removeFromCart, addToCart, isMobile }) {
  const P = window.POP;
  const [coupon, setCoupon] = React.useState('');
  const [couponApplied, setCouponApplied] = React.useState(null);

  const fmt = n => n.toLocaleString('es-MX');
  const subtotal = cart.reduce((s, it) => s + it.price * it.qty, 0);
  const shipping = subtotal > 50 ? 0 : 5;
  const discount = couponApplied ? Math.round(subtotal * couponApplied.pct / 100) : 0;
  const total = Math.max(0, subtotal + shipping - discount);

  const applyCoupon = () => {
    const code = coupon.trim().toUpperCase();
    if (code === 'MAGICCELL10') setCouponApplied({ code, pct: 10 });
    else if (code === 'HOTWEEK') setCouponApplied({ code, pct: 15 });
    else setCouponApplied({ code, pct: 0, error: true });
  };

  const suggested = window.POP_PRODUCTS
    .filter(p => !cart.find(c => c.id === p.id))
    .sort((a, b) => (b.discount || 0) - (a.discount || 0))
    .slice(0, 4);

  if (cart.length === 0) {
    return (
      <div className="pop-page-in" style={{ padding: isMobile ? 24 : 64, textAlign: 'center' }}>
        <div style={{ fontSize: 80, marginBottom: 16 }}>🛍</div>
        <div style={{ fontFamily: P.display, fontSize: isMobile ? 32 : 48, letterSpacing: -1.5 }}>Tu bolsa está vacía</div>
        <div style={{ fontSize: 14, color: P.dim, marginTop: 10, maxWidth: 480, margin: '10px auto 0' }}>
          Aún no has agregado productos. Echa un vistazo a nuestras ofertas Hot Week con hasta -60%.
        </div>
        <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <PopButton variant="primary" size="lg" onClick={() => navigate('listing', { category: 'Ofertas' })}>🔥 VER OFERTAS</PopButton>
          <PopButton variant="secondary" size="lg" onClick={() => navigate('home')}>← Volver al inicio</PopButton>
        </div>
      </div>
    );
  }

  return (
    <div className="pop-page-in" style={{ padding: isMobile ? 16 : 32 }}>
      <div style={{ fontSize: 11, color: P.dim, letterSpacing: 0.5, marginBottom: 6 }}>
        <span onClick={() => navigate('home')} style={{ cursor: 'pointer', textDecoration: 'underline' }}>Inicio</span> › Carrito
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ fontFamily: P.display, fontSize: isMobile ? 32 : 48, letterSpacing: -1.5, lineHeight: 1 }}>🛒 TU BOLSA</div>
          <div style={{ fontSize: 13, color: P.dim, marginTop: 6 }}>{cart.length} producto{cart.length !== 1 ? 's' : ''} · {cart.reduce((s, it) => s + it.qty, 0)} unidades</div>
        </div>
        <span onClick={() => navigate('home')} style={{ cursor: 'pointer', borderBottom: `2px solid ${P.ink}`, paddingBottom: 2, fontSize: 13, fontWeight: 600 }}>← Seguir comprando</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.5fr 1fr', gap: isMobile ? 20 : 32 }}>
        {/* Items */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {cart.map((it, i) => (
            <div key={it.id} className="pop-fade-up" style={{
              background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14,
              padding: isMobile ? 14 : 18, boxShadow: `4px 4px 0 ${P.ink}`,
              display: 'grid', gridTemplateColumns: isMobile ? '100px 1fr' : '120px 1fr auto',
              gap: isMobile ? 14 : 18, animationDelay: `${i * 0.05}s`,
            }}>
              <div onClick={() => navigate('pdp', { id: it.id })} style={{ width: isMobile ? 100 : 120, height: isMobile ? 100 : 120, cursor: 'pointer' }}>
                <ProductImage tone={it.tone || getCategoryTone(it.category)} sku={it.sku} imageUrl={it.image_url} />
              </div>
              <div style={{ minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 10, color: P.blue, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase' }}>{it.brand}</span>
                  {it.discount && <PopBadge color={P.red}>-{it.discount}%</PopBadge>}
                </div>
                <div onClick={() => navigate('pdp', { id: it.id })} style={{ fontSize: isMobile ? 14 : 16, fontWeight: 600, lineHeight: 1.3, cursor: 'pointer' }}>{it.name}</div>
                <div style={{ fontSize: 11, color: P.dim, fontFamily: 'ui-monospace, monospace' }}>SKU: {it.sku} · En stock</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 6, flexWrap: 'wrap' }}>
                  <QtyStepper qty={it.qty} setQty={q => updateQty(it.id, q)} size="md" />
                  <button onClick={() => removeFromCart(it.id)} style={{
                    background: 'transparent', border: 'none', color: P.red, fontSize: 12,
                    fontWeight: 600, cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center', gap: 4,
                  }}>🗑 Eliminar</button>
                  <button style={{ background: 'transparent', border: 'none', color: P.dim, fontSize: 12, cursor: 'pointer', padding: 0, textDecoration: 'underline' }}>
                    ♡ Guardar para después
                  </button>
                </div>
                {isMobile && (
                  <div style={{ marginTop: 6, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <div style={{ fontSize: 11, color: P.dim }}>{it.qty} × ${fmt(it.price)}</div>
                    <div style={{ fontFamily: P.display, fontSize: 20, letterSpacing: -0.5 }}>${fmt(it.price * it.qty)}</div>
                  </div>
                )}
              </div>
              {!isMobile && (
                <div style={{ textAlign: 'right', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{ fontFamily: P.display, fontSize: 22, letterSpacing: -0.5 }}>${fmt(it.price * it.qty)}</div>
                    {it.qty > 1 && <div style={{ fontSize: 11, color: P.dim, marginTop: 2 }}>${fmt(it.price)} c/u</div>}
                    {it.oldPrice && (
                      <div style={{ fontSize: 11, color: P.green, fontWeight: 700, marginTop: 4 }}>Ahorras ${fmt((it.oldPrice - it.price) * it.qty)}</div>
                    )}
                  </div>
                </div>
              )}
            </div>
          ))}

        </div>

        {/* Summary */}
        <div style={{ position: isMobile ? 'static' : 'sticky', top: 140, height: 'fit-content', display: 'flex', flexDirection: 'column', gap: 16 }}>
          {subtotal < 50 ? (
            <div className="pop-bounce-in" style={{ background: P.yellow, border: `3px solid ${P.ink}`, borderRadius: 14, padding: 16, boxShadow: `4px 4px 0 ${P.ink}` }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>🚚 ¡Te faltan <span style={{ color: P.red }}>${fmt(50 - subtotal)}</span> para envío gratis!</div>
              <div style={{ height: 10, background: P.card, borderRadius: 999, marginTop: 10, overflow: 'hidden', border: `2px solid ${P.ink}` }}>
                <div style={{ height: '100%', background: `repeating-linear-gradient(45deg, ${P.green} 0 8px, #0a9659 8px 16px)`,
                  width: `${Math.min(100, (subtotal / 50) * 100)}%`, transition: 'width .5s cubic-bezier(.2,.8,.2,1)' }}></div>
              </div>
            </div>
          ) : (
            <div className="pop-bounce-in" style={{ background: P.green, color: P.card, border: `3px solid ${P.ink}`, borderRadius: 14, padding: 16, boxShadow: `4px 4px 0 ${P.ink}`, fontSize: 14, fontWeight: 700 }}>
              ✅ ¡Felicidades! Tu envío es <span style={{ color: P.yellow }}>GRATIS</span>.
            </div>
          )}

          <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, padding: isMobile ? 16 : 20, boxShadow: `4px 4px 0 ${P.ink}` }}>
            <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: 0.5, marginBottom: 10 }}>🎟 ¿TIENES UN CUPÓN?</div>
            <div style={{ display: 'flex', gap: 8 }}>
              <input value={coupon} onChange={e => setCoupon(e.target.value)} placeholder="Ej: HOTWEEK"
                style={{ flex: 1, padding: '10px 12px', border: `2px solid ${P.ink}`, borderRadius: 10,
                  fontFamily: 'ui-monospace, monospace', fontSize: 13, letterSpacing: 1, textTransform: 'uppercase',
                  outline: 'none', background: P.cream, boxShadow: `inset 2px 2px 0 ${P.line2}` }} />
              <PopButton variant="primary" size="md" onClick={applyCoupon}>Aplicar</PopButton>
            </div>
            {couponApplied && !couponApplied.error && (
              <div className="pop-bounce-in" style={{ marginTop: 10, padding: '8px 12px', background: P.green, color: P.card,
                border: `2px solid ${P.ink}`, borderRadius: 8, fontSize: 12, fontWeight: 600 }}>
                ✅ Cupón {couponApplied.code} aplicado · -{couponApplied.pct}%
              </div>
            )}
            {couponApplied && couponApplied.error && (
              <div className="pop-bounce-in" style={{ marginTop: 10, padding: '8px 12px', background: P.red, color: P.card,
                border: `2px solid ${P.ink}`, borderRadius: 8, fontSize: 12, fontWeight: 600 }}>
                ✗ Cupón inválido · prueba HOTWEEK o MAGICCELL10
              </div>
            )}
            <div style={{ fontSize: 10, color: P.dim, marginTop: 8 }}>Cupones de prueba: HOTWEEK (-15%) · MAGICCELL10 (-10%)</div>
          </div>

          <div style={{ background: P.cream, border: `3px solid ${P.ink}`, borderRadius: 14, padding: isMobile ? 18 : 22, boxShadow: `5px 5px 0 ${P.ink}` }}>
            <div style={{ fontFamily: P.display, fontSize: 18, letterSpacing: -0.5, marginBottom: 14,
              paddingBottom: 10, borderBottom: `2px dashed ${P.ink}` }}>RESUMEN DEL PEDIDO</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>Subtotal ({cart.length} {cart.length === 1 ? 'item' : 'items'})</span>
                <span style={{ fontWeight: 600 }}>${fmt(subtotal)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>Envío estándar</span>
                <span style={{ fontWeight: 600, color: shipping === 0 ? P.green : P.ink }}>{shipping === 0 ? '¡GRATIS!' : `$${fmt(shipping)}`}</span>
              </div>
              {discount > 0 && (
                <div style={{ display: 'flex', justifyContent: 'space-between', color: P.green }}>
                  <span>Cupón ({couponApplied.code})</span>
                  <span style={{ fontWeight: 700 }}>-${fmt(discount)}</span>
                </div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                borderTop: `2px dashed ${P.ink}`, paddingTop: 12, marginTop: 4 }}>
                <span style={{ fontFamily: P.display, fontSize: 20 }}>TOTAL</span>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: P.display, fontSize: isMobile ? 28 : 34, letterSpacing: -1.5, lineHeight: 1 }}>${fmt(total)}</div>
                  <div style={{ fontSize: 11, color: P.dim, marginTop: 2 }}>o 12 Cuotas de ${fmt(Math.round(total / 12))}</div>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 16 }}>
              <PopButton variant="dark" size="lg" full onClick={() => navigate('checkout')}>IR AL CHECKOUT →</PopButton>
            </div>
            <div style={{ marginTop: 14, padding: '10px 12px', background: P.card, border: `2px dashed ${P.line2}`,
              borderRadius: 8, fontSize: 11, color: P.ink2, textAlign: 'center', lineHeight: 1.5 }}>
              🔒 Pago seguro · datos cifrados<br />Aceptamos Visa, MasterCard, transferencia
            </div>
          </div>
        </div>
      </div>

      {/* Suggested — debajo del grid completo */}
      {suggested.length > 0 && (
        <div style={{ marginTop: isMobile ? 32 : 48 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
            <div style={{ background: P.pink, border: `2px solid ${P.ink}`, padding: '6px 12px', borderRadius: 8,
              fontFamily: P.display, fontSize: 11, letterSpacing: 1, boxShadow: `2px 2px 0 ${P.ink}` }}>🎁 SE COMPRAN JUNTOS</div>
            <div style={{ fontFamily: P.display, fontSize: isMobile ? 18 : 22, letterSpacing: -0.5 }}>Quizás necesites esto</div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4,1fr)', gap: 12 }}>
            {suggested.map(p => (
              <ProductCard key={p.id} product={p} onClick={() => navigate('pdp', { id: p.id })} onAddToCart={addToCart} compact />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.CartScreen = CartScreen;
