/* ═══════════════════════════════════════
   ROMAJA — Carrito & Checkout con Sinpe Móvil
═══════════════════════════════════════ */

const ProductThumb = ({ product, size = 80 }) => {
  const img = product.imagen_url || (product.imagenes && product.imagenes[0]);
  return (
    <div style={{ width: size, height: size, borderRadius: 2, overflow: "hidden", flexShrink: 0, background: product.bg }}>
      {img
        ? <img src={img} alt={product.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        : <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 8, color: "rgba(58,44,30,0.3)", fontFamily: "monospace", textAlign: "center", padding: 4 }}>{product.name}</div>
      }
    </div>
  );
};

/* ══════════ CARRITO ══════════ */
const PageCarrito = () => {
  const { navigate } = useNav();
  const { items, removeItem, updateQty, total } = useCart();
  const isMobile = useMobile();

  if (items.length === 0) return (
    <div style={{ background: T.bg, minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <div style={{ textAlign: "center", padding: 40 }}>
        <div style={{ fontSize: 48, marginBottom: 16 }}>🛍️</div>
        <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 26, color: T.dark, marginBottom: 8 }}>Tu carrito está vacío</div>
        <p style={{ fontSize: 14, color: T.mid, marginBottom: 28 }}>Explorá nuestra tienda y encontrá algo especial.</p>
        <button onClick={() => navigate("/tienda")} style={{ background: T.primary, color: "#fff", border: "none", padding: "13px 32px", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", cursor: "pointer", fontFamily: "'Lato', sans-serif", borderRadius: 2 }}>
          Ir a la Tienda
        </button>
      </div>
    </div>
  );

  return (
    <div style={{ background: T.bg, minHeight: "70vh" }}>
      <div style={{ maxWidth: 1100, margin: "0 auto", padding: isMobile ? "24px 16px" : "48px 32px" }}>
        <Breadcrumb items={[{ label: "Inicio", path: "/" }, { label: "Carrito" }]} />
        <SectionHeader eyebrow={`${items.reduce((s,i)=>s+i.qty,0)} productos`} title="Tu Carrito" />

        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 360px", gap: isMobile ? 24 : 40 }}>
          {/* Items */}
          <div>
            {items.map(item => (
              <div key={item.key} style={{ display: "grid", gridTemplateColumns: isMobile ? "64px 1fr" : "80px 1fr auto", gap: isMobile ? 12 : 20, padding: "16px 0", borderBottom: `1px solid ${T.border}`, alignItems: "center" }}>
                <ProductThumb product={item.product} size={isMobile ? 64 : 80} />
                <div>
                  <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: isMobile ? 14 : 16, color: T.dark, marginBottom: 4 }}>{item.product.name}</div>
                  {item.options.color && <div style={{ fontSize: 11, color: T.light, marginBottom: 2 }}>Color: {item.options.color}</div>}
                  {item.options.size  && <div style={{ fontSize: 11, color: T.light, marginBottom: 2 }}>Talla: {item.options.size}</div>}
                  <div style={{ fontSize: 14, color: T.primary, fontWeight: 700, marginTop: 4 }}>{formatPrice(item.product.price)}</div>
                  {isMobile && (
                    <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 8 }}>
                      <div style={{ display: "flex", alignItems: "center", border: `1px solid ${T.border}`, borderRadius: 2 }}>
                        <button onClick={() => updateQty(item.key, item.qty - 1)} style={{ width: 28, height: 28, background: "none", border: "none", cursor: "pointer", fontSize: 14, color: T.mid }}>−</button>
                        <span style={{ width: 24, textAlign: "center", fontSize: 13, color: T.dark }}>{item.qty}</span>
                        <button onClick={() => updateQty(item.key, item.qty + 1)} style={{ width: 28, height: 28, background: "none", border: "none", cursor: "pointer", fontSize: 14, color: T.mid }}>+</button>
                      </div>
                      <div style={{ fontSize: 14, fontWeight: 700, color: T.dark }}>{formatPrice(item.product.price * item.qty)}</div>
                      <button onClick={() => removeItem(item.key)} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 11, color: T.light, textDecoration: "underline", fontFamily: "'Lato', sans-serif" }}>Quitar</button>
                    </div>
                  )}
                </div>
                {!isMobile && (
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 10 }}>
                    <div style={{ display: "flex", alignItems: "center", border: `1px solid ${T.border}`, borderRadius: 2 }}>
                      <button onClick={() => updateQty(item.key, item.qty - 1)} style={{ width: 32, height: 32, background: "none", border: "none", cursor: "pointer", fontSize: 14, color: T.mid }}>−</button>
                      <span style={{ width: 28, textAlign: "center", fontSize: 13, color: T.dark }}>{item.qty}</span>
                      <button onClick={() => updateQty(item.key, item.qty + 1)} style={{ width: 32, height: 32, background: "none", border: "none", cursor: "pointer", fontSize: 14, color: T.mid }}>+</button>
                    </div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: T.dark }}>{formatPrice(item.product.price * item.qty)}</div>
                    <button onClick={() => removeItem(item.key)} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 11, color: T.light, letterSpacing: "0.06em", textDecoration: "underline", fontFamily: "'Lato', sans-serif" }}>Eliminar</button>
                  </div>
                )}
              </div>
            ))}
            <div style={{ marginTop: 20 }}>
              <button onClick={() => navigate("/tienda")} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 12, color: T.primary, letterSpacing: "0.1em", fontFamily: "'Lato', sans-serif" }}>← Seguir comprando</button>
            </div>
          </div>

          {/* Resumen */}
          <div style={{ position: "sticky", top: 100 }}>
            <div style={{ background: T.bgSoft, padding: "28px", borderRadius: 2, border: `1px solid ${T.border}` }}>
              <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 20, color: T.dark, marginBottom: 20 }}>Resumen del Pedido</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 20 }}>
                {items.map(i => (
                  <div key={i.key} style={{ display: "flex", justifyContent: "space-between", fontSize: 13, color: T.mid }}>
                    <span>{i.product.name} x{i.qty}</span>
                    <span>{formatPrice(i.product.price * i.qty)}</span>
                  </div>
                ))}
              </div>
              <div style={{ borderTop: `1px solid ${T.border}`, paddingTop: 16, marginBottom: 20 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: T.light, marginBottom: 8 }}>
                  <span>Subtotal</span><span>{formatPrice(total)}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: T.light, marginBottom: 4 }}>
                  <span>Envío</span><span>Coordinar por WhatsApp</span>
                </div>
                <div style={{ fontSize: 11, color: T.light, marginBottom: 12 }}>No se incluye el costo de envío</div>
                <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "'DM Serif Display', serif", fontSize: 20, color: T.dark }}>
                  <span>Total</span><span style={{ color: T.primary }}>{formatPrice(total)}</span>
                </div>
              </div>
              <button onClick={() => navigate("/checkout")} style={{ width: "100%", background: T.primary, color: "#fff", border: "none", padding: "14px", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", cursor: "pointer", fontFamily: "'Lato', sans-serif", borderRadius: 2, marginBottom: 12 }}>
                Proceder al Pago
              </button>
              <div style={{ textAlign: "center", fontSize: 11, color: T.light }}>Pago por Sinpe Móvil · 100% seguro</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

/* ══════════ CHECKOUT ══════════ */
const PageCheckout = () => {
  const { navigate } = useNav();
  const { items, total, clearCart } = useCart();
  const isMobile = useMobile();
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({ nombre: "", telefono: "", provincia: "", canton: "", direccion: "", notas: "" });
  const [errors, setErrors] = React.useState({});
  const [orderNum, setOrderNum] = React.useState(null);
  const [orderError, setOrderError] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [turnstileToken, setTurnstileToken] = React.useState(null);
  const turnstileRef = React.useRef(null);
  const turnstileWidgetId = React.useRef(null);

  React.useEffect(() => {
    if (step !== 2) return;
    // Si window.turnstile todavía no cargó, reintenta cada 200ms. Sin el
    // pollTimeoutId de acá abajo, ese reintento seguía corriendo en segundo
    // plano para siempre si el usuario salía del checkout antes de que
    // Cloudflare terminara de cargar (turnstileRef.current queda null tras
    // desmontar, así que la condición nunca se cumplía y el setTimeout se
    // reprogramaba indefinidamente).
    let pollTimeoutId = null;
    let cancelled = false;
    const render = () => {
      if (cancelled) return;
      if (!window.turnstile || !turnstileRef.current) { pollTimeoutId = setTimeout(render, 200); return; }
      if (turnstileWidgetId.current) window.turnstile.remove(turnstileWidgetId.current);
      turnstileWidgetId.current = window.turnstile.render(turnstileRef.current, {
        sitekey: "0x4AAAAAADP_bzLUrKH13CV-",
        callback: t => setTurnstileToken(t),
        "expired-callback": () => setTurnstileToken(null),
        "error-callback": () => setTurnstileToken(null),
        theme: "light",
      });
    };
    setTurnstileToken(null);
    render();
    return () => {
      cancelled = true;
      if (pollTimeoutId) clearTimeout(pollTimeoutId);
      if (turnstileWidgetId.current) window.turnstile.remove(turnstileWidgetId.current);
    };
  }, [step]);

  if (items.length === 0 && step !== 3) {
    return (
      <div style={{ background: T.bg, minHeight: "60vh", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 24, color: T.dark, marginBottom: 12 }}>No hay productos en el carrito</div>
          <button onClick={() => navigate("/tienda")} style={{ background: T.primary, color: "#fff", border: "none", padding: "12px 28px", cursor: "pointer", fontFamily: "'Lato', sans-serif", borderRadius: 2, fontSize: 12 }}>Ir a la Tienda</button>
        </div>
      </div>
    );
  }

  const validate = () => {
    const e = {};
    if (!form.nombre.trim()) e.nombre = "Requerido";
    if (!form.telefono.trim() || !/^[0-9]{8}$/.test(form.telefono.replace(/\s|-/g, ""))) e.telefono = "Ingresá un teléfono válido (8 dígitos)";
    if (!form.provincia.trim()) e.provincia = "Requerido";
    if (!form.canton.trim()) e.canton = "Requerido";
    if (!form.direccion.trim()) e.direccion = "Ingresá tu dirección para coordinar el envío";
    return e;
  };

  const handleStep1 = () => {
    const e = validate();
    if (Object.keys(e).length) { setErrors(e); return; }
    setErrors({});
    setStep(2);
    window.scrollTo({ top: 0 });
  };

  const handleConfirm = async () => {
    setSubmitting(true);
    setOrderError(null);
    try {
      const r = await fetch('/api/pedidos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          nombre: form.nombre, telefono: form.telefono,
          provincia: form.provincia, canton: form.canton,
          direccion: form.direccion, notas: form.notas || null,
          items: items.map(i => ({
            id: i.product.id, name: i.product.name, qty: i.qty, price: i.product.price,
            color: i.options.color || null, size: i.options.size || null,
          })),
          turnstileToken,
        }),
      });
      const data = await r.json();
      if (!r.ok) {
        setOrderError(data.error || "No se pudo registrar el pedido. Intentá de nuevo.");
        setSubmitting(false);
        return;
      }
      const num = data.numero;
      setOrderNum(num);
      const msg = encodeURIComponent(
        `🛍️ *Pedido #${num}*\n\n` +
        items.map(i => `• ${i.product.name}${i.options.color ? ` (${i.options.color})` : ""}${i.options.size ? ` T:${i.options.size}` : ""} x${i.qty} — ${formatPrice(i.product.price * i.qty)}`).join("\n") +
        `\n\n💰 *Total: ${formatPrice(total)}*\n\n` +
        `👤 *Datos de envío:*\n${form.nombre}\nTel: ${form.telefono}\n${form.canton}, ${form.provincia}\n${form.direccion}` +
        (form.notas ? `\nNotas: ${form.notas}` : "") +
        `\n\n✅ Ya realicé el Sinpe Móvil de ${formatPrice(total)} al ${SINPE_NUMBER} (${SINPE_NAME}). Adjunto el comprobante.`
      );
      clearCart();
      setStep(3);
      setTimeout(() => window.open(`https://wa.me/${WHATSAPP_NUMBER}?text=${msg}`, "_blank"), 500);
    } catch {
      setOrderError("Error de conexión. Verificá tu internet e intentá de nuevo.");
    } finally {
      setSubmitting(false);
    }
  };

  const input = (field, label, placeholder, type = "text") => (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <label style={{ fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: errors[field] ? "#c0392b" : T.dark, fontFamily: "'Lato', sans-serif" }}>{label}</label>
      <input type={type} placeholder={placeholder} value={form[field]}
        onChange={e => { setForm(f => ({ ...f, [field]: e.target.value })); if (errors[field]) setErrors(e2 => { const c = { ...e2 }; delete c[field]; return c; }); }}
        style={{ border: `1px solid ${errors[field] ? "#c0392b" : T.border}`, background: T.card, padding: "11px 14px", fontSize: 13, fontFamily: "'Lato', sans-serif", color: T.dark, borderRadius: 2, outline: "none", width: "100%" }} />
      {errors[field] && <span style={{ fontSize: 11, color: "#c0392b" }}>{errors[field]}</span>}
    </div>
  );

  const StepIndicator = () => (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 0, marginBottom: 48 }}>
      {[["1", "Tus datos"], ["2", "Pago Sinpe"], ["3", "Confirmado"]].map(([n, label], i) => (
        <React.Fragment key={n}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
            <div style={{ width: 36, height: 36, borderRadius: "50%", background: step >= parseInt(n) ? T.primary : T.border, color: step >= parseInt(n) ? "#fff" : T.light, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 700, transition: "background 0.3s" }}>{n}</div>
            <span style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: step >= parseInt(n) ? T.dark : T.light }}>{label}</span>
          </div>
          {i < 2 && <div style={{ width: 80, height: 1, background: step > parseInt(n) ? T.primary : T.border, marginBottom: 22, transition: "background 0.3s" }} />}
        </React.Fragment>
      ))}
    </div>
  );

  return (
    <div style={{ background: T.bg, minHeight: "70vh" }}>
      <div style={{ maxWidth: 900, margin: "0 auto", padding: isMobile ? "24px 16px" : "48px 32px" }}>
        <Breadcrumb items={[{ label: "Inicio", path: "/" }, { label: "Carrito", path: "/carrito" }, { label: "Checkout" }]} />
        <SectionHeader eyebrow="Casi listo" title="Finalizar Pedido" center />
        <StepIndicator />

        {/* PASO 1 — DATOS */}
        {step === 1 && (
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 340px", gap: isMobile ? 24 : 40 }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 20, color: T.dark, marginBottom: 4 }}>Datos de contacto y envío</div>
              <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 14 }}>
                {input("nombre", "Nombre completo", "Tu nombre")}
                {input("telefono", "Teléfono", "88887777", "tel")}
              </div>
              <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 14 }}>
                {input("provincia", "Provincia", "Ej: San José")}
                {input("canton", "Cantón / Ciudad", "Ej: Curridabat")}
              </div>
              {input("direccion", "Dirección exacta", "Barrio, calle, señas...")}
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                <label style={{ fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: T.dark, fontFamily: "'Lato', sans-serif" }}>Notas adicionales (opcional)</label>
                <textarea placeholder="Instrucciones especiales, color preferido, etc." value={form.notas} onChange={e => setForm(f => ({ ...f, notas: e.target.value }))}
                  style={{ border: `1px solid ${T.border}`, background: T.card, padding: "11px 14px", fontSize: 13, fontFamily: "'Lato', sans-serif", color: T.dark, borderRadius: 2, outline: "none", resize: "vertical", minHeight: 80 }} />
              </div>
              <div style={{ background: "#f0f8f0", border: "1px solid #c0ddc0", padding: "14px 18px", borderRadius: 2, fontSize: 12, color: "#3a6a3a", lineHeight: 1.7 }}>
                🚚 El costo de envío se coordina por WhatsApp después de confirmar el pedido.
              </div>
              <button onClick={handleStep1} style={{ background: T.primary, color: "#fff", border: "none", padding: "14px", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", cursor: "pointer", fontFamily: "'Lato', sans-serif", borderRadius: 2 }}>
                Continuar al Pago →
              </button>
            </div>

            {/* Mini resumen */}
            <div>
              <div style={{ background: T.bgSoft, padding: "24px", borderRadius: 2, border: `1px solid ${T.border}` }}>
                <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 18, color: T.dark, marginBottom: 16 }}>Tu pedido</div>
                {items.map(i => (
                  <div key={i.key} style={{ display: "flex", gap: 12, marginBottom: 14, alignItems: "flex-start" }}>
                    <ProductThumb product={i.product} size={48} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, color: T.dark, marginBottom: 2 }}>{i.product.name}</div>
                      <div style={{ fontSize: 11, color: T.light }}>x{i.qty}</div>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: T.dark }}>{formatPrice(i.product.price * i.qty)}</div>
                  </div>
                ))}
                <div style={{ borderTop: `1px solid ${T.border}`, paddingTop: 14, display: "flex", justifyContent: "space-between", fontFamily: "'DM Serif Display', serif", fontSize: 18, color: T.dark }}>
                  <span>Total</span><span style={{ color: T.primary }}>{formatPrice(total)}</span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* PASO 2 — SINPE */}
        {step === 2 && (
          <div style={{ maxWidth: 560, margin: "0 auto" }}>
            {/* Tarjeta Sinpe */}
            <div style={{ background: T.dark, borderRadius: 2, padding: "40px", marginBottom: 28, textAlign: "center", position: "relative", overflow: "hidden" }}>
              <div style={{ position: "absolute", top: -30, right: -30, width: 160, height: 160, borderRadius: "50%", background: "rgba(200,125,82,0.12)" }} />
              <div style={{ position: "absolute", bottom: -20, left: -20, width: 100, height: 100, borderRadius: "50%", background: "rgba(200,125,82,0.08)" }} />
              <div style={{ position: "relative" }}>
                <div style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(240,232,220,0.5)", marginBottom: 16 }}>Sinpe Móvil</div>
                <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 48, color: "#fff", letterSpacing: "0.08em", marginBottom: 8 }}>{SINPE_NUMBER}</div>
                <div style={{ fontSize: 14, color: "rgba(240,232,220,0.7)", marginBottom: 28 }}>{SINPE_NAME}</div>
                <div style={{ display: "inline-block", background: T.primary, padding: "10px 24px", borderRadius: 2 }}>
                  <span style={{ fontSize: 11, color: "#fff", letterSpacing: "0.1em", textTransform: "uppercase" }}>Monto a transferir:</span>
                  <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 28, color: "#fff", marginTop: 4 }}>{formatPrice(total)}</div>
                </div>
              </div>
            </div>

            {/* Instrucciones */}
            <div style={{ background: T.bgSoft, border: `1px solid ${T.border}`, borderRadius: 2, padding: "28px", marginBottom: 28 }}>
              <div style={{ fontFamily: "'DM Serif Display', serif", fontSize: 18, color: T.dark, marginBottom: 16 }}>Cómo pagar:</div>
              {[
                `Abrí tu app bancaria y seleccioná "Sinpe Móvil"`,
                `Ingresá el número: ${SINPE_NUMBER}`,
                `Verificá que el nombre sea: ${SINPE_NAME}`,
                `Transferí exactamente: ${formatPrice(total)}`,
                `En la descripción escribí tu nombre completo`,
                `Guardá el comprobante y hacé clic en "Confirmar Pedido"`,
              ].map((step, i) => (
                <div key={i} style={{ display: "flex", gap: 14, marginBottom: 14, alignItems: "flex-start" }}>
                  <div style={{ width: 24, height: 24, borderRadius: "50%", background: T.primary, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, flexShrink: 0 }}>{i + 1}</div>
                  <span style={{ fontSize: 13, color: T.mid, lineHeight: 1.6, paddingTop: 3 }}>{step}</span>
                </div>
              ))}
            </div>

            <div style={{ background: "#f0f8f0", border: "1px solid #c0ddc0", padding: "14px 18px", borderRadius: 2, marginBottom: 16, textAlign: "center" }}>
              <span style={{ fontSize: 12, color: "#3a6a3a" }}>Al confirmar se te asignará el número de pedido y se abrirá WhatsApp automáticamente.</span>
            </div>

            <div ref={turnstileRef} style={{ marginBottom: 16 }} />

            {orderError && (
              <div style={{ background: "#fdf0f0", border: "1px solid #f5c6c6", color: "#c0392b", padding: "12px 16px", borderRadius: 2, fontSize: 12, marginBottom: 16 }}>
                {orderError}
              </div>
            )}

            <div style={{ display: "flex", gap: 12 }}>
              <button onClick={() => setStep(1)} disabled={submitting} style={{ flex: "0 0 auto", background: "transparent", color: T.mid, border: `1px solid ${T.border}`, padding: "13px 20px", fontSize: 11, letterSpacing: "0.1em", cursor: submitting ? "not-allowed" : "pointer", fontFamily: "'Lato', sans-serif", borderRadius: 2 }}>← Atrás</button>
              <button onClick={handleConfirm} disabled={!turnstileToken || submitting} style={{ flex: 1, background: (turnstileToken && !submitting) ? "#25D366" : "#b89a84", color: "#fff", border: "none", padding: "14px", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", cursor: (turnstileToken && !submitting) ? "pointer" : "not-allowed", fontFamily: "'Lato', sans-serif", borderRadius: 2, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
                {!submitting && <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>}
                {submitting ? "Enviando…" : "Ya pagué — Confirmar por WhatsApp"}
              </button>
            </div>
          </div>
        )}

        {/* PASO 3 — CONFIRMADO */}
        {step === 3 && (
          <div style={{ maxWidth: 520, margin: "0 auto", textAlign: "center" }}>
            <div style={{ width: 72, height: 72, borderRadius: "50%", background: "#e8f5e8", border: "2px solid #4caf50", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 24px", fontSize: 32 }}>✓</div>
            <h2 style={{ fontFamily: "'DM Serif Display', serif", fontSize: 32, color: T.dark, marginBottom: 12 }}>¡Pedido enviado!</h2>
            <p style={{ fontSize: 14, color: T.mid, lineHeight: 1.85, marginBottom: 8 }}>
              Tu pedido <strong>#{orderNum}</strong> fue registrado correctamente.
            </p>
            <p style={{ fontSize: 14, color: T.mid, lineHeight: 1.85, marginBottom: 32 }}>
              Se abrió WhatsApp con el detalle del pedido. Envianos el comprobante del Sinpe para confirmar y coordinar el envío. 🌿
            </p>
            <div style={{ background: T.bgSoft, border: `1px solid ${T.border}`, padding: "20px", borderRadius: 2, marginBottom: 32, textAlign: "left" }}>
              <div style={{ fontSize: 12, color: T.mid, lineHeight: 1.85 }}>
                📱 Número Sinpe: <strong>{SINPE_NUMBER}</strong><br />
                👤 A nombre de: <strong>{SINPE_NAME}</strong><br />
                🔢 Número de pedido: <strong>#{orderNum}</strong>
              </div>
            </div>
            <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
              <a href={`https://wa.me/${WHATSAPP_NUMBER}`} target="_blank" rel="noreferrer"
                style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "#25D366", color: "#fff", padding: "12px 24px", borderRadius: 2, fontSize: 11, textDecoration: "none", letterSpacing: "0.12em", textTransform: "uppercase" }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                Abrir WhatsApp
              </a>
              <button onClick={() => navigate("/")}
                style={{ background: T.bgSoft, color: T.dark, border: `1px solid ${T.border}`, padding: "12px 24px", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", cursor: "pointer", fontFamily: "'Lato', sans-serif", borderRadius: 2 }}>
                Volver al Inicio
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { PageCarrito, PageCheckout });
