/* Multi-step register flow */

const STEPS = ["Athlete", "Division", "Schedule", "Guardian", "Review"];

const DIVISION_PRICES = {
  rookie:      { 1: 425, 2: 750,   3: 995   },
  foundation:  { 1: 495, 2: 875,   3: 1175  },
  development: { 1: 535, 2: 950,   3: 1275  },
  performance: { 1: 565, 2: 995,   3: 1345  },
  elite:       { 1: 585, 2: 1035,  3: 1395  },
};

const WEEK_RANGES = ["Aug 3 – 7", "Aug 10 – 14", "Aug 17 – 21"];

function computeTotal(divisionId, selectedWeeks) {
  const n = selectedWeeks ? selectedWeeks.length : 0;
  if (!divisionId || !n) return 0;
  const prices = DIVISION_PRICES[divisionId];
  if (!prices) return 0;
  return prices[n] || 0;
}

const WEB3FORMS_KEY = "b8d90ff4-9ffd-422f-a59d-c0c2d5e120c6";
const REGISTRATION_EMAIL = "coach_ad@londonlogicbasketball.com";

async function submitRegistrationEmail(data) {
  const division = DIV_FULL.find(d => d.id === data.division);
  const total = computeTotal(data.division, data.selectedWeeks);
  const weeksLabel = data.selectedWeeks.length === 0 ? "—" :
    data.selectedWeeks.length === 3 ? "All 3 weeks (Aug 3 – 21)" :
    data.selectedWeeks.map(w => `Week ${w} (${WEEK_RANGES[w - 1]})`).join(", ");

  const isScholarship = data.mode === "scholarship";

  const subject = isScholarship
    ? `[Scholarship] ${data.firstName} ${data.lastName} — ${division?.name || "?"} LOGIC`
    : `[Registration] ${data.firstName} ${data.lastName} — ${division?.name || "?"} LOGIC · ${data.selectedWeeks.length} wk(s)`;

  const payload = {
    access_key: WEB3FORMS_KEY,
    subject,
    from_name: "London LOGIC Basketball — Registration Form",
    "Application Type": isScholarship ? "SCHOLARSHIP APPLICATION (free)" : "PAID REGISTRATION",

    "Athlete Name":  `${data.firstName} ${data.lastName}`,
    "Grade":         data.grade,
    "Gender":        data.gender,

    "Division":      division ? `${division.name} LOGIC` : data.division,
    "Weeks":         weeksLabel,
    "Total Due":     isScholarship ? "Free (scholarship)" : (total ? `$${total.toLocaleString()}` : "—"),
    "Sponsor-a-Week": data.donateWeek ? `Donating Week ${data.donateWeek} to scholarship fund` : "—",
    "Aug 22 Community Game (Elite)": data.division === "elite" ? (data.wantsCommunityGame ? "Yes" : "No") : "N/A",

    "Guardian Name":  data.guardianName,
    "Guardian Email": data.email,
    "Guardian Phone": data.phone,

    "Billing Address": data.mode === "scholarship"
      ? "N/A (scholarship)"
      : [data.billingStreet, data.billingCity, data.billingProvince, data.billingPostal, data.billingCountry].filter(Boolean).join(", "),

    "Waiver Accepted":     data.waiver ? "Yes" : "No",
    "Media Consent":       data.mediaConsent ? "Yes" : "No",
    "Player Portfolio Consent": data.portfolioConsent ? "Yes" : "No",
    "Marketing Email Consent": data.emailConsent ? "Yes" : "No",

    "Scholarship Statement": isScholarship ? data.scholarshipReason : "—",

    "Document Package": "Consent Waiver + Emergency Info, Athlete Registration, Medical Information — delivered to family on confirmation",

    replyto: data.email,
  };

  const res = await fetch("https://api.web3forms.com/submit", {
    method: "POST",
    headers: { "Content-Type": "application/json", "Accept": "application/json" },
    body: JSON.stringify(payload),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || !json.success) {
    throw new Error(json.message || `Submission failed (${res.status})`);
  }
  return json;
}

function RegisterPage() {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState(() => {
    let initialMode = "paid";
    let initialWeeks = [1, 2, 3];
    try {
      const stored = localStorage.getItem("logic_register_mode");
      if (stored === "scholarship") {
        initialMode = "scholarship";
        localStorage.removeItem("logic_register_mode");
      }
      const w = localStorage.getItem("logic_register_weeks");
      if (w) {
        const parsed = JSON.parse(w);
        if (Array.isArray(parsed) && parsed.every(x => [1, 2, 3].includes(x)) && parsed.length) {
          initialWeeks = parsed;
        }
      }
    } catch (e) {}
    return {
    firstName: "", lastName: "", grade: "", gender: "",
    division: "", selectedWeeks: initialWeeks, wantsCommunityGame: false,
    donateWeek: null,
    mode: initialMode, scholarshipReason: "",
    guardianName: "", email: "", phone: "",
    billingAddress: false, billingStreet: "", billingCity: "",
    billingProvince: "", billingPostal: "", billingCountry: "Canada",
    waiver: false, mediaConsent: false, portfolioConsent: false,
    emailConsent: false,
    };
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const update = (patch) => setData(d => {
    const next = { ...d, ...patch };
    // Persist selectedWeeks any time they change
    if (patch.selectedWeeks) {
      try { localStorage.setItem("logic_register_weeks", JSON.stringify(next.selectedWeeks)); } catch (e) {}
    }
    // If donateWeek is no longer in selectedWeeks, clear it
    if (next.donateWeek && !next.selectedWeeks.includes(next.donateWeek)) {
      next.donateWeek = null;
    }
    return next;
  });

  const canAdvance = () => {
    if (step === 0) return data.firstName && data.lastName && data.grade && data.gender;
    if (step === 1) return data.division;
    if (step === 2) return data.selectedWeeks.length >= 1;
    if (step === 3) {
      const billingOk = data.mode === "scholarship" ||
        (data.billingStreet && data.billingCity && data.billingProvince && data.billingPostal && data.billingCountry);
      return data.guardianName && data.email && data.phone && data.waiver && billingOk && (data.mode !== "scholarship" || data.scholarshipReason.trim().length > 30);
    }
    return true;
  };

  if (submitted) return <ThankYou data={data}/>;

  return (
    <section style={{ padding: "60px 0 120px" }}>
      <div className="container" style={{ maxWidth: 880 }}>
        <SectionHead
          eyebrow="Registration · 2026 cohort"
          title={<span>Reserve your <span style={{ color: "var(--c-red)" }}>spot.</span></span>}
          kicker="120 spots total — 24 per division. We'll save your place once you complete the steps below."
        />

        {/* Mode toggle — explicit two-track switch (dark theme for visibility) */}
        <div className="mode-toggle" style={{
          marginTop: 24,
          background: "#15110d",
          border: "1.5px solid #15110d",
          borderRadius: "var(--radius-card)",
          padding: 6,
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 6,
          position: "relative",
        }}>
          {[
            { v: "paid", lbl: "Paid Registration", sub: "1, 2, or 3 weeks", icon: "💳" },
            { v: "scholarship", lbl: "Scholarship Application", sub: "1 of 10 fully-funded spots · apply free", icon: "★" },
          ].map(o => {
            const on = data.mode === o.v;
            const isScholar = o.v === "scholarship";
            return (
              <button key={o.v} onClick={() => update({ mode: o.v })} style={{
                display: "flex", alignItems: "center", gap: 14, textAlign: "left",
                background: on
                  ? (isScholar ? "var(--c-red)" : "#0a0a0a")
                  : "transparent",
                color: "#ffffff",
                border: on && !isScholar ? "1px solid rgba(255,255,255,0.12)" : "1px solid transparent",
                borderRadius: 10,
                padding: "16px 18px",
                cursor: "pointer",
                transition: "background 200ms ease, color 200ms ease, border-color 200ms ease",
                position: "relative",
              }}>
                <div style={{
                  flex: "0 0 auto",
                  width: 36, height: 36, borderRadius: 8,
                  background: on
                    ? "rgba(255,255,255,0.18)"
                    : (isScholar ? "var(--c-red)" : "rgba(255,255,255,0.10)"),
                  color: "#fff",
                  display: "grid", placeItems: "center",
                  fontSize: 18, fontWeight: 700,
                }}>{o.icon}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="display" style={{
                    fontSize: 17, lineHeight: 1.05, color: "#ffffff",
                  }}>{o.lbl}</div>
                  <div className="mono" style={{
                    marginTop: 4, fontSize: 10,
                    color: on ? "rgba(255,255,255,0.88)" : "rgba(255,255,255,0.65)",
                  }}>{o.sub}</div>
                </div>
                {on && (
                  <div style={{
                    flex: "0 0 auto",
                    width: 22, height: 22, borderRadius: 999,
                    background: "rgba(255,255,255,0.22)",
                    display: "grid", placeItems: "center",
                    color: "#fff", fontSize: 13, fontWeight: 700,
                  }}>✓</div>
                )}
              </button>
            );
          })}
        </div>

        {/* Scholarship application banner — only visible in scholarship mode */}
        {data.mode === "scholarship" && (
          <div style={{
            marginTop: 14,
            background: "var(--c-red)",
            color: "#ffffff",
            borderRadius: "var(--radius-card)",
            padding: "22px 26px",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            gap: 18, flexWrap: "wrap",
            border: "1.5px solid var(--c-red)",
            boxShadow: "0 12px 36px rgba(209,26,42,0.28)",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
              <div style={{
                flex: "0 0 auto",
                width: 56, height: 56, borderRadius: 12,
                background: "rgba(0,0,0,0.28)",
                display: "grid", placeItems: "center",
                color: "#fff",
              }}>
                <span className="display" style={{ fontSize: 26, lineHeight: 1, color: "#fff" }}>10</span>
              </div>
              <div>
                <div className="mono" style={{ color: "rgba(255,255,255,0.92)", fontSize: 10 }}>
                  You're applying for a Scholarship · Application is FREE
                </div>
                <div className="display" style={{ marginTop: 6, fontSize: 22, lineHeight: 1.1, color: "#ffffff" }}>
                  One boy &amp; one girl from every division — full ride.
                </div>
                <div style={{ marginTop: 6, fontSize: 13, color: "rgba(255,255,255,0.88)", lineHeight: 1.45, maxWidth: "60ch" }}>
                  Awarded on need + character. You'll write a short answer in Step 4. Recipients announced mid-June.
                </div>
              </div>
            </div>
          </div>
        )}
        <style>{`
          @media (max-width: 720px) {
            .mode-toggle { grid-template-columns: 1fr !important; }
          }
        `}</style>

        <Stepper step={step} onJump={(i) => i < step && setStep(i)}/>

        <div className="reveal" key={step} style={{
          background: "var(--c-paper)",
          border: "1px solid var(--c-line)",
          borderRadius: "var(--radius-card)",
          padding: "40px 44px",
          marginTop: 28,
        }}>
          {step === 0 && <StepAthlete data={data} update={update}/>}
          {step === 1 && <StepDivision data={data} update={update}/>}
          {step === 2 && <StepSchedule data={data} update={update}/>}
          {step === 3 && <StepGuardian data={data} update={update}/>}
          {step === 4 && <StepReview data={data}/>}
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24, gap: 12, flexWrap: "wrap" }}>
          <Btn kind="ghost" onClick={() => setStep(s => Math.max(0, s - 1))} disabled={step === 0}>← Back</Btn>
          {step < STEPS.length - 1 ? (
            <Btn kind="primary" onClick={() => canAdvance() && setStep(s => s + 1)} disabled={!canAdvance()}>
              Continue
            </Btn>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8 }}>
              {submitError && (
                <div style={{
                  padding: "10px 14px", borderRadius: 10,
                  background: "color-mix(in oklab, var(--c-red) 14%, var(--c-paper))",
                  border: "1px solid color-mix(in oklab, var(--c-red) 45%, var(--c-line))",
                  color: "var(--c-ink)", fontSize: 13, maxWidth: 420,
                }}>
                  <strong style={{ color: "var(--c-red)" }}>Couldn't send.</strong> {submitError} Please try again, or email{" "}
                  <a href="mailto:coach_ad@londonlogicbasketball.com" style={{ color: "var(--c-ink)" }}>coach_ad@londonlogicbasketball.com</a> directly.
                </div>
              )}
              <Btn kind="primary" disabled={sending} onClick={async () => {
                setSending(true); setSubmitError(null);
                try {
                  await submitRegistrationEmail(data);
                  setSubmitted(true);
                } catch (err) {
                  setSubmitError(err.message || "Network error.");
                } finally {
                  setSending(false);
                }
              }}>{sending ? "Sending…" : "Submit registration"}</Btn>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function Stepper({ step, onJump }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: `repeat(${STEPS.length}, 1fr)`,
      gap: 8,
      marginTop: 16,
    }}>
      {STEPS.map((s, i) => {
        const done = i < step, on = i === step;
        return (
          <button key={s} onClick={() => onJump(i)} style={{
            background: "transparent", border: "none", padding: 0, textAlign: "left", cursor: i < step ? "pointer" : "default",
          }}>
            <div style={{
              height: 6, borderRadius: 999,
              background: done || on ? "var(--c-red)" : "var(--c-line)",
              transition: "background 200ms ease",
            }}/>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10 }}>
              <span className="mono" style={{ color: on ? "var(--c-red)" : "var(--c-ink-soft)" }}>0{i + 1}</span>
              <span style={{ fontSize: 13, fontWeight: 600, color: done || on ? "var(--c-ink)" : "var(--c-ink-soft)" }}>{s}</span>
            </div>
          </button>
        );
      })}
    </div>
  );
}

