// Checkout flow + Order confirmation

function CheckoutPage({ cart, fmt, ccy, account, library, setPage }) {
  const [step, setStep] = useState(1); // 1 contact, 2 payment, 3 review
  const [email, setEmail] = useState(account.user?.email || "");
  const [name,  setName]  = useState(account.user?.name || "");
  const [country, setCountry] = useState("United Kingdom");
  const [card, setCard] = useState("");
  const [orderId, setOrderId] = useState(null);

  if (cart.items.length === 0 && !orderId) {
    return (
      <div className="page-enter page-in container" style={{ paddingTop: 100, paddingBottom: 100, textAlign: "center" }}>
        <div className="serif-italic" style={{ fontSize: 36 }}>Your cart is empty.</div>
        <button className="btn btn-primary" style={{ marginTop: 24 }} onClick={() => setPage("shop")}>Browse the catalogue →</button>
      </div>
    );
  }

  const complete = () => {
    const id = "FBO-" + Math.floor(Math.random() * 9000 + 1000) + "-" + new Date().getFullYear();
    if (!account.user) account.signIn(email);
    library.add(cart.items);
    cart.clear();
    setOrderId(id);
  };

  if (orderId) return <OrderConfirmation orderId={orderId} email={email} setPage={setPage} fmt={fmt} />;

  return (
    <div className="page-enter page-in">
      <section className="container" style={{ paddingTop: 60, paddingBottom: 40 }}>
        <div className="eyebrow-rule">CHECKOUT</div>
        <h1 className="h-section" style={{ margin: "20px 0 0" }}>
          One step from <em>delivery.</em>
        </h1>
      </section>

      <section className="container" style={{ paddingTop: 30, paddingBottom: 100 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 48, alignItems: "start" }} data-mobile="stack">

          {/* LEFT — Steps */}
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <Step n="1" label="Contact"  active={step >= 1} done={step > 1} onClick={() => setStep(1)} />
            {step === 1 && (
              <div style={{ padding: 32, borderTop: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 16 }}>
                <Field label="Name"  value={name}  onChange={setName} />
                <Field label="Email — delivery goes here" value={email} onChange={setEmail} type="email" />
                <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  <span className="eyebrow">Country</span>
                  <select className="input" value={country} onChange={e => setCountry(e.target.value)}>
                    {["United Kingdom", "United States", "Hong Kong", "Singapore", "Australia", "Germany", "France", "Other"].map(c => <option key={c}>{c}</option>)}
                  </select>
                </label>
                <button className="btn btn-primary" style={{ marginTop: 8, alignSelf: "flex-start" }} onClick={() => setStep(2)}>Continue to payment →</button>
              </div>
            )}

            <Step n="2" label="Payment"  active={step >= 2} done={step > 2} onClick={() => step >= 2 && setStep(2)} />
            {step === 2 && (
              <div style={{ padding: 32, borderTop: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 18 }}>
                <div style={{ display: "flex", gap: 10 }}>
                  {["Card", "Apple Pay", "WeChat Pay", "Alipay"].map((m, i) => (
                    <button key={m} className={i === 0 ? "btn btn-primary btn-sm" : "btn btn-dark btn-sm"} style={{ flex: 1, justifyContent: "center" }}>{m}</button>
                  ))}
                </div>
                <Field label="Card number" value={card} onChange={setCard} placeholder="4242  4242  4242  4242" />
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                  <Field label="Expiry"  value="" onChange={() => {}} placeholder="MM / YY" />
                  <Field label="CVC"     value="" onChange={() => {}} placeholder="•••" />
                </div>
                <div style={{ fontSize: 12, color: "var(--text-3)", display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 3, background: "var(--success, var(--accent))" }} />
                  Secured by Stripe · 3-D Secure enabled · PCI-DSS compliant
                </div>
                <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
                  <button className="btn btn-ghost btn-sm" onClick={() => setStep(1)}>← Back</button>
                  <button className="btn btn-primary" onClick={() => setStep(3)}>Review order →</button>
                </div>
              </div>
            )}

            <Step n="3" label="Review & confirm" active={step >= 3} done={false} onClick={() => step >= 3 && setStep(3)} />
            {step === 3 && (
              <div style={{ padding: 32, borderTop: "1px solid var(--border)" }}>
                <div className="eyebrow" style={{ marginBottom: 14 }}>YOUR ORDER</div>
                {cart.items.map((it, i) => (
                  <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "12px 0", borderTop: i > 0 ? "1px solid var(--border)" : "none", fontSize: 14 }}>
                    <div>
                      <div>{it.company} <span style={{ color: "var(--text-3)" }}>· {it.variant}</span></div>
                      <div style={{ fontSize: 12, color: "var(--text-3)" }}>{it.role}</div>
                    </div>
                    <div className="mono" style={{ fontSize: 14 }}>{fmt(it.gbp * it.qty)}</div>
                  </div>
                ))}
                <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--border)", fontSize: 13, color: "var(--text-2)" }}>
                  Delivery to <strong style={{ color: "var(--text)" }}>{email || "—"}</strong> · {country}
                </div>
                <label style={{ display: "flex", gap: 10, marginTop: 18, fontSize: 12.5, color: "var(--text-2)" }}>
                  <input type="checkbox" defaultChecked />
                  <span>I agree to the <button onClick={() => setPage("terms")} style={{ color: "var(--accent)", textDecoration: "underline" }}>Terms</button> and <button onClick={() => setPage("refund")} style={{ color: "var(--accent)", textDecoration: "underline" }}>Refund Policy</button>.</span>
                </label>
                <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
                  <button className="btn btn-ghost btn-sm" onClick={() => setStep(2)}>← Back</button>
                  <button className="btn btn-primary" onClick={complete}>Place order — {fmt(cart.total)} →</button>
                </div>
              </div>
            )}
          </div>

          {/* RIGHT — Summary */}
          <aside style={{ position: "sticky", top: 120 }}>
            <div className="card" style={{ padding: 28 }}>
              <div className="eyebrow" style={{ marginBottom: 18 }}>ORDER SUMMARY</div>
              {cart.items.map((it, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, padding: "10px 0", borderTop: i > 0 ? "1px solid var(--border)" : "none" }}>
                  <span>{it.ticker} · {it.variant.split(" ")[0]}</span>
                  <span className="mono">{fmt(it.gbp * it.qty)}</span>
                </div>
              ))}
              <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--border)" }}>
                <Row label="Subtotal" value={fmt(cart.total)} />
                <Row label="VAT (auto-calculated)" value="—" muted />
                <Row label={`Total · ${ccy.code}`} value={fmt(cart.total)} bold />
              </div>
              <div style={{ marginTop: 18, padding: 14, background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 8, fontSize: 12, color: "var(--text-2)", lineHeight: 1.55 }}>
                <strong style={{ color: "var(--text)" }}>Instant delivery.</strong> A secure cloud link lands in your inbox seconds after payment. Lifetime access on the device of your choice.
              </div>
            </div>
          </aside>
        </div>
      </section>
    </div>
  );
}

