// Cart.jsx — shopping cart + checkout step
const { useState: useCartState } = React;

const Cart = ({ cart, onChangeQty, onRemove, onNav, onCheckout }) => {
  const { isMobile } = useViewport();
  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 [coupon, setCoupon] = useCartState("");

  return (
    <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: isMobile ? "0 16px" : "0 32px" }}>
      <Breadcrumb items={["Inicio", "Mi carrito"]} />
      <h1 className="display-sm" style={{ marginBottom: 8 }}>Mi carrito</h1>
      <p className="body-sm" style={{ marginBottom: 28 }}>{cart.length} {cart.length === 1 ? "producto" : "productos"} listos para tu compra</p>

      {cart.length === 0 ? (
        <div style={{ padding: 80, textAlign: "center", background: "var(--bg-elev-1)", borderRadius: "var(--radius-xl)", border: "1px solid var(--border-soft)" }}>
          <AllenIcon name="shopping_cart" size={56} color="var(--fg-hint)" />
          <h2 className="headline-sm" style={{ marginTop: 16 }}>Tu carrito está vacío</h2>
          <p className="body" style={{ marginTop: 8, color: "var(--fg-muted)" }}>Cuando agregues productos los verás aquí.</p>
          <button onClick={() => onNav("home")} style={{ marginTop: 20, background: "var(--primary)", color: "#fff", border: 0, padding: "14px 28px", borderRadius: "9999px", font: "700 14px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)" }}>Seguir comprando</button>
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 380px", gap: isMobile ? 16 : 32, alignItems: "start" }}>
          {/* items */}
          <div style={{ background: "var(--bg-elev-1)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-soft)", overflow: "hidden" }}>
            {cart.map((it, i) => (
              <div key={it.p.id} style={{ display: "grid", gridTemplateColumns: "100px 1fr auto", gap: 20, padding: 20, borderBottom: i === cart.length - 1 ? "none" : "1px solid var(--border-soft)" }}>
                <div style={{ aspectRatio: 1, borderRadius: "var(--radius-md)", overflow: "hidden", background: it.p.imgBg }}>
                  <img src={it.p.img} alt={it.p.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </div>
                <div>
                  <div className="label-sm" style={{ color: "var(--fg-subtle)" }}>{it.p.brand}</div>
                  <a onClick={() => onNav("pdp", { id: it.p.id })} className="title-sm" style={{ cursor: "pointer", display: "block", marginTop: 4 }}>{it.p.name}</a>
                  <div className="body-sm" style={{ marginTop: 6, color: "var(--success)", fontWeight: 600 }}>
                    <AllenIcon name="local_shipping" size={14} /> {it.p.shipping || "Llegada en 3-5 días"}
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 12 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 4, padding: 4, border: "1px solid var(--border-strong)", borderRadius: "9999px" }}>
                      <button onClick={() => onChangeQty(it.p.id, Math.max(1, it.qty - 1))} style={iconBtn}><AllenIcon name="remove" size={16} /></button>
                      <span style={{ width: 28, textAlign: "center", font: "700 13px var(--font-sans)" }}>{it.qty}</span>
                      <button onClick={() => onChangeQty(it.p.id, it.qty + 1)} style={iconBtn}><AllenIcon name="add" size={16} /></button>
                    </div>
                    <button onClick={() => onRemove(it.p.id)} style={{ background: "transparent", border: 0, color: "var(--fg-muted)", font: "600 13px var(--font-sans)", cursor: "pointer", display: "flex", alignItems: "center", gap: 4 }}>
                      <AllenIcon name="delete" size={16} /> Eliminar
                    </button>
                    <button style={{ background: "transparent", border: 0, color: "var(--fg-muted)", font: "600 13px var(--font-sans)", cursor: "pointer" }}>Guardar para después</button>
                  </div>
                </div>
                <div style={{ textAlign: "right", display: "flex", flexDirection: "column", justifyContent: "space-between", alignItems: "flex-end" }}>
                  <div>
                    <div className="price-lg">${(it.p.price * it.qty).toLocaleString("es-MX")}</div>
                    {it.p.was && <div style={{ font: "500 12px var(--font-sans)", color: "var(--fg-hint)", textDecoration: "line-through", marginTop: 2 }}>${(it.p.was * it.qty).toLocaleString("es-MX")}</div>}
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* summary */}
          <aside style={{ background: "var(--bg-elev-1)", borderRadius: "var(--radius-lg)", padding: 24, position: isMobile ? "static" : "sticky", top: 160, border: "1px solid var(--border-soft)" }}>
            <h3 className="title-lg" style={{ marginBottom: 18 }}>Resumen de compra</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <Line k="Subtotal" v={`$${subtotal.toLocaleString("es-MX")}`} />
              {savings > 0 && <Line k="Ahorras" v={`−$${savings.toLocaleString("es-MX")}`} color="var(--discount)" />}
              <Line 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 }}>
                <div style={{ 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>
                <div className="body-sm" style={{ marginTop: 4 }}>o 12 MSI de <strong>${Math.round(total / 12).toLocaleString("es-MX")}</strong></div>
              </div>
            </div>

            {/* coupon */}
            <div style={{ marginTop: 18, display: "flex", gap: 8 }}>
              <input value={coupon} onChange={e => setCoupon(e.target.value)} placeholder="Código de cupón"
                style={{ flex: 1, padding: "10px 14px", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-input)", font: "400 13px var(--font-sans)", outline: 0 }} />
              <button style={{ background: "var(--bg-section)", color: "var(--fg-strong)", border: "1px solid var(--border-strong)", padding: "10px 16px", borderRadius: "var(--radius-input)", font: "700 13px var(--font-sans)", cursor: "pointer" }}>Aplicar</button>
            </div>

            <button onClick={onCheckout} style={{ width: "100%", marginTop: 20, background: "var(--primary)", color: "#fff", border: 0, padding: "16px 24px", borderRadius: "9999px", font: "700 15px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)" }}>
              Confirmar compra
            </button>
            <p className="body-sm" style={{ marginTop: 12, textAlign: "center" }}>
              <AllenIcon name="lock" size={13} /> Pago seguro · Tarjeta o MSI
            </p>
          </aside>
        </div>
      )}
    </div>
  );
};

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