function StepAthlete({ data, update }) {
  return (
    <div>
      <StepHead n="01" title="Tell us about the athlete"/>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="form-grid">
        <Field label="First name" value={data.firstName} onChange={v => update({ firstName: v })}/>
        <Field label="Last name" value={data.lastName} onChange={v => update({ lastName: v })}/>
        <Select label="Grade in Sept 2026" value={data.grade}
          onChange={v => update({ grade: v })}
          options={["", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]}/>
        <Radio label="Gender" value={data.gender} onChange={v => update({ gender: v })}
          options={[["boys", "Boys"], ["girls", "Girls"]]}/>
      </div>
    </div>
  );
}

function StepDivision({ data, update }) {
  const recommended = recommendDivision(data.grade);
  return (
    <div>
      <StepHead n="02" title="Choose a division"/>
      {recommended && (
        <div style={{
          padding: "12px 16px", marginBottom: 18,
          background: "color-mix(in oklab, var(--c-red) 10%, var(--c-paper))",
          border: "1px solid color-mix(in oklab, var(--c-red) 30%, var(--c-line))",
          borderRadius: 10, fontSize: 14,
        }}>
          Based on Grade {data.grade}, we recommend <b>{recommended.name} LOGIC</b>.
        </div>
      )}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 }} className="div-pick">
        {DIV_FULL.map(d => {
          const on = data.division === d.id;
          return (
            <button key={d.id} onClick={() => update({ division: d.id })} style={{
              background: on ? d.color : "var(--c-paper)", color: on ? "#fff" : "var(--c-ink)",
              border: `1.5px solid ${on ? d.color : "var(--c-line)"}`,
              borderRadius: "var(--radius-card)", padding: 18, textAlign: "left", cursor: "pointer",
            }}>
              <div className="mono" style={{ opacity: 0.85, fontSize: 10 }}>{d.grades}</div>
              <div className="display" style={{ fontSize: 22, marginTop: 6, color: "inherit" }}>{d.name}</div>
              <div style={{ fontSize: 12, marginTop: 8, opacity: 0.85, lineHeight: 1.4 }}>{d.tagline}</div>
            </button>
          );
        })}
      </div>
      <style>{`@media (max-width: 900px) { .div-pick { grid-template-columns: repeat(2, 1fr) !important; } }`}</style>
    </div>
  );
}

