// Page: Cart — review + Stripe Checkout
const { useState: useStateCart } = React;

function CartPage({ cart, setQty, removeItem, clearCart, navigate, pushToast }) {
  const [busy, setBusy] = useStateCart(false);
  const [err, setErr] = useStateCart("");

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

  async function checkout() {
    if (cart.length === 0) return;
    setBusy(true);
    setErr("");
    try {
      const res = await fetch("/api/checkout-session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          items: cart.map((it) => ({ id: it.id, qty: it.qty })),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.url) {
        throw new Error(data.error || "Checkout could not be started");
      }
      window.location.href = data.url;
    } catch (e) {
      console.error("[checkout]", e);
      setErr(e.message);
      pushToast && pushToast("Couldn't start checkout — please try again.");
      setBusy(false);
    }
  }

  return (
    <main id="main">
      <PageHeader
        eyebrow="Your cart"
        title="Ready to check out?"
        sub="Review your selections below, then continue to secure payment via Stripe. UK shipping is collected at checkout."
      />

      <section className="section" style={{ paddingTop: 32 }}>
        <div className="container">
          <div className="two-col" style={{ alignItems: "start" }}>
            <div>
              <h2 style={{ fontSize: "1.4rem", marginBottom: 16 }}>Items ({cart.length})</h2>
              {cart.length === 0 ? (
                <div className="empty">
                  <h3>Your cart is empty</h3>
                  <p>Browse the studio shop and add a few favourites.</p>
                  <button className="btn btn-primary" style={{ marginTop: 16 }}
                          onClick={() => navigate("products")}>
                    Browse products <Icon.Arrow />
                  </button>
                </div>
              ) : (
                <div>
                  {cart.map((it) => (
                    <div key={it.id} className="cart-row">
                      <div className="thumb"><img src={it.image} alt={it.name} /></div>
                      <div>
                        <div style={{ fontFamily: "var(--font-serif)", fontSize: "1.05rem" }}>{it.name}</div>
                        <div style={{ fontSize: 13, color: "var(--muted)" }}>{it.category} · £{it.price} each</div>
                        <div className="qty" style={{ marginTop: 8 }}>
                          <button onClick={() => setQty(it.id, it.qty - 1)} aria-label="Decrease">−</button>
                          <span className="n">{it.qty}</span>
                          <button onClick={() => setQty(it.id, it.qty + 1)} aria-label="Increase">+</button>
                        </div>
                      </div>
                      <div style={{ fontFamily: "var(--font-serif)", fontSize: "1.05rem" }}>£{it.qty * it.price}</div>
                      <button className="btn btn-ghost btn-sm" onClick={() => removeItem(it.id)} aria-label={`Remove ${it.name}`}>
                        <Icon.Trash />
                      </button>
                    </div>
                  ))}
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 24 }}>
                    <button className="btn btn-ghost btn-sm" onClick={clearCart}>Clear all</button>
                    <div style={{ textAlign: "right" }}>
                      <div style={{ fontSize: 13, color: "var(--muted)" }}>Subtotal</div>
                      <div style={{ fontFamily: "var(--font-serif)", fontSize: "1.8rem", color: "var(--accent)" }}>£{total}</div>
                    </div>
                  </div>
                </div>
              )}
            </div>

            <aside style={{ background: "var(--surface)", padding: 24, borderRadius: "var(--radius)", border: "1px solid var(--line)" }}>
              <h3 style={{ fontFamily: "var(--font-serif)", marginBottom: 8 }}>Order summary</h3>
              <p style={{ color: "var(--ink-2)", fontSize: 14, marginBottom: 16 }}>
                Tax and shipping (UK) calculated at checkout.
              </p>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 16 }}>
                <span>Subtotal</span>
                <strong>£{total}</strong>
              </div>
              <button className="btn btn-primary" onClick={checkout}
                      disabled={cart.length === 0 || busy}
                      style={{ width: "100%", opacity: (cart.length === 0 || busy) ? 0.6 : 1 }}>
                {busy ? "Starting checkout…" : <React.Fragment>Checkout with Stripe <Icon.Arrow /></React.Fragment>}
              </button>
              {err && <div className="error-text" style={{ marginTop: 12 }}>{err}</div>}
              <p style={{ fontSize: 12, color: "var(--muted)", marginTop: 12 }}>
                Payments are processed securely by Stripe. We never see your card details.
              </p>
            </aside>
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { CartPage });
