// Campo de formulario — definido FUERA del componente para evitar remount en cada render
function CheckoutField({ label, value, onChange, type = 'text', placeholder, col = 12, error, required = false, isMobile }) {
  const P = window.POP;
  return (
    <div style={{ gridColumn: `span ${isMobile ? 12 : col}`, display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label style={{ fontFamily: P.display, fontSize: 11, letterSpacing: 1 }}>
        {label}{required && <span style={{ color: P.red, marginLeft: 3 }}>*</span>}
      </label>
      <input type={type} value={value} onChange={onChange} placeholder={placeholder}
        style={{ padding: '12px 14px', border: `2px solid ${error ? P.red : P.ink}`, borderRadius: 10, fontFamily: P.font, fontSize: 14,
          outline: 'none', background: error ? '#fff5f5' : P.card,
          boxShadow: `inset 2px 2px 0 ${error ? '#ffd0d0' : P.line2}`,
          transition: 'border-color .15s, background .15s' }} />
      {error && (
        <div style={{ fontSize: 11, color: P.red, fontWeight: 600, marginTop: -2 }}>✗ {error}</div>
      )}
    </div>
  );
}

// Checkout — 3 steps (Datos / Envío / Pago) + Confirmación
function CheckoutScreen({ navigate, cart, isMobile, onComplete, user }) {
  const P = window.POP;
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    email: user?.email || '', name: user?.name || '', phone: '',
    address: '', city: '', zip: '', country: 'Uruguay',
    shipMethod: 'standard', payMethod: 'mercadopago',
  });

  const fmt = n => n.toLocaleString('es-UY');
  const subtotal = cart.reduce((s, it) => s + it.price * it.qty, 0);
  const shipCost = form.shipMethod === 'express' ? 10 : (subtotal > 50 ? 0 : 5);
  const [errors, setErrors] = React.useState({});
  const setField = k => e => {
    setForm(prev => ({ ...prev, [k]: e.target?.value ?? e }));
    setErrors(prev => ({ ...prev, [k]: '' }));
  };

  const [payLoading, setPayLoading] = React.useState(false);
  const [payError, setPayError] = React.useState('');

  // ── Cupones ───────────────────────────────────────────────────
  const [couponCode, setCouponCode] = React.useState('');
  const [couponData, setCouponData] = React.useState(null);   // { code, type, value, discount, label }
  const [couponLoading, setCouponLoading] = React.useState(false);
  const [couponError, setCouponError] = React.useState('');

  const couponDiscount = couponData
    ? (couponData.type === 'percent' ? Math.round(subtotal * couponData.value / 100) : Math.min(couponData.value, subtotal))
    : 0;
  const total = subtotal + shipCost - couponDiscount;

  const applyCoupon = async () => {
    const code = couponCode.trim().toUpperCase();
    if (!code) return;
    setCouponLoading(true);
    setCouponError('');
    try {
      const res = await fetch('/api/validate-coupon', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code, subtotal }),
      });
      const data = await res.json();
      if (!res.ok) { setCouponError(data.error || 'Código inválido'); setCouponData(null); }
      else { setCouponData(data); setCouponError(''); }
    } catch { setCouponError('Error al validar el cupón'); }
    setCouponLoading(false);
  };

  const removeCoupon = () => { setCouponData(null); setCouponCode(''); setCouponError(''); };

  const steps = [{ n: 1, label: 'Datos', icon: '👤' }, { n: 2, label: 'Envío', icon: '🚚' }, { n: 3, label: 'Pago', icon: '💳' }];
  const prev = () => step > 1 ? setStep(step - 1) : navigate('cart');

  const handlePayment = async () => {
    setPayLoading(true);
    setPayError('');
    try {
      // 1 — Obtener userId si está autenticado
      let userId = null;
      if (window.sb) {
        const { data: { user: authUser } } = await window.sb.auth.getUser();
        userId = authUser?.id || null;
      }

      // 2 — Crear pedido vía API server-side (bypasea RLS con service role)
      const orderRes = await fetch('/api/create-order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          cart,
          subtotal,
          shipping: shipCost,
          discount: couponDiscount,
          total,
          couponCode: couponData?.code || null,
          userId,
          payer: { name: form.name, email: form.email, phone: form.phone, address: form.address, city: form.city, zip: form.zip },
        }),
      });
      if (!orderRes.ok) {
        const err = await orderRes.json();
        throw new Error(err.error || 'Error al crear el pedido');
      }
      const { orderId } = await orderRes.json();

      // Redimir cupón (fire & forget)
      if (couponData?.code) {
        fetch('/api/validate-coupon', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ code: couponData.code, subtotal, redeem: true, orderId }),
        }).catch(() => {});
      }

      // 3 — Crear preferencia en MercadoPago
      const res = await fetch('/api/mp-preference', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: cart, shipping: shipCost, orderId, payer: { name: form.name, email: form.email, phone: form.phone } }),
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || 'Error al crear preferencia de pago');
      }
      const { initPoint, sandboxInitPoint } = await res.json();
      const cfg = window.VOLTIO_CONFIG || {};
      // Usar sandbox si la public key es de prueba
      const isSandbox = cfg.mpPublicKey && cfg.mpPublicKey.startsWith('TEST-');
      // Guardar datos del comprador para la pantalla de éxito
      localStorage.setItem('voltio-last-payer', JSON.stringify({
        name: form.name, email: form.email,
        address: [form.address, form.city].filter(Boolean).join(', '),
      }));
      window.location.href = isSandbox ? sandboxInitPoint : initPoint;

    } catch (err) {
      console.error('[checkout]', err);
      // Si la API no está configurada, caer en modo demo
      if (err.message.includes('Failed to fetch') || err.message.includes('mp-preference')) {
        onComplete();
      } else {
        setPayError(err.message);
        setPayLoading(false);
      }
    }
  };

  const validateStep1 = () => {
    const e = {};
    if (!form.email.trim()) e.email = 'El email es obligatorio';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = 'Ingresá un email válido';
    if (!form.name.trim()) e.name = 'El nombre es obligatorio';
    if (!form.phone.trim()) e.phone = 'El teléfono es obligatorio';
    return e;
  };

  const validateStep2 = () => {
    const e = {};
    if (!form.address.trim()) e.address = 'La dirección es obligatoria';
    if (!form.city.trim()) e.city = 'La ciudad es obligatoria';
    if (!form.zip.trim()) e.zip = 'El código postal es obligatorio';
    return e;
  };

  const next = () => {
    if (step === 1) {
      const e = validateStep1();
      setErrors(e);
      if (Object.keys(e).length > 0) return;
    }
    if (step === 2) {
      const e = validateStep2();
      setErrors(e);
      if (Object.keys(e).length > 0) return;
    }
    step < 3 ? setStep(step + 1) : handlePayment();
  };

  if (cart.length === 0) {
    return (
      <div className="pop-page-in" style={{ padding: isMobile ? 24 : 64, textAlign: 'center' }}>
        <div style={{ fontSize: 64 }}>🛒</div>
        <div style={{ fontFamily: P.display, fontSize: 32, marginTop: 14 }}>Nada para procesar</div>
        <div style={{ fontSize: 13, color: P.dim, marginTop: 6 }}>Tu bolsa está vacía.</div>
        <div style={{ marginTop: 20 }}>
          <PopButton variant="primary" size="lg" onClick={() => navigate('home')}>Volver al inicio</PopButton>
        </div>
      </div>
    );
  }


  return (
    <div className="pop-page-in" style={{ padding: isMobile ? 16 : 32 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 24, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ fontSize: 11, color: P.dim, letterSpacing: 0.5, marginBottom: 6 }}>
            <span onClick={() => navigate('cart')} style={{ cursor: 'pointer', textDecoration: 'underline' }}>Carrito</span> › Checkout
          </div>
          <div style={{ fontFamily: P.display, fontSize: isMobile ? 28 : 44, letterSpacing: -1.5, lineHeight: 1 }}>💳 CHECKOUT</div>
        </div>
        <div style={{ fontSize: 12, color: P.dim }}>🔒 Pago 100% seguro · datos cifrados</div>
      </div>

      {/* Stepper */}
      <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 6 : 14, marginBottom: isMobile ? 24 : 32,
        background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, padding: isMobile ? 12 : 16,
        boxShadow: `4px 4px 0 ${P.ink}`, overflowX: 'auto' }}>
        {steps.map((s, i) => (
          <React.Fragment key={s.n}>
            <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 6 : 10, opacity: step >= s.n ? 1 : 0.4, transition: 'opacity .3s', flexShrink: 0 }}>
              <div style={{
                width: isMobile ? 32 : 40, height: isMobile ? 32 : 40, borderRadius: '50%',
                background: step > s.n ? P.green : step === s.n ? P.yellow : P.cream,
                color: step > s.n ? P.card : P.ink,
                border: `2px solid ${P.ink}`,
                boxShadow: step === s.n ? `3px 3px 0 ${P.ink}` : 'none',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: P.display, fontSize: isMobile ? 14 : 16, letterSpacing: -0.5,
                transition: 'all .3s cubic-bezier(.3,1.4,.5,1)',
              }}>{step > s.n ? '✓' : s.n}</div>
              <div>
                <div style={{ fontFamily: P.display, fontSize: isMobile ? 12 : 14, letterSpacing: -0.5 }}>{s.label.toUpperCase()}</div>
                {!isMobile && <div style={{ fontSize: 10, color: P.dim, marginTop: 2 }}>Paso {s.n} de 3</div>}
              </div>
            </div>
            {i < steps.length - 1 && (
              <div style={{ flex: 1, height: 3,
                background: step > s.n ? `repeating-linear-gradient(90deg, ${P.green} 0 8px, transparent 8px 12px)` : P.line2,
                borderRadius: 999, minWidth: isMobile ? 20 : 60, transition: 'background .4s' }}></div>
            )}
          </React.Fragment>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.5fr 1fr', gap: isMobile ? 20 : 32 }}>
        {/* Form */}
        <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, padding: isMobile ? 18 : 28, boxShadow: `4px 4px 0 ${P.ink}`, minHeight: 400 }}>

          {step === 1 && (
            <div className="pop-page-in" key="step1">
              <div style={{ fontFamily: P.display, fontSize: 22, letterSpacing: -1, marginBottom: 18 }}>👤 TUS DATOS</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12,1fr)', gap: 14 }}>
                <CheckoutField isMobile={isMobile} label="EMAIL" value={form.email} onChange={setField('email')} type="email" col={12} required error={errors.email} />
                <CheckoutField isMobile={isMobile} label="NOMBRE COMPLETO" value={form.name} onChange={setField('name')} col={12} required error={errors.name} />
                <CheckoutField isMobile={isMobile} label="TELÉFONO" value={form.phone} onChange={setField('phone')} col={6} required error={errors.phone} />
                <CheckoutField isMobile={isMobile} label="PAÍS" value={form.country} onChange={setField('country')} col={6} />
              </div>
              <div style={{ marginTop: 18, padding: 14, background: P.cream, border: `2px dashed ${P.line2}`, borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
                <input type="checkbox" defaultChecked style={{ width: 18, height: 18, accentColor: P.ink }} />
                <span style={{ fontSize: 12 }}>Quiero recibir ofertas exclusivas y descuentos por email 📧</span>
              </div>
              <div style={{ marginTop: 14, padding: 14, background: P.yellow, border: `2px solid ${P.ink}`, borderRadius: 10, boxShadow: `3px 3px 0 ${P.ink}`, display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ fontSize: 22 }}>⚡</div>
                <div style={{ flex: 1, fontSize: 12, fontWeight: 600, lineHeight: 1.4 }}>
                  ¿Ya tienes cuenta? <span style={{ textDecoration: 'underline', cursor: 'pointer' }}>Inicia sesión</span> para autocompletar tus datos.
                </div>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="pop-page-in" key="step2">
              <div style={{ fontFamily: P.display, fontSize: 22, letterSpacing: -1, marginBottom: 18 }}>🚚 DIRECCIÓN DE ENVÍO</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12,1fr)', gap: 14 }}>
                <CheckoutField isMobile={isMobile} label="DIRECCIÓN" value={form.address} onChange={setField('address')} col={12} required error={errors.address} />
                <CheckoutField isMobile={isMobile} label="CIUDAD" value={form.city} onChange={setField('city')} col={7} required error={errors.city} />
                <CheckoutField isMobile={isMobile} label="C.P." value={form.zip} onChange={setField('zip')} col={5} required error={errors.zip} />
              </div>
              <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: -0.5, marginTop: 24, marginBottom: 12 }}>MÉTODO DE ENVÍO</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[
                  { id: 'standard', icon: '📦', name: 'Estándar', sub: '2–4 días hábiles', price: subtotal > 50 ? 0 : 5, badge: 'Más popular' },
                  { id: 'express',  icon: '⚡', name: 'Express',  sub: '24h en Montevideo', price: 10, badge: 'Más rápido' },
                  { id: 'pickup',   icon: '🏪', name: 'Recoger en sucursal', sub: 'Listo en 2h · 4 sucursales', price: 0, badge: 'GRATIS' },
                ].map(s => (
                  <label key={s.id} onClick={() => setForm({ ...form, shipMethod: s.id })} className="pop-press" style={{
                    display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px',
                    background: form.shipMethod === s.id ? P.yellow : P.cream,
                    border: `2px solid ${P.ink}`, borderRadius: 12, cursor: 'pointer',
                    boxShadow: form.shipMethod === s.id ? `3px 3px 0 ${P.ink}` : 'none',
                  }}>
                    <input type="radio" checked={form.shipMethod === s.id} onChange={() => {}} style={{ width: 20, height: 20, accentColor: P.ink }} />
                    <span style={{ fontSize: 26 }}>{s.icon}</span>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                        <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: -0.5 }}>{s.name.toUpperCase()}</div>
                        <PopBadge color={s.id === 'standard' ? P.blue : s.id === 'express' ? P.red : P.green}>{s.badge}</PopBadge>
                      </div>
                      <div style={{ fontSize: 12, color: P.ink2, marginTop: 2 }}>{s.sub}</div>
                    </div>
                    <div style={{ fontFamily: P.display, fontSize: 16, letterSpacing: -0.5, color: s.price === 0 ? P.green : P.ink }}>
                      {s.price === 0 ? '¡GRATIS!' : `$${fmt(s.price)}`}
                    </div>
                  </label>
                ))}
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="pop-page-in" key="step3">
              <div style={{ fontFamily: P.display, fontSize: 22, letterSpacing: -1, marginBottom: 18 }}>💳 MÉTODO DE PAGO</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24 }}>
                {[
                  { id: 'mercadopago', icon: '💙', name: 'Mercado Pago',        sub: 'Serás redirigido a MercadoPago para completar el pago de forma segura.' },
                  { id: 'transfer',   icon: '🏦', name: 'Transferencia',        sub: 'Recibirás los datos de cuenta y referencia por email.' },
                  { id: 'cash',       icon: '💵', name: 'Efectivo en mostrador', sub: 'Pagá cuando retirás el pedido en nuestra sucursal.' },
                ].map(m => (
                  <label key={m.id} onClick={() => setForm({ ...form, payMethod: m.id })} className="pop-press" style={{
                    display: 'flex', alignItems: 'center', gap: 14, padding: '16px 18px',
                    background: form.payMethod === m.id ? P.yellow : P.cream,
                    border: `2px solid ${P.ink}`, borderRadius: 12, cursor: 'pointer',
                    boxShadow: form.payMethod === m.id ? `3px 3px 0 ${P.ink}` : 'none',
                    transition: 'background .15s',
                  }}>
                    <input type="radio" checked={form.payMethod === m.id} onChange={() => {}} style={{ width: 18, height: 18, accentColor: P.ink, flexShrink: 0 }} />
                    <span style={{ fontSize: 28, flexShrink: 0 }}>{m.icon}</span>
                    <div>
                      <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: -0.5 }}>{m.name.toUpperCase()}</div>
                      <div style={{ fontSize: 12, color: P.ink2, marginTop: 3, lineHeight: 1.4 }}>{m.sub}</div>
                    </div>
                  </label>
                ))}
              </div>
            </div>
          )}

          {payError && (
            <div className="pop-bounce-in" style={{ marginTop: 16, padding: '10px 14px', background: P.red, color: P.card,
              border: `2px solid ${P.ink}`, borderRadius: 8, fontSize: 12, fontWeight: 600 }}>
              ✗ {payError}
            </div>
          )}
          <div style={{ display: 'flex', flexDirection: isMobile && step === 3 ? 'column-reverse' : 'row', gap: 10, marginTop: 28, justifyContent: 'space-between', flexWrap: 'wrap' }}>
            <PopButton variant="secondary" size="md" onClick={prev}>← {step === 1 ? 'Volver al carrito' : 'Atrás'}</PopButton>
            <PopButton variant="dark" size={isMobile ? 'md' : 'lg'} onClick={next} style={isMobile && step === 3 ? { width: '100%' } : {}}>
              {step < 3 ? 'Continuar →' : payLoading ? '⚡ Procesando...' : `CONFIRMAR PEDIDO · $${fmt(total)}`}
            </PopButton>
          </div>
        </div>

        {/* Order summary */}
        <div style={{ position: isMobile ? 'static' : 'sticky', top: 140, height: 'fit-content' }}>
          <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}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span>TU PEDIDO</span>
              <span style={{ fontSize: 11, color: P.dim, fontFamily: P.font }}>{cart.length} items</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 240, overflowY: 'auto', marginBottom: 14 }}>
              {cart.map(it => (
                <div key={it.id} style={{ display: 'grid', gridTemplateColumns: '48px 1fr auto', gap: 10, alignItems: 'center' }}>
                  <div style={{ width: 48, height: 48, position: 'relative' }}>
                    <ProductImage tone={it.tone || getCategoryTone(it.category)} sku={it.sku} imageUrl={it.image_url} />
                    <div style={{ position: 'absolute', top: -6, right: -6, background: P.ink, color: '#ffffff',
                      width: 20, height: 20, borderRadius: '50%', border: `2px solid ${P.card}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700 }}>{it.qty}</div>
                  </div>
                  <div style={{ minWidth: 0, fontSize: 12, fontWeight: 600, lineHeight: 1.3,
                    display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{it.name}</div>
                  <div style={{ fontFamily: P.display, fontSize: 13, letterSpacing: -0.5, whiteSpace: 'nowrap' }}>${fmt(it.price * it.qty)}</div>
                </div>
              ))}
            </div>
            {/* ── Campo de cupón ── */}
            <div style={{ marginBottom: 14, paddingBottom: 14, borderBottom: `2px dashed ${P.ink}` }}>
              {couponData ? (
                <div className="pop-bounce-in" style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  background: '#d4f5e2', border: `2px solid ${P.green}`, borderRadius: 10, padding: '10px 12px',
                }}>
                  <div>
                    <div style={{ fontFamily: P.display, fontSize: 10, letterSpacing: 1, color: P.green }}>✓ CUPÓN APLICADO</div>
                    <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 13, fontWeight: 700, marginTop: 2 }}>{couponData.code}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ fontFamily: P.display, fontSize: 15, color: P.green, letterSpacing: -0.5 }}>{couponData.label}</span>
                    <button onClick={removeCoupon} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 18, color: P.dim, lineHeight: 1, padding: 0 }}>×</button>
                  </div>
                </div>
              ) : (
                <div>
                  <div style={{ fontFamily: P.display, fontSize: 10, letterSpacing: 1, color: P.dim, marginBottom: 7 }}>CUPÓN DE DESCUENTO</div>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <input
                      type="text"
                      value={couponCode}
                      onChange={e => setCouponCode(e.target.value.toUpperCase())}
                      onKeyDown={e => e.key === 'Enter' && applyCoupon()}
                      placeholder="TU CÓDIGO"
                      style={{
                        flex: 1, minWidth: 0, padding: '9px 11px',
                        border: `2px solid ${couponError ? P.red : P.ink}`, borderRadius: 8,
                        fontFamily: 'ui-monospace, monospace', fontSize: 12, fontWeight: 700,
                        letterSpacing: 1.5, outline: 'none', background: P.card, textTransform: 'uppercase',
                        transition: 'border-color .15s',
                      }}
                    />
                    <button onClick={applyCoupon} disabled={couponLoading || !couponCode.trim()} style={{
                      background: P.ink, color: '#ffffff', border: `2px solid ${P.ink}`, borderRadius: 8,
                      padding: '9px 13px', fontFamily: P.display, fontSize: 11, letterSpacing: 0.5,
                      cursor: couponLoading ? 'wait' : 'pointer', flexShrink: 0,
                      opacity: couponLoading || !couponCode.trim() ? 0.6 : 1, transition: 'opacity .15s',
                    }}>{couponLoading ? '...' : 'APLICAR'}</button>
                  </div>
                  {couponError && (
                    <div style={{ fontSize: 11, color: P.red, fontWeight: 600, marginTop: 5 }}>✗ {couponError}</div>
                  )}
                </div>
              )}
            </div>

            {/* ── Totales ── */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Subtotal</span><span style={{ fontWeight: 600 }}>${fmt(subtotal)}</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>Envío</span>
                <span style={{ fontWeight: 600, color: shipCost === 0 ? P.green : P.ink }}>{shipCost === 0 ? '¡GRATIS!' : `$${fmt(shipCost)}`}</span>
              </div>
              {couponDiscount > 0 && (
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: P.green }}>Descuento <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 11 }}>{couponData.code}</span></span>
                  <span style={{ fontWeight: 700, color: P.green }}>-${fmt(couponDiscount)}</span>
                </div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderTop: `2px solid ${P.ink}`, paddingTop: 10, marginTop: 4 }}>
                <span style={{ fontFamily: P.display, fontSize: 18 }}>TOTAL</span>
                <span style={{ fontFamily: P.display, fontSize: 26, letterSpacing: -1 }}>${fmt(total)}</span>
              </div>
            </div>
            <div style={{ marginTop: 14, padding: '10px 12px', background: P.card, border: `2px dashed ${P.line2}`, borderRadius: 8, fontSize: 11, color: P.ink2, lineHeight: 1.5 }}>
              <div style={{ fontWeight: 700, marginBottom: 4 }}>📅 Entrega estimada</div>
              <div>{form.shipMethod === 'express' ? 'Mañana 12:00–18:00' : form.shipMethod === 'pickup' ? 'Hoy en 2h · Sucursal Pocitos' : 'En 2–4 días hábiles'}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// Success / Confirmation screen
function SuccessScreen({ navigate, lastOrder, isMobile, orderId: orderIdProp, user }) {
  const P = window.POP;
  const fmt = n => n.toLocaleString('es-UY');

  // Datos del comprador guardados antes del redirect a MP
  const payer = React.useMemo(() => {
    try { return JSON.parse(localStorage.getItem('voltio-last-payer') || '{}'); } catch { return {}; }
  }, []);
  const buyerFirstName = ((payer.name || user?.name || '').split(' ')[0] || 'CLIENTE').toUpperCase();
  const buyerAddress = payer.address || '';
  const deliveryDate = React.useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() + 3);
    return d.toLocaleDateString('es-UY', { weekday: 'long', day: 'numeric', month: 'short' });
  }, []);

  // Usar el orderId real de MP/Supabase; si no hay, generar uno de display
  const fallbackId = React.useMemo(() => 'VLT-' + Math.floor(Math.random() * 900000 + 100000), []);
  const orderId = orderIdProp || fallbackId;

  const total = lastOrder?.reduce((s, it) => s + it.price * it.qty, 0) || 0;

  React.useEffect(() => {
    const colors = [P.yellow, P.red, P.blue, P.green, P.pink, P.purple, P.orange];
    const pieces = [];
    for (let i = 0; i < 80; i++) {
      const el = document.createElement('div');
      el.style.cssText = `
        position:fixed;top:-20px;left:${Math.random() * 100}vw;
        width:${8 + Math.random() * 8}px;height:${10 + Math.random() * 14}px;
        background:${colors[i % colors.length]};border:1.5px solid ${P.ink};
        z-index:9999;pointer-events:none;
        animation:pop-confetti ${2 + Math.random() * 2}s cubic-bezier(.3,.6,.4,1) ${Math.random() * 0.8}s forwards;
        border-radius:${Math.random() > 0.5 ? '50%' : '2px'};
      `;
      document.body.appendChild(el);
      pieces.push(el);
    }
    const cleanup = setTimeout(() => pieces.forEach(p => p.remove()), 5000);
    return () => { clearTimeout(cleanup); pieces.forEach(p => p.remove()); };
  }, []);

  return (
    <div className="pop-page-in" style={{ padding: isMobile ? 16 : 32, maxWidth: 840, margin: '0 auto' }}>
      <div style={{ background: P.green, color: P.card, border: `3px solid ${P.ink}`, borderRadius: 20,
        padding: isMobile ? 28 : 48, boxShadow: `6px 6px 0 ${P.ink}`, textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
        <div className="pop-dots" style={{ position: 'absolute', inset: 0, opacity: 0.3 }}></div>
        <div style={{ position: 'absolute', top: isMobile ? 12 : 24, right: isMobile ? 12 : 24 }}>
          <StarBurst size={isMobile ? 70 : 100} fill={P.yellow} text={'PAID!'} rotate={12} />
        </div>
        <div className="pop-bounce-in" style={{ position: 'relative', fontSize: isMobile ? 64 : 96, lineHeight: 1 }}>✅</div>
        <div className="pop-fade-up" style={{ position: 'relative', fontFamily: P.display, fontSize: isMobile ? 36 : 64, letterSpacing: -2, marginTop: 14, lineHeight: 1, animationDelay: '.1s' }}>
          ¡GRACIAS,<br />{buyerFirstName}! 🎉
        </div>
        <div className="pop-fade-up" style={{ position: 'relative', fontSize: isMobile ? 13 : 16, marginTop: 16, fontWeight: 500, maxWidth: 480, margin: '16px auto 0', animationDelay: '.2s' }}>
          Tu pedido <span style={{ fontFamily: 'ui-monospace, monospace', background: P.ink, color: '#ffffff', padding: '2px 8px', borderRadius: 4 }}>{orderId}</span> está confirmado. Te enviamos un email con los detalles.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 14 : 18, marginTop: isMobile ? 20 : 28 }}>
        <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, padding: 18, boxShadow: `4px 4px 0 ${P.ink}` }}>
          <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: 0.5, marginBottom: 10 }}>📦 RESUMEN DEL PEDIDO</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 6 }}>
            <span style={{ color: P.dim }}>Pedido</span><span style={{ fontFamily: 'ui-monospace, monospace' }}>{orderId}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 6 }}>
            <span style={{ color: P.dim }}>Productos</span><span>{lastOrder?.length || 0} items</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderTop: `2px dashed ${P.line2}`, paddingTop: 10, marginTop: 6 }}>
            <span style={{ fontFamily: P.display, fontSize: 15 }}>TOTAL PAGADO</span>
            <span style={{ fontFamily: P.display, fontSize: 24, letterSpacing: -1 }}>${fmt(total)}</span>
          </div>
        </div>
        <div style={{ background: P.yellow, border: `2px solid ${P.ink}`, borderRadius: 14, padding: 18, boxShadow: `4px 4px 0 ${P.ink}` }}>
          <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: 0.5, marginBottom: 10 }}>🚚 ENTREGA ESTIMADA</div>
          <div style={{ fontFamily: P.display, fontSize: isMobile ? 22 : 26, letterSpacing: -1, lineHeight: 1.1 }}>
            {deliveryDate}<br /><span style={{ fontSize: 14, color: P.ink2 }}>entre 12:00 y 18:00</span>
          </div>
          <div style={{ marginTop: 10, fontSize: 12, fontWeight: 600, display: 'flex', gap: 6, alignItems: 'center' }}>📍 {buyerAddress || 'Dirección de entrega'}</div>
        </div>
      </div>

      {/* Timeline */}
      <div style={{ marginTop: isMobile ? 20 : 28, background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14, padding: isMobile ? 18 : 22, boxShadow: `4px 4px 0 ${P.ink}` }}>
        <div style={{ fontFamily: P.display, fontSize: 14, letterSpacing: 0.5, marginBottom: 16 }}>📍 SEGUIMIENTO</div>
        <div style={{ display: 'flex', justifyContent: 'space-between', position: 'relative', padding: isMobile ? '0 8px' : '0 16px' }}>
          <div style={{ position: 'absolute', top: isMobile ? 12 : 16, left: isMobile ? 20 : 30, right: isMobile ? 20 : 30, height: 3, background: P.line2, borderRadius: 999, zIndex: 0 }}></div>
          <div style={{ position: 'absolute', top: isMobile ? 12 : 16, left: isMobile ? 20 : 30, width: '12%', height: 3,
            background: `repeating-linear-gradient(90deg, ${P.green} 0 6px, transparent 6px 10px)`, borderRadius: 999, zIndex: 1 }}></div>
          {[
            ['✓', 'Confirmado', 'Hoy 14:32', P.green],
            ['📦', 'Preparando', 'En proceso', P.yellow],
            ['🚚', 'En camino', '—', P.cream],
            ['🏠', 'Entregado', '—', P.cream],
          ].map(([icon, label, t, bg], i) => (
            <div key={label} style={{ textAlign: 'center', position: 'relative', zIndex: 2, flex: 1 }}>
              <div style={{ width: isMobile ? 24 : 32, height: isMobile ? 24 : 32, borderRadius: '50%',
                background: bg, color: i < 2 ? P.card : P.ink, border: `2px solid ${P.ink}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: isMobile ? 12 : 14, fontWeight: 700, margin: '0 auto',
                boxShadow: i === 0 ? `3px 3px 0 ${P.ink}` : 'none' }}>{icon}</div>
              <div style={{ fontFamily: P.display, fontSize: isMobile ? 10 : 12, letterSpacing: 0.5, marginTop: 6 }}>{label.toUpperCase()}</div>
              <div style={{ fontSize: isMobile ? 9 : 10, color: P.dim, marginTop: 2 }}>{t}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ marginTop: isMobile ? 20 : 28, display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
        <PopButton variant="dark" size="lg" onClick={() => navigate('home')}>← Volver al inicio</PopButton>
        <PopButton variant="primary" size="lg">📧 Ver email de confirmación</PopButton>
      </div>

      <div style={{ marginTop: isMobile ? 20 : 28, padding: isMobile ? 16 : 20, background: P.purple, border: `2px solid ${P.ink}`,
        borderRadius: 14, boxShadow: `4px 4px 0 ${P.ink}`, display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
        <StarBurst size={70} fill={P.yellow} text={'+$50K'} />
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontFamily: P.display, fontSize: isMobile ? 18 : 22, letterSpacing: -0.5 }}>¡Comparte y gana!</div>
          <div style={{ fontSize: 12, fontWeight: 500, marginTop: 4 }}>
            Comparte tu código <span style={{ fontFamily: 'ui-monospace, monospace', background: P.ink, color: '#ffffff', padding: '2px 8px', borderRadius: 4 }}>{buyerFirstName.slice(0, 3)}-VLT50</span> y ambos reciben $50.000 en su próxima compra.
          </div>
        </div>
        <PopButton variant="dark" size="md">📤 Compartir</PopButton>
      </div>
    </div>
  );
}

window.CheckoutScreen = CheckoutScreen;
window.SuccessScreen = SuccessScreen;
