/* Merch checkout — desktop #checkout. No payment: invoice emailed after order. */
function MerchQty({ value, onChange }) {
  const b = { width: 30, height: 30, borderRadius: 999, border: "1px solid var(--c-line)", background: "transparent", color: "var(--c-ink)", cursor: "pointer", fontSize: 16, lineHeight: 1, display: "grid", placeItems: "center" };
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <button type="button" aria-label="Decrease" onClick={() => onChange(value - 1)} style={b}>−</button>
      <span className="mono" style={{ minWidth: 16, textAlign: "center" }}>{value}</span>
      <button type="button" aria-label="Increase" onClick={() => onChange(value + 1)} style={b}>+</button>
    </div>);
}

function MerchCheckoutDesktopPage() {
  const cart = useMerchCart(MERCH_PRODUCTS);
  const [d, setD] = React.useState({ name: "", email: "", phone: "", fulfillment: "delivery", street: "", city: "London", postal: "", notes: "" });
  const [sending, setSending] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [done, setDone] = React.useState(null);
  const up = (k) => (e) => setD({ ...d, [k]: e.target.value });
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.email);
  const addrOk = d.fulfillment === "pickup" || (d.street.trim() && d.city.trim());
  const ready = cart.count > 0 && d.name.trim() && emailOk && addrOk;

  React.useEffect(() => { window.scrollTo(0, 0); }, [done]);

  if (done) return (
    <section data-screen-label="Order placed" style={{ padding: "80px 0 110px" }}>
      <div className="container" style={{ maxWidth: 760, textAlign: "center" }}>
        <Eyebrow color="var(--c-red)">Order received</Eyebrow>
        <h1 className="display" style={{ margin: "16px 0 0", fontSize: "clamp(52px, 7vw, 96px)", lineHeight: 0.92 }}>Thanks for <span style={{ color: "var(--c-red)" }}>repping LOGIC.</span></h1>
        <p style={{ margin: "20px auto 0", maxWidth: "52ch", fontSize: 17, lineHeight: 1.6, color: "var(--c-ink-soft)" }}>
          We've got your order, {done.name.split(" ")[0]}. An invoice for <strong style={{ color: "var(--c-ink)" }}>{merchMoney(done.total)}</strong> will be emailed to {done.email}. Once it's paid, we'll reach out to organize {done.fulfillment === "delivery" ? "your free delivery" : "your pickup"}.
        </p>
        <div style={{ marginTop: 30, display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <Btn to="merch">Back to merch</Btn>
          <Btn to="home" kind="ghost">Back home</Btn>
        </div>
      </div>
    </section>);

  const opt = (v, t, sub) => {
    const on = d.fulfillment === v;
    return <button type="button" key={v} onClick={() => setD({ ...d, fulfillment: v })} aria-pressed={on} style={{
      display: "flex", alignItems: "center", gap: 12, textAlign: "left", padding: "14px 16px", borderRadius: 10, cursor: "pointer", fontFamily: "inherit",
      border: `1.5px solid ${on ? "var(--c-red)" : "var(--c-line)"}`, background: on ? "color-mix(in oklab, var(--c-red) 10%, var(--c-bg))" : "var(--c-bg)", color: "var(--c-ink)"
    }}>
      <span style={{ flex: "0 0 auto", width: 18, height: 18, borderRadius: 999, border: `2px solid ${on ? "var(--c-red)" : "var(--c-line)"}`, display: "grid", placeItems: "center" }}>{on && <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--c-red)" }}></span>}</span>
      <span style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        <span className="display" style={{ fontSize: 19, lineHeight: 1 }}>{t}</span>
        <span style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>{sub}</span>
      </span>
    </button>;
  };

  return (
    <section data-screen-label="Checkout" style={{ padding: "48px 0 96px" }}>
      <div className="container">
        <a href="#merch" className="mono" style={{ display: "inline-flex", gap: 8, color: "var(--c-ink-soft)", marginBottom: 20 }}>← Merch</a>
        <SectionHead eyebrow="Merch order · checkout"
          title={<span>Check <span style={{ color: "var(--c-red)" }}>out.</span></span>}
          kicker="No payment today. Place your order and we'll email you an invoice — once it's paid, we'll organize delivery or pickup with you." />
        <div className="co-wrap" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: "clamp(20px, 3vw, 40px)", alignItems: "start" }}>
          <form onSubmit={async (e) => {
            e.preventDefault(); if (!ready || sending) return;
            setSending(true); setErr(null);
            try { await submitMerchOrder(d, cart.lines, cart.total, "Desktop"); setDone({ name: d.name, email: d.email, total: cart.total, fulfillment: d.fulfillment }); cart.clear(); }
            catch (x) { setErr(x.message || "Network error."); } finally { setSending(false); }
          }} style={{ background: "var(--c-paper)", border: "1px solid var(--c-line)", borderRadius: "var(--radius-card)", padding: "clamp(24px, 3.4vw, 40px)" }}>
            <div className="co-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <VolField label="Full name" full><input required value={d.name} onChange={up("name")} autoComplete="name" style={volFieldStyle} /></VolField>
              <VolField label="Email"><input required type="email" value={d.email} onChange={up("email")} autoComplete="email" style={volFieldStyle} /></VolField>
              <VolField label="Phone (optional)"><input type="tel" value={d.phone} onChange={up("phone")} autoComplete="tel" style={volFieldStyle} /></VolField>
              <VolField as="div" label="Delivery or pickup" full>
                <div className="co-opts" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                  {opt("delivery", "Free delivery", "Within London")}
                  {opt("pickup", "Pick up", "We'll arrange a time and place")}
                </div>
              </VolField>
              {d.fulfillment === "delivery" && <React.Fragment>
                <VolField label="Street address" full><input required value={d.street} onChange={up("street")} autoComplete="street-address" style={volFieldStyle} /></VolField>
                <VolField label="City"><input required value={d.city} onChange={up("city")} style={volFieldStyle} /></VolField>
                <VolField label="Postal code (optional)"><input value={d.postal} onChange={up("postal")} autoComplete="postal-code" style={volFieldStyle} /></VolField>
              </React.Fragment>}
              <VolField label="Notes (optional)" full><textarea rows={3} value={d.notes} onChange={up("notes")} style={{ ...volFieldStyle, resize: "vertical", lineHeight: 1.5 }} /></VolField>
            </div>
            <div style={{ marginTop: 22, display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
              <button type="submit" disabled={!ready || sending} style={{
                padding: "14px 22px", borderRadius: 999, border: 0, background: "var(--c-red)", color: "#fff",
                fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 700,
                cursor: ready && !sending ? "pointer" : "not-allowed", opacity: ready && !sending ? 1 : 0.45
              }}>{sending ? "Placing order…" : "Place order · invoice me"}</button>
              <span style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>You won't be charged now.</span>
            </div>
            {err && <p style={{ margin: "12px 0 0", color: "var(--c-red)", fontSize: 14 }}>Couldn't send: {err}</p>}
          </form>

          <aside style={{ background: "var(--c-paper)", border: "1px solid var(--c-line)", borderRadius: "var(--radius-card)", overflow: "hidden" }}>
            <div style={{ padding: "20px 22px", borderBottom: "1px solid var(--c-line)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <Eyebrow color="var(--c-red)">Your order</Eyebrow>
              <span className="mono" style={{ color: "var(--c-ink-soft)", fontSize: 11 }}>{cart.count} item{cart.count === 1 ? "" : "s"}</span>
            </div>
            {cart.lines.length === 0 ? (
              <div style={{ padding: "28px 22px" }}>
                <p style={{ margin: 0, color: "var(--c-ink-soft)", fontSize: 15 }}>Your cart is empty.</p>
                <div style={{ marginTop: 16 }}><Btn to="merch">Shop merch</Btn></div>
              </div>
            ) : cart.lines.map((l) => (
              <div key={l.id} style={{ display: "grid", gridTemplateColumns: "64px minmax(0,1fr) auto", gap: 14, alignItems: "center", padding: "16px 22px", borderBottom: "1px solid var(--c-line)" }}>
                <img src={l.product.img} alt={l.product.name} style={{ width: 64, height: 64, objectFit: "cover", borderRadius: 8, objectPosition: l.product.pos || "center" }} />
                <div style={{ minWidth: 0 }}>
                  <div className="display" style={{ fontSize: 18, lineHeight: 1.05 }}>{l.product.name}</div>
                  {merchLineLabel(l) && <div className="mono" style={{ marginTop: 4, color: "var(--c-ink-soft)", fontSize: 10.5 }}>{merchLineLabel(l)}</div>}
                  <div style={{ marginTop: 8 }}><MerchQty value={l.qty} onChange={(q) => cart.setQty(l.id, q)} /></div>
                </div>
                <span className="display" style={{ fontSize: 20, color: "var(--c-red)" }}>{merchMoney(l.qty * l.product.price)}</span>
              </div>
            ))}
            <div style={{ padding: "18px 22px", display: "flex", flexDirection: "column", gap: 8 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "var(--c-ink-soft)" }}><span>{d.fulfillment === "delivery" ? "Delivery (within London)" : "Pick up"}</span><span>Free</span></div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", paddingTop: 10, borderTop: "1px solid var(--c-line)" }}>
                <span className="mono" style={{ fontSize: 11 }}>Total · invoiced</span>
                <span className="display" style={{ fontSize: 32, lineHeight: 1, color: "var(--c-red)" }}>{merchMoney(cart.total)}</span>
              </div>
            </div>
            <div style={{ padding: "16px 22px", background: "var(--c-bg)", borderTop: "1px solid var(--c-line)", fontSize: 13.5, lineHeight: 1.55, color: "var(--c-ink-soft)" }}>
              <strong style={{ color: "var(--c-ink)" }}>How it works:</strong> place your order → we email an invoice → once paid, we organize delivery or pickup. <strong style={{ color: "var(--c-ink)" }}>Free delivery within London.</strong> All profits fund camp scholarships.
            </div>
          </aside>
        </div>
      </div>
      <style>{`@media (max-width: 900px){.co-wrap{grid-template-columns:1fr !important}} @media (max-width: 600px){.co-grid,.co-opts{grid-template-columns:1fr !important}}`}</style>
    </section>);
}
Object.assign(window, { MerchCheckoutDesktopPage });