function StepSchedule({ data, update }) {
  const eliteOnly = data.division === "elite";
  const division = DIV_FULL.find(d => d.id === data.division);
  const total = computeTotal(data.division, data.selectedWeeks);
  const allThree = data.selectedWeeks.length === 3;
  const showSponsor = data.mode !== "scholarship" && data.selectedWeeks.length >= 2;

  const toggleWeek = (n) => {
    const has = data.selectedWeeks.includes(n);
    const next = has
      ? data.selectedWeeks.filter(w => w !== n)
      : [...data.selectedWeeks, n].sort((a, b) => a - b);
    update({ selectedWeeks: next });
  };

  return (
    <div>
      <StepHead n="03" title="Choose your weeks"/>
      <p style={{ marginTop: -12, marginBottom: 18, color: "var(--c-ink-soft)", fontSize: 14, lineHeight: 1.55 }}>
        Families may register for 1, 2, or 3 weeks. The full 3-week experience is recommended for the complete LOGIC development pathway and best weekly value.
      </p>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }} className="wk-pick">
        {[1, 2, 3].map(n => {
          const on = data.selectedWeeks.includes(n);
          return (
            <button
              key={n}
              onClick={() => toggleWeek(n)}
              style={{
                background: on ? "var(--c-ink)" : "var(--c-paper)",
                color: on ? "var(--c-paper)" : "var(--c-ink)",
                border: `1.5px solid ${on ? "var(--c-ink)" : "var(--c-line)"}`,
                borderRadius: "var(--radius-card)", padding: 22,
                textAlign: "left", cursor: "pointer",
                position: "relative",
                transition: "background 180ms ease, color 180ms ease, border-color 180ms ease",
              }}
            >
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span className="mono" style={{ color: "var(--c-red)" }}>Week {n}</span>
                <span style={{
                  width: 22, height: 22, borderRadius: 6,
                  background: on ? "var(--c-red)" : "transparent",
                  border: `1.5px solid ${on ? "var(--c-red)" : "var(--c-line)"}`,
                  color: "#fff", display: "grid", placeItems: "center", fontSize: 12,
                  transition: "background 180ms ease, border-color 180ms ease",
                }}>{on ? "✓" : ""}</span>
              </div>
              <div className="display" style={{ fontSize: 26, marginTop: 8, color: "inherit", lineHeight: 1 }}>{WEEK_RANGES[n - 1]}</div>
              <div className="mono" style={{ marginTop: 6, opacity: on ? 0.7 : 0.6 }}>Mon – Fri</div>
            </button>
          );
        })}
      </div>

      {data.selectedWeeks.length === 0 && (
        <div style={{
          marginTop: 14, padding: "12px 16px", borderRadius: 10,
          background: "color-mix(in oklab, var(--c-red) 12%, var(--c-paper))",
          border: "1px solid color-mix(in oklab, var(--c-red) 35%, var(--c-line))",
          fontSize: 13.5, color: "var(--c-ink)",
        }}>
          Select at least one week to continue.
        </div>
      )}

      {/* Live price summary — paid only */}
      {data.mode !== "scholarship" && (
      <div style={{
        marginTop: 18,
        background: "var(--c-ink)", color: "var(--c-paper)",
        borderRadius: "var(--radius-card)", padding: "22px 26px",
        position: "relative", overflow: "hidden",
      }}>
        {allThree && (
          <span style={{
            position: "absolute", top: 14, right: 14,
            background: "var(--c-red)", color: "#fff",
            padding: "5px 10px", borderRadius: 999,
            fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em",
            textTransform: "uppercase", fontWeight: 600,
          }}>★ Best Value · Full LOGIC</span>
        )}
        <div className="mono" style={{ color: "var(--c-red)" }}>Your selection</div>
        <div style={{
          marginTop: 12, display: "grid",
          gridTemplateColumns: "1.4fr 1fr 1fr",
          gap: 24, alignItems: "end",
        }} className="summary-row">
          <div style={{ minWidth: 0 }}>
            <div className="mono" style={{ color: "rgba(255,255,255,0.55)", fontSize: 10 }}>Division</div>
            <div className="display" style={{ fontSize: 26, marginTop: 6, lineHeight: 1, color: "#fff" }}>
              {division ? `${division.name} LOGIC` : "—"}
            </div>
          </div>
          <div style={{ minWidth: 0 }}>
            <div className="mono" style={{ color: "rgba(255,255,255,0.55)", fontSize: 10 }}>Weeks selected</div>
            <div className="display" style={{ fontSize: 26, marginTop: 6, lineHeight: 1, color: "#fff" }}>
              {data.selectedWeeks.length === 0 ? "—" :
                data.selectedWeeks.length === 3 ? "All 3 weeks" :
                data.selectedWeeks.map(w => `Wk ${w}`).join(" + ")}
            </div>
          </div>
          <div style={{ textAlign: "right", minWidth: 0 }}>
            <div className="mono" style={{ color: "rgba(255,255,255,0.55)", fontSize: 10 }}>Total</div>
            <div className="display" style={{
              fontSize: 44, marginTop: 4, lineHeight: 1,
              color: total ? "var(--c-red)" : "rgba(255,255,255,0.4)",
            }}>
              {total ? `$${total.toLocaleString()}` : "—"}
            </div>
          </div>
        </div>
        {!data.division && (
          <div className="mono" style={{
            marginTop: 12, color: "rgba(255,255,255,0.5)", fontSize: 10,
          }}>
            Choose a division in Step 02 to see your total.
          </div>
        )}
      </div>
      )}

      {showSponsor && (
      <div style={{
        marginTop: 22,
        background: "var(--c-ink)", color: "var(--c-paper)",
        borderRadius: "var(--radius-card)", padding: "24px 26px",
        position: "relative", overflow: "hidden",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 18, flexWrap: "wrap" }}>
          <div style={{ maxWidth: "52ch" }}>
            <Eyebrow color="var(--c-red)">Optional · Sponsor-a-Week</Eyebrow>
            <div className="display" style={{ marginTop: 10, fontSize: 24, color: "#fff", lineHeight: 1.05 }}>
              Can't make one of your weeks? Donate it.
            </div>
            <p style={{ marginTop: 10, fontSize: 14, color: "rgba(255,255,255,0.78)", lineHeight: 1.55 }}>
              If your athlete genuinely cannot attend one of the weeks you've registered for —
              travel, injury, an unavoidable conflict — you can donate that week to a family
              in need instead of taking a refund. The spot funds a London athlete on scholarship
              rather than going unused.
              {" "}
              <a href="#scholarship" style={{ color: "#fff", textDecoration: "underline" }}>Learn how it works →</a>
            </p>
          </div>
        </div>
        <div style={{
          display: "grid",
          gridTemplateColumns: `repeat(${data.selectedWeeks.length + 1}, 1fr)`,
          gap: 8, marginTop: 18,
        }} className="don-pick">
          {[
            { v: null, label: "Attending all" },
            ...data.selectedWeeks.map(w => ({ v: w, label: `Can't attend Week ${w}` })),
          ].map(o => {
            const on = data.donateWeek === o.v;
            return (
              <button key={String(o.v)} onClick={() => update({ donateWeek: o.v })} style={{
                background: on ? "var(--c-red)" : "transparent",
                color: on ? "#fff" : "var(--c-paper)",
                border: `1.5px solid ${on ? "var(--c-red)" : "rgba(255,255,255,0.22)"}`,
                borderRadius: 10, padding: "12px 10px",
                fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.06em",
                textTransform: "uppercase", fontWeight: 600, cursor: "pointer",
              }}>{o.label}</button>
            );
          })}
        </div>
        <style>{`@media (max-width: 700px) { .don-pick { grid-template-columns: repeat(2, 1fr) !important; } }`}</style>
      </div>
      )}

      {eliteOnly && (
        <div style={{
          marginTop: 18, padding: 18,
          background: "var(--c-red)", color: "#fff",
          borderRadius: "var(--radius-card)",
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap",
        }}>
          <div>
            <div className="mono" style={{ opacity: 0.9 }}>Elite athletes</div>
            <div className="display" style={{ fontSize: 24, marginTop: 6 }}>Aug 22 · Community Game</div>
            <div style={{ marginTop: 4, fontSize: 14, opacity: 0.95 }}>Included for all Elite registrants.</div>
          </div>
          <label style={{ display: "inline-flex", alignItems: "center", gap: 10, fontWeight: 600 }}>
            <input type="checkbox" checked={data.wantsCommunityGame} onChange={e => update({ wantsCommunityGame: e.target.checked })}/>
            Confirm participation
          </label>
        </div>
      )}
      <style>{`
        @media (max-width: 700px) {
          .wk-pick { grid-template-columns: 1fr !important; }
          .summary-row { grid-template-columns: 1fr !important; gap: 14px !important; }
          .summary-row > div:last-child { text-align: left !important; }
        }
      `}</style>
    </div>
  );
}