// ---------------------------------------------------------------
// CheckoutDone — receipt screen with order summary, address, payment, ETA, invoice.
const CheckoutDone = ({ order, onNav }) => {
  // Backwards compat: in case caller still passes orderNum as a string
  const orderNum = order?.orderNum || order || "AL-000000";
  const o = typeof order === "object" ? order : null;
  return (
    <div style={{ maxWidth: 880, margin: "40px auto 80px", padding: "0 32px" }}>
      {/* Hero */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <div style={{ width: 88, height: 88, borderRadius: 44, background: "var(--success-bg)", display: "grid", placeItems: "center", margin: "0 auto 20px", animation: "checkPop .4s var(--ease-out-quart)" }}>
          <style>{`@keyframes checkPop { from { transform: scale(0.6); opacity: 0 } to { transform: scale(1); opacity: 1 } }`}</style>
          <AllenIcon name="check_circle" size={52} fill={1} color="var(--success)" />
        </div>
        <h1 className="display-sm">¡Listo, tu compra fue confirmada!</h1>
        <p className="body-lg" style={{ marginTop: 12, color: "var(--fg-muted)" }}>
          Pedido <strong style={{ color: "var(--fg-strong)" }}>#{orderNum}</strong>. Te enviamos los detalles a tu correo.
        </p>
      </div>

      {/* Receipt card */}
      <div style={{ background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-xl)", overflow: "hidden" }}>
        {/* ETA banner */}
        <div style={{ padding: "20px 28px", background: "var(--primary-soft)", display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 22, background: "var(--primary)", color: "#fff", display: "grid", placeItems: "center" }}>
            <AllenIcon name="local_shipping" size={22} color="#fff" />
          </div>
          <div style={{ flex: 1 }}>
            <div className="title">Llegada estimada: viernes 5 de marzo</div>
            <div className="body-sm" style={{ marginTop: 2 }}>Entre 10:00 y 18:00. Te avisamos por correo y notificación cuando salga del centro Allen Vallarta.</div>
          </div>
        </div>

        {o && (
          <>
            {/* Address + payment */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0, borderBottom: "1px solid var(--border-soft)" }}>
              <div style={{ padding: "24px 28px", borderRight: "1px solid var(--border-soft)" }}>
                <div className="label" style={{ marginBottom: 8 }}>Entregar a</div>
                <div className="body" style={{ color: "var(--fg-strong)" }}>{o.address.name}</div>
                <div className="body-sm">{o.address.street}</div>
                <div className="body-sm">{o.address.area} · CP {o.address.zip}</div>
              </div>
              <div style={{ padding: "24px 28px" }}>
                <div className="label" style={{ marginBottom: 8 }}>Pago</div>
                {o.payment.type === "card" && o.payment.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" }}>{o.payment.card.brand}</span>
                      <span style={{ fontFamily: "var(--font-mono)" }}>•••• {o.payment.card.last4}</span>
                    </div>
                    {o.payment.msi > 1 && <div className="body-sm" style={{ marginTop: 4 }}>{o.payment.msi} MSI de ${Math.round(o.total / o.payment.msi).toLocaleString("es-MX")}</div>}
                  </>
                )}
                {o.payment.type === "newCard" && <div className="body" style={{ color: "var(--fg-strong)" }}>Tarjeta nueva guardada</div>}
                {o.payment.type === "oxxo" && (
                  <>
                    <div className="body" style={{ color: "var(--fg-strong)" }}>OXXO efectivo</div>
                    <div className="body-sm" style={{ marginTop: 4, color: "var(--warning)", fontWeight: 600 }}>⏱ Tienes 48h para pagar la ficha</div>
                  </>
                )}
              </div>
            </div>

            {/* Items */}
            <div style={{ padding: "24px 28px", borderBottom: "1px solid var(--border-soft)" }}>
              <div className="label" style={{ marginBottom: 14 }}>Productos ({o.items.length})</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {o.items.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>
            </div>

            {/* Total */}
            <div style={{ padding: "20px 28px", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span className="title-lg">Total pagado</span>
              <span className="price-xl">${o.total.toLocaleString("es-MX")}</span>
            </div>
          </>
        )}
      </div>

      {/* Actions */}
      <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 32, flexWrap: "wrap" }}>
        <button onClick={() => onNav("home")} style={{ background: "var(--primary)", color: "#fff", border: 0, padding: "14px 28px", borderRadius: "9999px", font: "700 14px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)" }}>Seguir comprando</button>
        <button onClick={() => onNav("account", { tab: "compras" })} style={{ background: "transparent", color: "var(--primary)", border: "1.5px solid var(--primary)", padding: "14px 28px", borderRadius: "9999px", font: "700 14px var(--font-sans)", cursor: "pointer" }}>Ver mis pedidos</button>
        <button style={{ background: "transparent", color: "var(--fg-strong)", border: "1.5px solid var(--border-strong)", padding: "14px 28px", borderRadius: "9999px", font: "700 14px var(--font-sans)", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8 }}>
          <AllenIcon name="credit_card" size={16} /> Descargar factura
        </button>
      </div>

      {/* Trust strip */}
      <div style={{ marginTop: 40, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
        {[
          { icon: "verified",       title: "Compra protegida",   sub: "Devolución gratis hasta 30 días" },
          { icon: "local_shipping", title: "Seguimiento en vivo",sub: "Te avisamos en cada cambio" },
          { icon: "support_agent",  title: "Soporte 24/7",       sub: "Estamos por correo y WhatsApp" },
        ].map(t => (
          <div key={t.icon} style={{ display: "flex", alignItems: "center", gap: 12, padding: 18, background: "var(--bg-elev-1)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)" }}>
            <AllenIcon name={t.icon} size={22} color="var(--primary)" />
            <div>
              <div className="title-sm">{t.title}</div>
              <div className="body-sm" style={{ marginTop: 2, fontSize: 12 }}>{t.sub}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

window.Cart = Cart;
window.CheckoutDone = CheckoutDone;