function Step({ n, label, active, done, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: "100%", textAlign: "left",
      padding: "18px 28px",
      borderTop: n === "1" ? "none" : "1px solid var(--border)",
      display: "flex", alignItems: "center", gap: 16,
      opacity: active ? 1 : 0.55,
      cursor: active ? "pointer" : "default",
    }}>
      <span style={{
        width: 28, height: 28, borderRadius: 999,
        border: "1px solid", borderColor: active ? "var(--accent)" : "var(--border-strong)",
        background: done ? "var(--accent)" : "transparent",
        color: done ? "var(--accent-fg)" : active ? "var(--accent)" : "var(--text-3)",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: "var(--mono)", fontSize: 12, fontWeight: 600,
      }}>{done ? "✓" : n}</span>
      <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 22 }}>{label}</span>
    </button>
  );
}
function Row({ label, value, bold, muted }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", fontSize: bold ? 16 : 13, fontWeight: bold ? 500 : 400, color: muted ? "var(--text-3)" : "var(--text)" }}>
      <span>{label}</span>
      <span className="mono">{value}</span>
    </div>
  );
}

function OrderConfirmation({ orderId, email, setPage, fmt }) {
  return (
    <div className="page-enter page-in">
      <section className="container" style={{ paddingTop: 80, paddingBottom: 80 }}>
        <div style={{ maxWidth: 720 }}>
          <div className="eyebrow-rule">ORDER CONFIRMED</div>
          <h1 className="h-section" style={{ margin: "24px 0 0" }}>
            Your library is <em>ready.</em>
          </h1>
          <p style={{ marginTop: 28, fontSize: 17, color: "var(--text-2)", lineHeight: 1.55 }}>
            A delivery email is on its way to <strong style={{ color: "var(--text)" }}>{email}</strong> with secure download links. Everything you bought is also waiting in your library — open it whenever you're ready.
          </p>

          <div className="card" style={{ marginTop: 40, padding: 28 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18 }}>
              <div>
                <div className="eyebrow">ORDER REFERENCE</div>
                <div className="mono" style={{ fontSize: 22, marginTop: 6 }}>{orderId}</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="eyebrow">RECEIPT</div>
                <div style={{ fontSize: 13, color: "var(--text-2)", marginTop: 8 }}>Sent to your inbox</div>
              </div>
            </div>
            <div style={{ paddingTop: 18, borderTop: "1px solid var(--border)", fontSize: 13, color: "var(--text-2)", lineHeight: 1.6 }}>
              Keep this reference for any future support or refund queries. Refunds are available within 48 hours on undownloaded items — just reply to your delivery email.
            </div>
          </div>

          <div style={{ display: "flex", gap: 10, marginTop: 36 }}>
            <button className="btn btn-primary" onClick={() => setPage("library")}>Open my library →</button>
            <button className="btn btn-ghost"   onClick={() => setPage("shop")}>Keep browsing</button>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { CheckoutPage });