function StepGuardian({ data, update }) {
  return (
    <div>
      <StepHead n="04" title="Parent / guardian"/>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="form-grid">
        <Field label="Full name" value={data.guardianName} onChange={v => update({ guardianName: v })}/>
        <Field label="Phone" value={data.phone} onChange={v => update({ phone: v })}/>
        <Field label="Email" value={data.email} onChange={v => update({ email: v })} full/>
      </div>

      {data.mode !== "scholarship" && (
        <div style={{ marginTop: 26 }}>
          <div style={{ marginBottom: 14 }}>
            <span className="mono" style={{ color: "var(--c-red)" }}>Billing address · required</span>
            <p style={{ margin: "4px 0 0", color: "var(--c-ink-soft)", fontSize: 13, lineHeight: 1.45 }}>
              Used on your invoice and receipt.
            </p>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="form-grid">
            <Field label="Street address" value={data.billingStreet} onChange={v => update({ billingStreet: v })} full/>
            <Field label="City" value={data.billingCity} onChange={v => update({ billingCity: v })}/>
            <Field label="Province / State" value={data.billingProvince} onChange={v => update({ billingProvince: v })}/>
            <Field label="Postal / ZIP code" value={data.billingPostal} onChange={v => update({ billingPostal: v })}/>
            <Field label="Country" value={data.billingCountry} onChange={v => update({ billingCountry: v })}/>
          </div>
        </div>
      )}

      {data.mode === "scholarship" && (
        <div style={{
          marginTop: 22, padding: "22px 22px",
          background: "color-mix(in oklab, var(--c-red) 8%, var(--c-paper))",
          border: "1.5px solid color-mix(in oklab, var(--c-red) 30%, var(--c-line))",
          borderRadius: "var(--radius-card)",
        }}>
          <div className="mono" style={{ color: "var(--c-red)" }}>Scholarship application · short answer</div>
          <div className="display" style={{ fontSize: 22, marginTop: 6, lineHeight: 1.15 }}>
            What would a LOGIC spot mean for your athlete?
          </div>
          <p style={{ fontSize: 13, color: "var(--c-ink-soft)", margin: "6px 0 12px" }}>
            A few sentences — character, basketball journey, why the scholarship matters. Reviewed confidentially.
          </p>
          <textarea value={data.scholarshipReason} onChange={e => update({ scholarshipReason: e.target.value })}
            placeholder="Tell us about your athlete..."
            style={{
              width: "100%", minHeight: 140, resize: "vertical",
              padding: "14px 14px", borderRadius: 10,
              border: "1px solid var(--c-line)", background: "var(--c-paper)",
              fontFamily: "inherit", fontSize: 14, lineHeight: 1.5, color: "var(--c-ink)",
            }}/>
          <div className="mono" style={{ marginTop: 8, color: "var(--c-ink-soft)", fontSize: 10 }}>
            {data.scholarshipReason.trim().length} chars · min 30
          </div>
        </div>
      )}
      <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 12 }}>
        <WaiverReview/>
        <Check label="I have read and accept the program waiver, code of conduct, and policies."
          value={data.waiver} onChange={v => update({ waiver: v })}/>
        <Check label="I consent to media coverage (photo / video) for the registered athlete."
          value={data.mediaConsent} onChange={v => update({ mediaConsent: v })}/>
        <Check label="I consent to LOGIC recording an ongoing player portfolio (training clips, skill assessments, growth notes) for the registered athlete — used for development feedback and shared privately with our family."
          value={data.portfolioConsent} onChange={v => update({ portfolioConsent: v })}/>
        <Check label="I agree to receive notifications, camp updates, and promotional emails from London LOGIC Basketball."
          value={data.emailConsent} onChange={v => update({ emailConsent: v })}/>
      </div>
    </div>
  );
}

