// Checkout.jsx — full 3-step checkout flow.
// Steps: dirección → pago → confirmar → (CheckoutDone in Cart.jsx)

const { useState: useChkState } = React;

// =====================================================================
// Saved addresses + cards (reused from Account.jsx fakes; could be hoisted).
const CHK_ADDRESSES = [
  { id: "a1", label: "Casa",    name: "Bau Andalón", street: "Av. Francisco Villa 1180, Int. 4", area: "Versalles, Puerto Vallarta", state: "Jalisco", zip: "48330", phone: "+52 322 145 2287", default: true },
  { id: "a2", label: "Oficina", name: "Bau Andalón", street: "Calle Honduras 156",               area: "5 de Diciembre, Puerto Vallarta", state: "Jalisco", zip: "48350", phone: "+52 322 145 2287" },
];
const CHK_CARDS = [
  { id: "c1", brand: "VISA",       last4: "4242", exp: "08/28", default: true,  gradient: "linear-gradient(135deg, #1F3A93 0%, #0A1740 100%)" },
  { id: "c2", brand: "MASTERCARD", last4: "5588", exp: "11/27", default: false, gradient: "linear-gradient(135deg, #18181B 0%, #3A3A40 100%)" },
];

const CheckoutPage = ({ cart, user, onNav, onComplete }) => {
  const [step, setStep] = useChkState(0);
  const { isMobile } = useViewport();
  const [addressId, setAddressId] = useChkState(CHK_ADDRESSES.find(a => a.default).id);
  const [showNewAddr, setShowNewAddr] = useChkState(false);
  const [newAddr, setNewAddr] = useChkState({ label: "Casa", name: user?.name || "", street: "", area: "", zip: "", phone: "" });
  const [savedAddresses, setSavedAddresses] = useChkState(CHK_ADDRESSES);

  const [paymentType, setPaymentType] = useChkState("card"); // 'card' | 'newCard' | 'oxxo' | 'paypal'
  const [cardId, setCardId] = useChkState(CHK_CARDS.find(c => c.default).id);
  const [msi, setMsi] = useChkState(1);
  const [newCard, setNewCard] = useChkState({ number: "", titular: "", exp: "", cvv: "", saveCard: true });

  const [processing, setProcessing] = useChkState(false);

  const toast = useToast();

  const subtotal = cart.reduce((s, it) => s + it.p.price * it.qty, 0);
  const savings = cart.reduce((s, it) => s + ((it.p.was || it.p.price) - it.p.price) * it.qty, 0);
  const shipping = subtotal >= 599 ? 0 : 89;
  const total = subtotal + shipping;

  const selectedAddress = savedAddresses.find(a => a.id === addressId);
  const selectedCard = CHK_CARDS.find(c => c.id === cardId);

  // Demo mode: all steps pass validation
  const canNext = true;

  const next = () => {
    if (!canNext) return;
    if (step < 2) setStep(s => s + 1);
    else pay();
  };

  const pay = () => {
    setProcessing(true);
    setTimeout(() => {
      setProcessing(false);
      const orderNum = "AL-" + Math.floor(Math.random() * 900000 + 100000);
      onComplete({ orderNum, address: selectedAddress, payment: { type: paymentType, card: selectedCard, msi }, total, items: cart });
    }, 1600);
  };

  // Empty cart guard removed in demo mode — user can walk checkout with empty cart too
  if (false && cart.length === 0 && !processing) {
    return (
      <div style={{ maxWidth: 640, margin: "80px auto", padding: "0 32px", textAlign: "center" }}>
        <AllenIcon name="shopping_cart" size={48} color="var(--fg-hint)" />
        <h1 className="headline-sm" style={{ marginTop: 16 }}>Tu carrito está vacío</h1>
        <p className="body" style={{ marginTop: 8, color: "var(--fg-muted)" }}>Agrega productos antes de continuar al pago.</p>
        <PrimaryButton onClick={() => onNav("home")} style={{ marginTop: 20, alignSelf: "center" }}>Seguir comprando</PrimaryButton>
      </div>
    );
  }

  const addNewAddr = () => {
    // Demo mode: accept any address
    const id = "a" + (savedAddresses.length + 1);
    const added = { id, ...newAddr, street: newAddr.street || "Nueva calle 123", zip: newAddr.zip || "48330", city: "Puerto Vallarta", state: "Jalisco" };
    setSavedAddresses([...savedAddresses, added]);
    setAddressId(id);
    setShowNewAddr(false);
    toast("Dirección agregada");
  };

  return (
    <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: isMobile ? "0 16px" : "0 32px" }}>
      <Breadcrumb items={["Inicio", "Carrito", "Pago"]} />

      {/* Stepper */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 32 }}>
        {["Dirección", "Pago", "Confirmar"].map((label, i) => (
          <div key={label}>
            <div style={{ height: 4, borderRadius: 2, background: i <= step ? "var(--primary)" : "var(--border)" }} />
            <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{
                width: 24, height: 24, borderRadius: 12,
                background: i < step ? "var(--success)" : i === step ? "var(--primary)" : "var(--bg-elev-2)",
                color: i <= step ? "#fff" : "var(--fg-muted)",
                font: "700 12px var(--font-sans)",
                display: "grid", placeItems: "center",
              }}>{i < step ? "✓" : i + 1}</span>
              <span style={{ font: i === step ? "700 14px var(--font-sans)" : "500 14px var(--font-sans)", color: i <= step ? "var(--fg-strong)" : "var(--fg-muted)" }}>{label}</span>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 380px", gap: isMobile ? 16 : 32, alignItems: "start" }}>
        {/* LEFT — step content */}
        <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 32 }}>
          {step === 0 && (
            <>
              <h2 className="headline-sm">Dirección de entrega</h2>
              <p className="body-sm" style={{ marginTop: 6, marginBottom: 24 }}>Elige a dónde te llega el pedido.</p>

              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {savedAddresses.map(a => (
                  <label key={a.id}
                    style={{
                      display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 14, alignItems: "start",
                      padding: 18, border: addressId === a.id ? "1.5px solid var(--primary)" : "1px solid var(--border)",
                      borderRadius: "var(--radius-md)", cursor: "pointer",
                      background: addressId === a.id ? "var(--primary-soft)" : "transparent",
                      transition: "all var(--dur-fast) var(--ease-out-quart)",
                    }}>
                    <Radio checked={addressId === a.id} onChange={() => setAddressId(a.id)} />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <span className="title-sm">{a.label}</span>
                        {a.default && <span style={{ font: "700 10px var(--font-sans)", color: "var(--primary)", background: "var(--bg-elev-1)", padding: "3px 8px", borderRadius: "9999px", textTransform: "uppercase", letterSpacing: ".05em" }}>Predeterminada</span>}
                      </div>
                      <div className="body" style={{ color: "var(--fg-strong)", marginTop: 4 }}>{a.name}</div>
                      <div className="body-sm">{a.street}</div>
                      <div className="body-sm">{a.area} · CP {a.zip}</div>
                      <div className="body-sm">{a.phone}</div>
                    </div>
                    <button onClick={e => { e.preventDefault(); toast("Editar dirección"); }}
                      style={{ background: "transparent", border: 0, color: "var(--primary)", font: "700 12px var(--font-sans)", cursor: "pointer", alignSelf: "center" }}>
                      Editar
                    </button>
                  </label>
                ))}

                {!showNewAddr ? (
                  <button onClick={() => setShowNewAddr(true)}
                    style={{
                      padding: 18, background: "transparent", border: "2px dashed var(--border-strong)",
                      borderRadius: "var(--radius-md)", display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                      color: "var(--fg-muted)", font: "600 14px var(--font-sans)", cursor: "pointer",
                    }}>
                    <AllenIcon name="add" size={18} /> Agregar nueva dirección
                  </button>
                ) : (
                  <div style={{ padding: 18, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)", display: "flex", flexDirection: "column", gap: 14 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                      <h4 className="title-sm">Nueva dirección</h4>
                      <button onClick={() => setShowNewAddr(false)} style={{ background: "transparent", border: 0, cursor: "pointer", color: "var(--fg-muted)", padding: 4, display: "grid", placeItems: "center" }}><AllenIcon name="close" size={18} /></button>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                      <Field label="Etiqueta">
                        <select value={newAddr.label} onChange={e => setNewAddr({ ...newAddr, label: e.target.value })}
                          style={{ ...inputStyle, width: "100%", appearance: "none", paddingRight: 36, backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23515259' stroke-width='2'><path d='m6 9 6 6 6-6'/></svg>\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center" }}>
                          <option>Casa</option><option>Oficina</option><option>Otra</option>
                        </select>
                      </Field>
                      <Field label="Nombre quien recibe"><TextInput value={newAddr.name} onChange={e => setNewAddr({ ...newAddr, name: e.target.value })} /></Field>
                    </div>
                    <Field label="Calle y número"><TextInput value={newAddr.street} onChange={e => setNewAddr({ ...newAddr, street: e.target.value })} /></Field>
                    <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 12 }}>
                      <Field label="Colonia"><TextInput value={newAddr.area} onChange={e => setNewAddr({ ...newAddr, area: e.target.value })} /></Field>
                      <Field label="CP"><TextInput value={newAddr.zip} onChange={e => setNewAddr({ ...newAddr, zip: e.target.value })} maxLength={5} /></Field>
                      <Field label="Teléfono"><TextInput type="tel" value={newAddr.phone} onChange={e => setNewAddr({ ...newAddr, phone: e.target.value })} /></Field>
                    </div>
                    <div style={{ display: "flex", gap: 8 }}>
                      <PrimaryButton onClick={addNewAddr}>Guardar dirección</PrimaryButton>
                      <button onClick={() => setShowNewAddr(false)} style={{ background: "transparent", border: 0, color: "var(--fg-muted)", font: "600 13px var(--font-sans)", cursor: "pointer", padding: "0 16px" }}>Cancelar</button>
                    </div>
                  </div>
                )}
              </div>

              <div style={{ marginTop: 20, padding: 14, background: "var(--success-bg)", borderRadius: "var(--radius-md)", display: "flex", alignItems: "center", gap: 10 }}>
                <AllenIcon name="local_shipping" size={18} color="var(--success)" />
                <span className="body-sm" style={{ color: "var(--fg-strong)" }}>
                  <strong>Llega el viernes 5 de marzo</strong> entre 10:00 y 18:00 a {selectedAddress?.area}.
                </span>
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <h2 className="headline-sm">Método de pago</h2>
              <p className="body-sm" style={{ marginTop: 6, marginBottom: 24 }}>Tus datos están cifrados. Nunca guardamos el CVV.</p>

              {/* Method tabs */}
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginBottom: 20, background: "var(--bg-elev-2)", borderRadius: "9999px", padding: 4 }}>
                {[
                  { id: "card",   label: "Tarjeta guardada", icon: "credit_card" },
                  { id: "newCard",label: "Tarjeta nueva",    icon: "add" },
                  { id: "oxxo",   label: "OXXO efectivo",    icon: "shopping_basket" },
                ].map(t => (
                  <button key={t.id} onClick={() => setPaymentType(t.id)}
                    style={{
                      padding: "10px 12px", borderRadius: "9999px",
                      background: paymentType === t.id ? "var(--bg-elev-1)" : "transparent",
                      color: paymentType === t.id ? "var(--fg-strong)" : "var(--fg-muted)",
                      border: 0, font: paymentType === t.id ? "700 12px var(--font-sans)" : "500 12px var(--font-sans)",
                      cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
                      boxShadow: paymentType === t.id ? "var(--elev-1)" : "none",
                      transition: "all var(--dur-fast) var(--ease-out-quart)",
                    }}>
                    <AllenIcon name={t.icon} size={14} /> {t.label}
                  </button>
                ))}
              </div>

              {paymentType === "card" && (
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  {CHK_CARDS.map(c => (
                    <label key={c.id}
                      style={{
                        display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 14, alignItems: "center",
                        padding: 16, border: cardId === c.id ? "1.5px solid var(--primary)" : "1px solid var(--border)",
                        borderRadius: "var(--radius-md)", cursor: "pointer",
                        background: cardId === c.id ? "var(--primary-soft)" : "transparent",
                      }}>
                      <Radio checked={cardId === c.id} onChange={() => setCardId(c.id)} />
                      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                        <div style={{ width: 48, height: 32, borderRadius: 6, background: c.gradient, display: "grid", placeItems: "center", color: "#fff", font: "700 10px var(--font-sans)", letterSpacing: ".05em" }}>{c.brand.slice(0,4)}</div>
                        <div>
                          <div className="title-sm" style={{ fontFamily: "var(--font-mono)" }}>•••• {c.last4}</div>
                          <div className="body-sm">Vence {c.exp}</div>
                        </div>
                      </div>
                      <span className="body-sm">{c.brand}</span>
                    </label>
                  ))}

                  {/* MSI selector */}
                  <div style={{ padding: 18, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)", marginTop: 6 }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                      <h4 className="title-sm">Meses sin intereses</h4>
                      <span className="body-sm">Solo en bancos participantes</span>
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 }}>
                      {[1, 3, 6, 9, 12].map(n => (
                        <button key={n} onClick={() => setMsi(n)}
                          style={{
                            padding: "10px 6px", borderRadius: "var(--radius-sm)",
                            background: msi === n ? "var(--primary)" : "var(--bg-elev-1)",
                            color: msi === n ? "#fff" : "var(--fg-strong)",
                            border: msi === n ? 0 : "1px solid var(--border)",
                            cursor: "pointer", textAlign: "center",
                          }}>
                          <div style={{ font: "700 13px var(--font-sans)" }}>{n === 1 ? "Único" : `${n} MSI`}</div>
                          {n > 1 && <div style={{ font: "500 10px var(--font-sans)", marginTop: 2, opacity: .8 }}>${Math.round(total / n).toLocaleString("es-MX")}/mes</div>}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {paymentType === "newCard" && (
                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  <Field label="Número de tarjeta">
                    <div style={{ position: "relative" }}>
                      <TextInput value={newCard.number}
                        onChange={e => setNewCard({ ...newCard, number: e.target.value.replace(/\D/g, "").slice(0, 16).replace(/(\d{4})(?=\d)/g, "$1 ").trim() })}
                        placeholder="4242 4242 4242 4242"
                        maxLength={19}
                        style={{ width: "100%", paddingRight: 56, fontFamily: "var(--font-mono)", letterSpacing: ".05em" }}
                        autoComplete="cc-number" inputMode="numeric"
                      />
                      <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", fontFamily: "var(--font-mono)", color: "var(--fg-muted)", font: "700 11px var(--font-sans)", letterSpacing: ".05em" }}>
                        {detectCardBrand(newCard.number) || "TARJETA"}
                      </span>
                    </div>
                  </Field>
                  <Field label="Titular como aparece en la tarjeta">
                    <TextInput value={newCard.titular} onChange={e => setNewCard({ ...newCard, titular: e.target.value })} placeholder="BAU ANDALON" autoComplete="cc-name" />
                  </Field>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                    <Field label="Vencimiento">
                      <TextInput value={newCard.exp}
                        onChange={e => { let v = e.target.value.replace(/\D/g, "").slice(0, 4); if (v.length > 2) v = v.slice(0, 2) + "/" + v.slice(2); setNewCard({ ...newCard, exp: v }); }}
                        placeholder="MM/AA" maxLength={5} autoComplete="cc-exp" inputMode="numeric"
                        style={{ fontFamily: "var(--font-mono)", letterSpacing: ".05em" }}
                      />
                    </Field>
                    <Field label="CVV" hint="3 dígitos al reverso">
                      <TextInput type="password" value={newCard.cvv}
                        onChange={e => setNewCard({ ...newCard, cvv: e.target.value.replace(/\D/g, "").slice(0, 4) })}
                        placeholder="•••" maxLength={4} autoComplete="cc-csc" inputMode="numeric"
                        style={{ fontFamily: "var(--font-mono)", letterSpacing: ".05em" }}
                      />
                    </Field>
                  </div>
                  <label style={{ display: "flex", alignItems: "center", gap: 10, font: "500 13px var(--font-sans)", color: "var(--fg-muted)", cursor: "pointer" }}>
                    <input type="checkbox" checked={newCard.saveCard} onChange={e => setNewCard({ ...newCard, saveCard: e.target.checked })} style={{ accentColor: "var(--primary)", width: 16, height: 16 }} />
                    Guardar tarjeta para próximas compras
                  </label>
                </div>
              )}

              {paymentType === "oxxo" && (
                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 16, padding: 18, background: "var(--orange-bg)", borderRadius: "var(--radius-md)" }}>
                    <div style={{ width: 60, height: 40, background: "#F2714C", color: "#fff", borderRadius: 6, display: "grid", placeItems: "center", font: "800 14px var(--font-sans)", letterSpacing: ".05em" }}>OXXO</div>
                    <div className="body" style={{ color: "var(--fg-strong)" }}>
                      Al confirmar generamos una <strong>ficha de pago</strong> con código de barras. Tienes <strong>48 horas</strong> para pagar en cualquier OXXO. Tu pedido empieza a procesarse cuando confirmamos el pago (en 1-2 horas).
                    </div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: 12, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)" }}>
                    <AllenIcon name="lock" size={16} color="var(--fg-muted)" />
                    <span className="body-sm" style={{ fontSize: 12 }}>Comisión de OXXO incluida en el total: $12 MXN</span>
                  </div>
                </div>
              )}
            </>
          )}

          {step === 2 && (
            <>
              <h2 className="headline-sm">Revisa tu pedido</h2>
              <p className="body-sm" style={{ marginTop: 6, marginBottom: 24 }}>Está todo listo. Confirma para pagar.</p>

              <ReviewBlock title="Entregar a" icon="location_on" onEdit={() => setStep(0)}>
                <div className="body" style={{ color: "var(--fg-strong)" }}>{selectedAddress.name}</div>
                <div className="body-sm">{selectedAddress.street}</div>
                <div className="body-sm">{selectedAddress.area} · CP {selectedAddress.zip}</div>
              </ReviewBlock>

              <ReviewBlock title="Pago" icon="credit_card" onEdit={() => setStep(1)}>
                {paymentType === "card" && (
                  <>
                    <div className="body" style={{ color: "var(--fg-strong)", display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ font: "700 11px var(--font-sans)", color: "var(--fg-muted)", letterSpacing: ".05em" }}>{selectedCard.brand}</span>
                      <span style={{ fontFamily: "var(--font-mono)" }}>•••• {selectedCard.last4}</span>
                    </div>
                    {msi > 1 && <div className="body-sm" style={{ marginTop: 4 }}>{msi} meses sin intereses · ${Math.round(total / msi).toLocaleString("es-MX")}/mes</div>}
                  </>
                )}
                {paymentType === "newCard" && (
                  <div className="body" style={{ color: "var(--fg-strong)", display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontFamily: "var(--font-mono)" }}>•••• {newCard.number.slice(-4)}</span>
                    <span style={{ font: "500 12px var(--font-sans)", color: "var(--fg-muted)" }}>{newCard.saveCard ? "(se guardará)" : ""}</span>
                  </div>
                )}
                {paymentType === "oxxo" && (
                  <div className="body" style={{ color: "var(--fg-strong)" }}>OXXO efectivo · ficha al confirmar</div>
                )}
              </ReviewBlock>

              <ReviewBlock title={`Productos (${cart.length})`} icon="shopping_basket">
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {cart.map(it => (
                    <div key={it.p.id} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <div style={{ width: 56, height: 56, borderRadius: "var(--radius-sm)", overflow: "hidden", background: it.p.imgBg, flexShrink: 0 }}>
                        <img src={it.p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="title-sm" style={{ fontSize: 13 }}>{it.p.name}</div>
                        <div className="body-sm" style={{ fontSize: 12 }}>Cantidad: {it.qty}</div>
                      </div>
                      <span className="price-sm">${(it.p.price * it.qty).toLocaleString("es-MX")}</span>
                    </div>
                  ))}
                </div>
              </ReviewBlock>
            </>
          )}

          {/* Footer buttons */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 32, paddingTop: 20, borderTop: "1px solid var(--border-soft)" }}>
            <button onClick={() => step === 0 ? onNav("cart") : setStep(s => s - 1)}
              style={{ background: "transparent", color: "var(--fg-strong)", border: 0, font: "600 13px var(--font-sans)", cursor: "pointer", padding: "10px 0" }}>
              ← {step === 0 ? "Volver al carrito" : "Atrás"}
            </button>
            <PrimaryButton onClick={next} disabled={!canNext || processing} style={{ opacity: (!canNext || processing) ? .5 : 1, pointerEvents: (!canNext || processing) ? "none" : "auto" }}>
              {processing ? (
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <Spinner /> Procesando…
                </span>
              ) : step === 2 ? `Pagar $${total.toLocaleString("es-MX")}` : "Continuar"}
            </PrimaryButton>
          </div>
        </div>

        {/* RIGHT — sticky summary */}
        <aside style={{ position: isMobile ? "static" : "sticky", top: 160, background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", padding: 24 }}>
          <h3 className="title-lg" style={{ marginBottom: 18 }}>Resumen</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <SumLine k={`Subtotal (${cart.length} productos)`} v={`$${subtotal.toLocaleString("es-MX")}`} />
            {savings > 0 && <SumLine k="Ahorros" v={`−$${savings.toLocaleString("es-MX")}`} color="var(--discount)" />}
            <SumLine k="Envío" v={shipping === 0 ? "GRATIS" : `$${shipping}`} color={shipping === 0 ? "var(--success)" : null} />
            <div style={{ borderTop: "1px solid var(--border-soft)", paddingTop: 12, marginTop: 4, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span className="title">Total</span>
              <div>
                <span className="price-lg">${total.toLocaleString("es-MX")}</span>
                <span style={{ marginLeft: 4, font: "500 12px var(--font-sans)", color: "var(--fg-subtle)" }}>MXN</span>
              </div>
            </div>
            {paymentType === "card" && msi > 1 && (
              <div className="body-sm" style={{ marginTop: -4 }}>{msi} MSI de <strong>${Math.round(total / msi).toLocaleString("es-MX")}</strong></div>
            )}
          </div>

          <div style={{ marginTop: 20, padding: 14, background: "var(--bg-elev-2)", borderRadius: "var(--radius-md)", display: "flex", alignItems: "center", gap: 10 }}>
            <AllenIcon name="lock" size={18} color="var(--fg-muted)" />
            <span className="body-sm" style={{ fontSize: 12 }}>Pago cifrado con TLS 1.3 · Cumple PCI DSS</span>
          </div>
        </aside>
      </div>
    </div>
  );
};

// =====================================================================
// Helpers
const Radio = ({ checked, onChange }) => (
  <span style={{
    width: 20, height: 20, borderRadius: 10, border: checked ? "6px solid var(--primary)" : "1.5px solid var(--border-input)",
    background: "var(--bg-elev-1)", flexShrink: 0, marginTop: 2,
    transition: "border var(--dur-fast)",
  }}
  onClick={onChange} />
);

const ReviewBlock = ({ title, icon, onEdit, children }) => (
  <div style={{ padding: "18px 0", borderBottom: "1px solid var(--border-soft)" }}>
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <AllenIcon name={icon} size={16} color="var(--primary)" />
        <h4 className="title-sm">{title}</h4>
      </div>
      {onEdit && <button onClick={onEdit} style={{ background: "transparent", border: 0, color: "var(--primary)", font: "700 12px var(--font-sans)", cursor: "pointer" }}>Editar</button>}
    </div>
    {children}
  </div>
);

const SumLine = ({ k, v, color }) => (
  <div style={{ display: "flex", justifyContent: "space-between", font: "500 14px var(--font-sans)" }}>
    <span style={{ color: "var(--fg-muted)" }}>{k}</span>
    <span style={{ color: color || "var(--fg-strong)", fontWeight: color ? 700 : 500 }}>{v}</span>
  </div>
);

const Spinner = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"
    style={{ animation: "spin 1s linear infinite" }}>
    <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
    <path d="M21 12a9 9 0 1 1-6.219-8.56" />
  </svg>
);

const detectCardBrand = (num) => {
  const n = num.replace(/\s/g, "");
  if (/^4/.test(n)) return "VISA";
  if (/^5[1-5]/.test(n) || /^2[2-7]/.test(n)) return "MASTERCARD";
  if (/^3[47]/.test(n)) return "AMEX";
  if (/^6/.test(n)) return "DISCOVER";
  return null;
};

window.CheckoutPage = CheckoutPage;
