function CheckoutPage({ navigate, items, clearCart }) {
  const [step, setStep] = useState(items.length ? 1 : 0); // 1=details, 2=shipping, 3=payment, 4=confirm
  const [info, setInfo] = useState({
    name: "", email: "",
    addr1: "", addr2: "", city: "", region: "", postal: "", country: "Canada",
    cardName: "", cardNum: "", cardExp: "", cardCvv: "",
    save: true,
  });
  const subtotal = items.reduce((s, i) => s + i.price, 0);
  const shipping = subtotal === 0 ? 0 : (subtotal > 2000 ? 0 : 95);
  const total = subtotal + shipping;

  if (items.length === 0 && step < 4) {
    return (
      <div className="page-enter" style={{ paddingTop: 200, paddingBottom: 200, textAlign: "center", maxWidth: 640, margin: "0 auto" }}>
        <div className="eyebrow">Checkout</div>
        <h1 className="h-display" style={{ fontSize: "clamp(40px, 5vw, 64px)", marginTop: 14, fontStyle: "italic" }}>
          Your cart is quiet.
        </h1>
        <p style={{ marginTop: 18, color: "var(--ink-soft)" }}>Begin in the gallery — every painting is one of one.</p>
        <button className="btn btn-primary" style={{ marginTop: 28 }} onClick={() => navigate("gallery")}>Enter the Gallery <Icon.ArrowR /></button>
      </div>
    );
  }

  if (step === 4) {
    return <Confirmation info={info} items={items} total={total} navigate={navigate} />;
  }

  const setField = (k, v) => setInfo((s) => ({ ...s, [k]: v }));

  return (
    <div className="page-enter" style={{ paddingTop: 120, paddingBottom: 100 }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "0 40px" }}>
        <div style={{ textAlign: "center", marginBottom: 40 }}>
          <div className="eyebrow">Checkout</div>
          <h1 className="h-display" style={{ fontSize: "clamp(36px, 4.4vw, 56px)", marginTop: 10, fontStyle: "italic" }}>
            A quiet acquisition.
          </h1>
        </div>

        {/* Stepper */}
        <div style={{ display: "flex", justifyContent: "center", gap: 0, marginBottom: 50 }}>
          {["Your Details", "Shipping", "Payment"].map((s, i) => {
            const n = i + 1;
            const active = step === n;
            const done = step > n;
            return (
              <div key={s} style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 999,
                  background: done ? "var(--gold)" : (active ? "var(--ink)" : "transparent"),
                  border: "1px solid " + (done || active ? "transparent" : "var(--line)"),
                  color: done || active ? "var(--warm-white)" : "var(--ink-mute)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "var(--serif)", fontSize: 15,
                }}>{done ? <Icon.Check /> : n}</div>
                <span style={{
                  fontSize: 11.5, letterSpacing: "0.2em", textTransform: "uppercase",
                  color: active ? "var(--ink)" : "var(--ink-mute)", fontWeight: 500,
                }}>{s}</span>
                {i < 2 && <div style={{ width: 60, height: 1, background: "var(--line)", margin: "0 18px" }} />}
              </div>
            );
          })}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 60, alignItems: "start" }}>
          {/* LEFT: Form */}
          <div style={{ background: "var(--warm-white)", padding: 44, border: "1px solid var(--line-soft)" }}>
            {step === 1 && (
              <div>
                <h2 style={{ fontFamily: "var(--serif)", fontSize: 28, margin: 0 }}>Your details</h2>
                <p style={{ fontSize: 13.5, color: "var(--ink-soft)", marginTop: 6 }}>No account needed — we'll send the confirmation by email.</p>
                <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <label className="lf-label">Full name</label>
                    <input className="lf-input" value={info.name} onChange={(e) => setField("name", e.target.value)} placeholder="Eleanor Whitmore" />
                  </div>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <label className="lf-label">Email</label>
                    <input className="lf-input" value={info.email} onChange={(e) => setField("email", e.target.value)} placeholder="you@home.com" type="email" />
                  </div>
                </div>
                <button className="btn btn-primary" style={{ marginTop: 32 }} onClick={() => setStep(2)}>Continue to Shipping <Icon.ArrowR /></button>
              </div>
            )}

            {step === 2 && (
              <div>
                <h2 style={{ fontFamily: "var(--serif)", fontSize: 28, margin: 0 }}>Where shall it arrive?</h2>
                <p style={{ fontSize: 13.5, color: "var(--ink-soft)", marginTop: 6 }}>We ship insured, worldwide. Average 7–12 business days.</p>
                <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <label className="lf-label">Street address</label>
                    <input className="lf-input" value={info.addr1} onChange={(e) => setField("addr1", e.target.value)} placeholder="142 Maple Lane" />
                  </div>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <label className="lf-label">Apartment / suite</label>
                    <input className="lf-input" value={info.addr2} onChange={(e) => setField("addr2", e.target.value)} placeholder="Optional" />
                  </div>
                  <div>
                    <label className="lf-label">City</label>
                    <input className="lf-input" value={info.city} onChange={(e) => setField("city", e.target.value)} placeholder="Toronto" />
                  </div>
                  <div>
                    <label className="lf-label">Province / State</label>
                    <input className="lf-input" value={info.region} onChange={(e) => setField("region", e.target.value)} placeholder="Ontario" />
                  </div>
                  <div>
                    <label className="lf-label">Postal / Zip</label>
                    <input className="lf-input" value={info.postal} onChange={(e) => setField("postal", e.target.value)} placeholder="M5V 2T6" />
                  </div>
                  <div>
                    <label className="lf-label">Country</label>
                    <select className="lf-input" value={info.country} onChange={(e) => setField("country", e.target.value)} style={{ appearance: "none" }}>
                      <option>Canada</option>
                      <option>United States</option>
                      <option>United Kingdom</option>
                      <option>France</option>
                      <option>Germany</option>
                      <option>Australia</option>
                      <option>New Zealand</option>
                      <option>Japan</option>
                    </select>
                  </div>
                </div>
                <div style={{ display: "flex", gap: 12, marginTop: 32 }}>
                  <button className="btn btn-ghost" onClick={() => setStep(1)}><Icon.ArrowL /> Back</button>
                  <button className="btn btn-primary" onClick={() => setStep(3)}>Continue to Payment <Icon.ArrowR /></button>
                </div>
              </div>
            )}

            {step === 3 && (
              <div>
                <h2 style={{ fontFamily: "var(--serif)", fontSize: 28, margin: 0 }}>Payment</h2>
                <p style={{ fontSize: 13.5, color: "var(--ink-soft)", marginTop: 6 }}>
                  Secured by Stripe. We never see or store your card details.
                </p>

                {/* Card mock */}
                <div style={{
                  marginTop: 24, padding: 24,
                  background: "linear-gradient(135deg, var(--ink) 0%, #4a4138 100%)",
                  color: "var(--warm-white)", borderRadius: 12, aspectRatio: "16/9", maxWidth: 380,
                  position: "relative", overflow: "hidden",
                }}>
                  <div style={{ position: "absolute", right: -40, top: -40, width: 200, height: 200, borderRadius: 999, background: "radial-gradient(circle, var(--gold) 0%, transparent 70%)", opacity: 0.4 }} />
                  <div style={{ fontSize: 11, letterSpacing: "0.22em", opacity: 0.7, textTransform: "uppercase" }}>Studio Card</div>
                  <div style={{ marginTop: 28, fontFamily: "var(--serif)", fontSize: 22, letterSpacing: "0.12em" }}>
                    {(info.cardNum || "•••• •••• •••• ••••").padEnd(19, "•").slice(0, 19)}
                  </div>
                  <div style={{ marginTop: 26, display: "flex", justifyContent: "space-between", fontSize: 11, letterSpacing: "0.14em" }}>
                    <div>{(info.cardName || "Cardholder Name").toUpperCase()}</div>
                    <div>{info.cardExp || "MM / YY"}</div>
                  </div>
                </div>

                <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <label className="lf-label">Name on card</label>
                    <input className="lf-input" value={info.cardName} onChange={(e) => setField("cardName", e.target.value)} placeholder="As shown on card" />
                  </div>
                  <div style={{ gridColumn: "1 / -1" }}>
                    <label className="lf-label">Card number</label>
                    <input className="lf-input" value={info.cardNum} onChange={(e) => setField("cardNum", formatCard(e.target.value))} placeholder="4242 4242 4242 4242" maxLength={19} />
                  </div>
                  <div>
                    <label className="lf-label">Expiry</label>
                    <input className="lf-input" value={info.cardExp} onChange={(e) => setField("cardExp", formatExp(e.target.value))} placeholder="MM / YY" maxLength={7} />
                  </div>
                  <div>
                    <label className="lf-label">CVV</label>
                    <input className="lf-input" value={info.cardCvv} onChange={(e) => setField("cardCvv", e.target.value.replace(/\D/g, ""))} placeholder="123" maxLength={4} />
                  </div>
                </div>

                <div style={{ marginTop: 22, padding: 16, background: "var(--cream)", borderRadius: 4, display: "flex", gap: 12, alignItems: "flex-start" }}>
                  <div style={{ color: "var(--gold-deep)", marginTop: 2 }}><Icon.Check /></div>
                  <div style={{ fontSize: 12.5, color: "var(--ink-soft)", lineHeight: 1.6 }}>
                    PCI-compliant, end-to-end encrypted. Your card never touches our servers. A receipt is emailed
                    instantly; Larissa is notified personally.
                  </div>
                </div>

                <div style={{ display: "flex", gap: 12, marginTop: 28 }}>
                  <button className="btn btn-ghost" onClick={() => setStep(2)}><Icon.ArrowL /> Back</button>
                  <button className="btn btn-primary" onClick={() => setStep(4)}>
                    Place Order · ${total.toLocaleString()} CAD <Icon.ArrowR />
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* RIGHT: Order summary */}
          <aside style={{ position: "sticky", top: 110 }}>
            <div style={{ background: "var(--paper)", padding: 32 }}>
              <div className="eyebrow" style={{ color: "var(--gold-deep)" }}>Your Selection</div>
              <h3 style={{ fontFamily: "var(--serif)", fontSize: 22, margin: "10px 0 22px" }}>Order Summary</h3>

              {items.map((p) => (
                <div key={p.id} style={{ display: "grid", gridTemplateColumns: "72px 1fr auto", gap: 14, alignItems: "start", padding: "14px 0", borderTop: "1px solid var(--line-soft)" }}>
                  <Painting p={p} aspect="4/5" tag={false} />
                  <div>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 16, lineHeight: 1.2 }}>{p.title}</div>
                    <div style={{ fontSize: 11, color: "var(--ink-mute)", marginTop: 4 }}>{p.dims}</div>
                  </div>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 15 }}>${p.price.toLocaleString()}</div>
                </div>
              ))}

              <div style={{ marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--line)" }}>
                <Row k="Subtotal" v={`$${subtotal.toLocaleString()} CAD`} />
                <Row k="Insured shipping" v={shipping === 0 ? "Complimentary" : `$${shipping} CAD`} />
                <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--line-soft)",
                                display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <span style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--ink-soft)" }}>Total</span>
                  <span style={{ fontFamily: "var(--serif)", fontSize: 26 }}>${total.toLocaleString()}<span style={{ fontSize: 12, color: "var(--ink-mute)", marginLeft: 6 }}>CAD</span></span>
                </div>
              </div>

              <div style={{ marginTop: 24, padding: 18, background: "var(--warm-white)", border: "1px solid var(--line-soft)" }}>
                <div className="h-script" style={{ fontSize: 24, color: "var(--gold-deep)", lineHeight: 1 }}>From the studio,</div>
                <p style={{ marginTop: 8, fontSize: 13, color: "var(--ink-soft)", lineHeight: 1.7 }}>
                  A hand-written note from Larissa and one small dried wildflower from the studio garden
                  travel in the crate with your painting. Always.
                </p>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