function StepReview({ data }) {
  const division = DIV_FULL.find(d => d.id === data.division);
  const total = computeTotal(data.division, data.selectedWeeks);
  const weeksLabel = data.selectedWeeks.length === 0 ? "—" :
    data.selectedWeeks.length === 3 ? "All 3 weeks · Aug 3 – 21" :
    data.selectedWeeks.map(w => `Week ${w} (${WEEK_RANGES[w - 1]})`).join(" · ");
  return (
    <div>
      <StepHead n="05" title="Review & submit"/>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }} className="form-grid">
        <ReviewBlock title="Athlete">
          <Line k="Name" v={`${data.firstName} ${data.lastName}`}/>
          <Line k="Grade" v={data.grade}/>
          <Line k="Gender" v={data.gender}/>
        </ReviewBlock>
        <ReviewBlock title="Program">
          <Line k="Mode" v={data.mode === "scholarship" ? "Scholarship application" : "Paid registration"}/>
          <Line k="Division" v={division?.name + " LOGIC"}/>
          <Line k="Weeks" v={weeksLabel}/>
          <Line k="Total" v={data.mode === "scholarship" ? "Free (scholarship)" : (total ? `$${total.toLocaleString()}` : "—")}/>
          {data.donateWeek && <Line k="Sponsor-a-Week" v={`Donating Week ${data.donateWeek}`}/>}
          {data.division === "elite" && <Line k="Aug 22 game" v={data.wantsCommunityGame ? "Yes" : "No"}/>}
        </ReviewBlock>
        <ReviewBlock title="Guardian">
          <Line k="Name" v={data.guardianName}/>
          <Line k="Email" v={data.email}/>
          <Line k="Phone" v={data.phone}/>
        </ReviewBlock>
        {data.mode !== "scholarship" && (
          <ReviewBlock title="Billing address">
            <Line k="Street" v={data.billingStreet}/>
            <Line k="City" v={data.billingCity}/>
            <Line k="Province / State" v={data.billingProvince}/>
            <Line k="Postal / ZIP" v={data.billingPostal}/>
            <Line k="Country" v={data.billingCountry}/>
          </ReviewBlock>
        )}
        <ReviewBlock title="Consents">
          <Line k="Waiver" v={data.waiver ? "Accepted" : "—"}/>
          <Line k="Media" v={data.mediaConsent ? "Yes" : "No"}/>
          <Line k="Player portfolio" v={data.portfolioConsent ? "Yes" : "No"}/>
          <Line k="Email updates" v={data.emailConsent ? "Yes" : "No"}/>
        </ReviewBlock>
      </div>
      <p style={{ marginTop: 22, color: "var(--c-ink-soft)", fontSize: 13 }}>
        After submitting, our team will email you within 2 business days to confirm your application.
      </p>
    </div>
  );
}

