/* Mobile merch checkout — #checkout. No payment: invoice emailed after order. */
function MerchCheckoutPage({ onGo }) {
  const cart = useMerchCart(MERCH_ITEMS);
  const [d, setD] = React.useState({ name: "", email: "", phone: "", fulfillment: "delivery", street: "", city: "London", postal: "", notes: "" });
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [done, setDone] = React.useState(null);
  const up = (k) => (v) => setD((s) => ({ ...s, [k]: v }));
  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({ top: 0, behavior: "smooth" }); }, [done]);

  async function submit() {
    if (!ready || sending) return;
    setSending(true); setError(null);
    try {
      await submitMerchOrder(d, cart.lines, cart.total, "Mobile");
      setDone({ name: d.name, email: d.email, total: cart.total, fulfillment: d.fulfillment });
      cart.clear();
    } catch (e) { setError(e.message || "Network error."); } finally { setSending(false); }
  }

  if (done) return (
    <main className="page">
      <section style={{ padding: "60px var(--gutter) 30px", textAlign: "center" }}>
        <span className="eyebrow" style={{ justifyContent: "center" }}>Order received</span>
        <h1 className="display" style={{ margin: "16px 0 0", fontSize: 58, lineHeight: 0.92, color: "#fff" }}>
          Thanks for <span style={{ color: "var(--c-red)" }}>repping LOGIC.</span>
        </h1>
        <p style={{ marginTop: 16, color: "var(--c-ink-soft)", fontSize: 15, lineHeight: 1.55 }}>
          We've got your order, {done.name.split(" ")[0]}. An invoice for <strong style={{ color: "#fff" }}>{merchMoney(done.total)}</strong> will be emailed to{" "}
          <span style={{ color: "#fff" }}>{done.email}</span>. Once it's paid, we'll reach out to organize {done.fulfillment === "delivery" ? "your free delivery" : "your pickup"}.
        </p>
      </section>
      <section style={{ padding: "0 var(--gutter) 24px", display: "flex", flexDirection: "column", gap: 10 }}>
        <button className="btn tappable" onClick={() => onGo("merch")}>Back to merch</button>
        <button className="btn btn-ghost tappable" onClick={() => onGo("home")}>Back home</button>
      </section>
    </main>
  );

  const qtyBtn = { width: 32, height: 32, borderRadius: 999, border: "1px solid var(--c-line)", background: "transparent", color: "#fff", fontSize: 16, display: "grid", placeItems: "center" };

  return (
    <main className="page" style={{ paddingBottom: "calc(110px + env(safe-area-inset-bottom, 0px))" }}>
      <section style={{ padding: "10px var(--gutter) 18px" }}>
        <a onClick={() => onGo("merch")} className="mono tappable" style={{ color: "var(--c-ink-soft)", fontSize: 10.5, cursor: "pointer", display: "inline-block", padding: "4px 0" }}>← Merch</a>
        <span className="eyebrow" style={{ display: "flex", marginTop: 12 }}>Merch order · checkout</span>
        <h1 className="display" style={{ margin: "10px 0 0", fontSize: 48, lineHeight: 0.95 }}>Check <span style={{ color: "var(--c-red)" }}>out.</span></h1>
        <p style={{ marginTop: 12, color: "var(--c-ink-soft)", fontSize: 14.5, lineHeight: 1.55 }}>
          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.
        </p>
      </section>

      <section style={{ padding: "0 var(--gutter) 16px" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--c-line)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <span className="mono" style={{ color: "var(--c-red)" }}>Your order</span>
            <span className="mono" style={{ color: "var(--c-ink-dim)", fontSize: 10 }}>{cart.count} item{cart.count === 1 ? "" : "s"}</span>
          </div>
          {cart.lines.length === 0 ? (
            <div style={{ padding: "20px 16px" }}>
              <p style={{ margin: "0 0 14px", color: "var(--c-ink-soft)", fontSize: 14 }}>Your cart is empty.</p>
              <button className="btn tappable" onClick={() => onGo("merch")}>Shop merch →</button>
            </div>
          ) : cart.lines.map((l) => (
            <div key={l.id} style={{ display: "grid", gridTemplateColumns: "56px minmax(0,1fr) auto", gap: 12, alignItems: "center", padding: "14px 16px", borderBottom: "1px solid var(--c-line)" }}>
              <img src={l.product.img} alt={l.product.name} style={{ width: 56, height: 56, objectFit: "cover", borderRadius: 8, objectPosition: l.product.pos || "center" }} />
              <div style={{ minWidth: 0 }}>
                <div className="display" style={{ fontSize: 16, lineHeight: 1.05, color: "#fff" }}>{l.product.name}</div>
                {merchLineLabel(l) && <div className="mono" style={{ marginTop: 3, color: "var(--c-ink-dim)", fontSize: 9.5 }}>{merchLineLabel(l)}</div>}
                <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 10 }}>
                  <button aria-label="Decrease" className="tappable" style={qtyBtn} onClick={() => cart.setQty(l.id, l.qty - 1)}>−</button>
                  <span className="mono" style={{ minWidth: 14, textAlign: "center" }}>{l.qty}</span>
                  <button aria-label="Increase" className="tappable" style={qtyBtn} onClick={() => cart.setQty(l.id, l.qty + 1)}>+</button>
                </div>
              </div>
              <span className="display" style={{ fontSize: 18, color: "var(--c-red)" }}>{merchMoney(l.qty * l.product.price)}</span>
            </div>
          ))}
          <div style={{ padding: "14px 16px", display: "flex", flexDirection: "column", gap: 8 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, 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: 10.5 }}>Total · invoiced</span>
              <span className="display" style={{ fontSize: 28, lineHeight: 1, color: "var(--c-red)" }}>{merchMoney(cart.total)}</span>
            </div>
          </div>
        </div>
      </section>

      <section style={{ padding: "0 var(--gutter) 16px" }}>
        <div className="card" style={{ padding: "20px 18px", display: "flex", flexDirection: "column", gap: 22 }}>
          <div>
            <span className="mono" style={{ color: "var(--c-red)" }}>01 · Your details</span>
            <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 12 }}>
              <ClinicField label="Full name" value={d.name} onChange={up("name")} />
              <ClinicField label="Email" type="email" value={d.email} onChange={up("email")} />
              <ClinicField label="Phone" type="tel" value={d.phone} onChange={up("phone")} optional />
            </div>
          </div>
          <div>
            <span className="mono" style={{ color: "var(--c-red)" }}>02 · Delivery or pickup</span>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 12 }}>
              {[["delivery", "Free delivery", "Within London"], ["pickup", "Pick up", "We'll arrange a time and place"]].map(([v, t, sub]) => {
                const on = d.fulfillment === v;
                return (
                  <button key={v} onClick={() => up("fulfillment")(v)} className="tappable" style={{
                    display: "flex", alignItems: "center", gap: 12, textAlign: "left", padding: "13px 14px", borderRadius: 10,
                    border: `1.5px solid ${on ? "var(--c-red)" : "var(--c-line)"}`, background: on ? "rgba(230,24,44,0.10)" : "#0a0a0a", color: "#fff",
                  }}>
                    <span style={{ flex: "0 0 auto", width: 20, height: 20, borderRadius: 999, border: `2px solid ${on ? "var(--c-red)" : "rgba(255,255,255,0.35)"}`, display: "grid", placeItems: "center" }}>
                      {on && <span style={{ width: 9, height: 9, borderRadius: 999, background: "var(--c-red)" }}></span>}
                    </span>
                    <span>
                      <span className="display" style={{ display: "block", fontSize: 17, lineHeight: 1.05 }}>{t}</span>
                      <span className="mono" style={{ display: "block", marginTop: 3, fontSize: 9.5, color: "var(--c-ink-soft)" }}>{sub}</span>
                    </span>
                  </button>
                );
              })}
            </div>
            {d.fulfillment === "delivery" && (
              <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 14 }}>
                <ClinicField label="Street address" value={d.street} onChange={up("street")} />
                <ClinicField label="City" value={d.city} onChange={up("city")} />
                <ClinicField label="Postal code" value={d.postal} onChange={up("postal")} optional />
              </div>
            )}
          </div>
          <ClinicField label="Notes" value={d.notes} onChange={up("notes")} optional multiline />
          <div style={{ padding: "12px 14px", borderRadius: 10, background: "rgba(230,24,44,0.08)", border: "1px solid rgba(230,24,44,0.35)", fontSize: 13, lineHeight: 1.5, color: "#fff" }}>
            <strong>No payment now.</strong> We'll email an invoice — once paid, we organize delivery or pickup. <strong>Free delivery within London.</strong>
          </div>
          {error && (
            <div style={{ padding: "12px 14px", borderRadius: 10, border: "1px solid var(--c-red)", fontSize: 13, lineHeight: 1.45 }}>
              <strong style={{ color: "var(--c-red)" }}>Couldn't send.</strong> {error}
            </div>
          )}
        </div>
      </section>

      <div style={{ position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 30, padding: "10px 12px calc(10px + env(safe-area-inset-bottom, 0px))", background: "linear-gradient(0deg, #0a0a0a 70%, rgba(10,10,10,0.6) 100%)" }}>
        <button onClick={submit} disabled={!ready || sending} className="tappable" style={{
          width: "100%", height: 52, borderRadius: 12, border: "none",
          background: ready ? "var(--c-red)" : "rgba(230,24,44,0.35)", color: "#fff",
          fontFamily: "var(--font-display)", fontSize: 15.5, letterSpacing: "0.06em", textTransform: "uppercase",
          boxShadow: ready ? "0 12px 32px rgba(230,24,44,0.45)" : "none",
        }}>{sending ? "Placing order…" : `Place order · ${merchMoney(cart.total)} · invoice me`}</button>
      </div>
    </main>
  );
}

Object.assign(window, { MerchCheckoutPage });