function Row({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, fontSize: 13.5, color: "var(--ink-soft)" }}>
      <span>{k}</span>
      <span style={{ color: "var(--ink)" }}>{v}</span>
    </div>
  );
}

function formatCard(v) {
  const d = v.replace(/\D/g, "").slice(0, 16);
  return d.replace(/(.{4})/g, "$1 ").trim();
}
function formatExp(v) {
  const d = v.replace(/\D/g, "").slice(0, 4);
  if (d.length < 3) return d;
  return d.slice(0, 2) + " / " + d.slice(2);
}

/* ============== Confirmation ============== */
function Confirmation({ info, items, total, navigate }) {
  // Capture the order, then clear cart on next mount
  useEffect(() => {
    return () => {};
  }, []);
  const orderNo = useMemo(() => "LFA-" + Math.floor(100000 + Math.random() * 899999), []);
  const eta = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() + 10);
    return d.toLocaleDateString("en-CA", { weekday: "long", month: "long", day: "numeric" });
  }, []);

  return (
    <div className="page-enter" style={{ paddingTop: 140, paddingBottom: 120 }}>
      <div style={{ maxWidth: 880, margin: "0 auto", padding: "0 40px", textAlign: "center" }}>
        <div className="h-script" style={{ fontSize: 96, color: "var(--gold-deep)", lineHeight: 0.9 }}>
          Thank you,<br />truly.
        </div>
        <h1 className="h-display" style={{ fontSize: "clamp(36px, 4.4vw, 56px)", marginTop: 28, fontStyle: "italic" }}>
          Your painting is in good hands.
        </h1>
        <p style={{ marginTop: 22, color: "var(--ink-soft)", fontSize: 17, lineHeight: 1.75, maxWidth: 620, margin: "22px auto 0" }}>
          A confirmation is on its way to <strong style={{ color: "var(--ink)" }}>{info.email || "your inbox"}</strong>.
          Larissa has been notified personally and will write to you in the next day or so.
        </p>

        <div style={{ marginTop: 40, padding: "32px 36px", background: "var(--cream)",
                       border: "1px solid var(--line-soft)", textAlign: "left" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24, paddingBottom: 24, borderBottom: "1px solid var(--line)" }}>
            <SmallStat label="Order" value={orderNo} />
            <SmallStat label="Total" value={`$${total.toLocaleString()} CAD`} />
            <SmallStat label="Estimated arrival" value={eta} />
          </div>

          <div style={{ marginTop: 24 }}>
            {items.map((p) => (
              <div key={p.id} style={{ display: "grid", gridTemplateColumns: "92px 1fr", gap: 18, alignItems: "center", padding: "14px 0", borderBottom: "1px solid var(--line-soft)" }}>
                <Painting p={p} aspect="4/5" tag={false} />
                <div>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 20 }}>{p.title}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{p.medium} · {p.dims} · {p.year}</div>
                </div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 24 }}>
            <div className="eyebrow">What happens next</div>
            <ol style={{ marginTop: 14, paddingLeft: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                "Tomorrow, Larissa writes you a short note by hand and registers your painting in the studio archive.",
                "Within four days the painting is crated in museum-quality archival packaging.",
                "Your courier picks it up; you receive insured tracking by email.",
                "Care instructions and a small dried wildflower travel in the crate. Enjoy.",
              ].map((s, i) => (
                <li key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 14, fontSize: 14.5, color: "var(--ink-soft)", lineHeight: 1.6 }}>
                  <span style={{
                    width: 22, height: 22, borderRadius: 999,
                    background: "var(--gold)", color: "var(--warm-white)",
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    fontFamily: "var(--serif)", fontSize: 12,
                  }}>{i + 1}</span>
                  {s}
                </li>
              ))}
            </ol>
          </div>
        </div>

        <div style={{ marginTop: 40, display: "flex", justifyContent: "center", gap: 14, flexWrap: "wrap" }}>
          <button className="btn btn-primary" onClick={() => navigate("gallery")}>Continue Browsing</button>
          <button className="btn btn-ghost" onClick={() => navigate("home")}>Back to the Studio</button>
        </div>

        <div style={{ marginTop: 60, fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18, color: "var(--ink-soft)" }}>
          "May this painting bring more light into your home than it took from mine to make it."
        </div>
        <div className="h-script" style={{ fontSize: 28, color: "var(--gold-deep)", marginTop: 4 }}>— Larissa</div>
      </div>
    </div>
  );
}

function SmallStat({ label, value }) {
  return (
    <div>
      <div style={{ fontSize: 10, letterSpacing: "0.22em", color: "var(--ink-mute)", textTransform: "uppercase" }}>{label}</div>
      <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginTop: 6 }}>{value}</div>
    </div>
  );
}

window.CheckoutPage = CheckoutPage;