/* The fillable forms families receive automatically on registration. */
const DOC_PACKAGE = [
  {
    n: "01",
    name: "Consent Waiver & Emergency Information",
    file: "uploads/London LOGIC - Fillable Consent Waiver and Emergency Information.pdf",
  },
  {
    n: "02",
    name: "Athlete Registration Form",
    file: "uploads/London LOGIC Basketball - Fillable Athlete Registration Form.pdf",
  },
  {
    n: "03",
    name: "Medical Information Form",
    file: "uploads/London LOGIC Basketball - Fillable Medical Information Form.pdf",
  },
];

function ThankYou({ data }) {
  const anchorRefs = React.useRef([]);
  const [autoTried, setAutoTried] = React.useState(false);
  const isScholarship = data.mode === "scholarship";

  const triggerAll = React.useCallback(() => {
    anchorRefs.current.forEach((a, i) => {
      if (!a) return;
      // Stagger so browsers don't suppress rapid-fire downloads
      setTimeout(() => a.click(), i * 600);
    });
  }, []);

  // Best-effort auto-download once the confirmation screen appears (paid only).
  React.useEffect(() => {
    if (isScholarship) return;
    const t = setTimeout(() => { triggerAll(); setAutoTried(true); }, 700);
    return () => clearTimeout(t);
  }, [triggerAll, isScholarship]);

  // Scholarship is an application only at this stage — no forms/invoice yet.
  if (isScholarship) {
    return (
      <section style={{ padding: "120px 0", textAlign: "center" }}>
        <div className="container" style={{ maxWidth: 640 }}>
          <Eyebrow>Application received</Eyebrow>
          <h1 className="display" style={{ fontSize: "clamp(54px, 9vw, 120px)", margin: "16px 0 0", lineHeight: 0.92 }}>
            You have <span style={{ color: "var(--c-red)" }}>applied.</span>
          </h1>
          <p style={{ fontSize: 18, color: "var(--c-ink-soft)", marginTop: 18, maxWidth: "52ch", marginInline: "auto" }}>
            Thanks {data.firstName}. We've logged your scholarship application and will email {data.email} within 2 business days to confirm.
          </p>
          <div style={{ display: "inline-flex", gap: 12, marginTop: 28 }}>
            <Btn to="home" kind="ghost">Back home</Btn>
            <Btn to="camp" kind="primary">Camp details</Btn>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section style={{ padding: "96px 0 120px", textAlign: "center" }}>
      <div className="container" style={{ maxWidth: 720 }}>
        <Eyebrow>Application received</Eyebrow>
        <h1 className="display" style={{ fontSize: "clamp(48px, 8vw, 104px)", margin: "16px 0 0", lineHeight: 0.92 }}>
          You have <span style={{ color: "var(--c-red)" }}>applied.</span>
        </h1>
        <p style={{ fontSize: 18, color: "var(--c-ink-soft)", marginTop: 18, maxWidth: "54ch", marginInline: "auto" }}>
          Thanks {data.firstName} — your spot is being held, but your registration is{" "}
          <strong style={{ color: "var(--c-ink)" }}>not complete yet</strong>. We've sent the details to {data.email}.
        </p>

        {/* ===== What's left to finalize ===== */}
        <div style={{
          marginTop: 26, textAlign: "left",
          background: "color-mix(in oklab, var(--c-red) 8%, var(--c-paper))",
          border: "1.5px solid color-mix(in oklab, var(--c-red) 32%, var(--c-line))",
          borderRadius: "var(--radius-card)",
          padding: "20px 24px",
        }}>
          <div className="mono" style={{ color: "var(--c-red)" }}>
            {isScholarship ? "To finalize a scholarship spot" : "Your registration is not complete until both steps are done"}
          </div>
          <ol style={{ margin: "12px 0 0", padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 12 }}>
            <li style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
              <span style={{ flex: "0 0 auto", width: 24, height: 24, borderRadius: 999, background: "var(--c-red)", color: "#fff", display: "grid", placeItems: "center", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600 }}>1</span>
              <span style={{ fontSize: 14.5, lineHeight: 1.5 }}>
                <strong>Return your forms.</strong> Complete and send back all three forms below — these must be received before your registration can be processed.
              </span>
            </li>
            {!isScholarship && (
            <li style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
              <span style={{ flex: "0 0 auto", width: 24, height: 24, borderRadius: 999, background: "var(--c-red)", color: "#fff", display: "grid", placeItems: "center", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600 }}>2</span>
              <span style={{ fontSize: 14.5, lineHeight: 1.5 }}>
                <strong>Pay your invoice.</strong> We'll email an invoice to {data.email} shortly. Your spot is confirmed only once both your completed forms and your invoice payment are received.
              </span>
            </li>
            )}
          </ol>
        </div>

        {/* ===== Document package ===== */}
        <div style={{
          marginTop: 40, textAlign: "left",
          background: "var(--c-paper)",
          border: "1px solid var(--c-line)",
          borderRadius: "var(--radius-card)",
          boxShadow: "var(--c-shadow)",
          overflow: "hidden",
        }}>
          <div style={{
            padding: "22px 26px",
            borderBottom: "1px solid var(--c-line)",
            display: "flex", alignItems: "center", justifyContent: "space-between",
            gap: 18, flexWrap: "wrap",
          }}>
            <div style={{ minWidth: 0 }}>
              <div className="mono" style={{ color: "var(--c-red)" }}>Your registration package · 3 forms</div>
              <div className="display" style={{ fontSize: 24, marginTop: 6, lineHeight: 1.05 }}>
                Complete &amp; return before registration is finalized
              </div>
              <p style={{ fontSize: 13.5, color: "var(--c-ink-soft)", margin: "8px 0 0", maxWidth: "54ch", lineHeight: 1.55 }}>
                Your forms should download automatically. Please complete all three and return them —
                printed or by email to{" "}
                <a href="mailto:coach_ad@londonlogicbasketball.com" style={{ color: "var(--c-ink)", textDecoration: "underline" }}>coach_ad@londonlogicbasketball.com</a>{" "}
                — before your registration can be completed.
              </p>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column" }}>
            {DOC_PACKAGE.map((d, i) => (
              <a
                key={d.file}
                ref={el => anchorRefs.current[i] = el}
                href={encodeURI(d.file)}
                download
                style={{
                  display: "flex", alignItems: "center", gap: 16,
                  padding: "16px 26px",
                  borderTop: i === 0 ? "none" : "1px solid var(--c-line)",
                  color: "var(--c-ink)", textDecoration: "none",
                }}
              >
                <span style={{
                  flex: "0 0 auto", width: 38, height: 38, borderRadius: 8,
                  background: "var(--c-bg)", border: "1px solid var(--c-line)",
                  display: "grid", placeItems: "center",
                  fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--c-red)", fontWeight: 500,
                }}>{d.n}</span>
                <span style={{ flex: 1, minWidth: 0 }}>
                  <span style={{ display: "block", fontWeight: 600, fontSize: 15 }}>{d.name}</span>
                  <span className="mono" style={{ color: "var(--c-ink-soft)", fontSize: 10 }}>PDF · fillable</span>
                </span>
                <span style={{
                  flex: "0 0 auto", display: "inline-flex", alignItems: "center", gap: 8,
                  color: "var(--c-red)", fontFamily: "var(--font-mono)", fontSize: 11,
                  letterSpacing: "0.08em", textTransform: "uppercase", fontWeight: 500,
                }}>Download ↓</span>
              </a>
            ))}
          </div>

          <div style={{ padding: "16px 26px", borderTop: "1px solid var(--c-line)", background: "var(--c-bg)" }}>
            <Btn kind="primary" onClick={triggerAll}>
              {autoTried ? "Download all 3 forms again" : "Download all 3 forms"}
            </Btn>
          </div>
        </div>

        <div style={{ display: "inline-flex", gap: 12, marginTop: 32 }}>
          <Btn to="home" kind="ghost">Back home</Btn>
          <Btn to="camp" kind="primary">Camp details</Btn>
        </div>
      </div>
    </section>
  );
}

/* ---------- form atoms ---------- */
function StepHead({ n, title }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <span className="mono" style={{ color: "var(--c-red)" }}>Step {n}</span>
      <h3 className="display" style={{ margin: "8px 0 0", fontSize: "clamp(28px, 4vw, 44px)", lineHeight: 1 }}>{title}</h3>
    </div>
  );
}
function Field({ label, value, onChange, full }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6, gridColumn: full ? "1 / -1" : undefined }}>
      <span className="mono" style={{ color: "var(--c-ink-soft)" }}>{label}</span>
      <input value={value} onChange={e => onChange(e.target.value)} style={{
        padding: "12px 14px", borderRadius: 10, border: "1.5px solid var(--c-line)",
        background: "var(--c-bg)", color: "var(--c-ink)", fontFamily: "inherit", fontSize: 15,
      }}/>
    </label>
  );
}
function Select({ label, value, onChange, options }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="mono" style={{ color: "var(--c-ink-soft)" }}>{label}</span>
      <select value={value} onChange={e => onChange(e.target.value)} style={{
        padding: "12px 14px", borderRadius: 10, border: "1.5px solid var(--c-line)",
        background: "var(--c-bg)", color: "var(--c-ink)", fontFamily: "inherit", fontSize: 15,
      }}>
        {options.map(o => <option key={o} value={o}>{o || "Select…"}</option>)}
      </select>
    </label>
  );
}
function Radio({ label, value, onChange, options }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="mono" style={{ color: "var(--c-ink-soft)" }}>{label}</span>
      <div style={{ display: "flex", gap: 8 }}>
        {options.map(([v, l]) => (
          <button key={v} onClick={() => onChange(v)} style={{
            flex: 1, padding: "12px 14px", borderRadius: 10,
            border: `1.5px solid ${value === v ? "var(--c-ink)" : "var(--c-line)"}`,
            background: value === v ? "var(--c-ink)" : "transparent",
            color: value === v ? "var(--c-paper)" : "var(--c-ink)",
            fontFamily: "inherit", fontSize: 15, fontWeight: 600, cursor: "pointer",
          }}>{l}</button>
        ))}
      </div>
    </div>
  );
}
function Check({ label, value, onChange }) {
  return (
    <label style={{
      display: "flex", gap: 12, alignItems: "flex-start",
      padding: "12px 14px", border: "1px solid var(--c-line)", borderRadius: 10,
      cursor: "pointer", background: value ? "color-mix(in oklab, var(--c-red) 6%, transparent)" : "transparent",
    }}>
      <input type="checkbox" checked={value} onChange={e => onChange(e.target.checked)} style={{ marginTop: 3 }}/>
      <span style={{ fontSize: 14 }}>{label}</span>
    </label>
  );
}
function ReviewBlock({ title, children }) {
  return (
    <div style={{
      padding: "16px 18px", background: "var(--c-bg)", borderRadius: 10,
      border: "1px solid var(--c-line)",
    }}>
      <div className="mono" style={{ color: "var(--c-red)", marginBottom: 10 }}>{title}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>{children}</div>
    </div>
  );
}
function Line({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14 }}>
      <span style={{ color: "var(--c-ink-soft)" }}>{k}</span>
      <span style={{ fontWeight: 600 }}>{v || "—"}</span>
    </div>
  );
}

function recommendDivision(grade) {
  const g = parseInt(grade, 10);
  if (g >= 11) return DIV_FULL.find(d => d.id === "elite");
  if (g >= 9) return DIV_FULL.find(d => d.id === "performance");
  if (g >= 7) return DIV_FULL.find(d => d.id === "development");
  if (g >= 4) return DIV_FULL.find(d => d.id === "foundation");
  if (g >= 1) return DIV_FULL.find(d => d.id === "rookie");
  return null;
}

window.RegisterPage = RegisterPage;
