/* Mobile multi-step register flow */

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

const REG_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 REG_WEEK_RANGES = ["Aug 3 – 7", "Aug 10 – 14", "Aug 17 – 21"];

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

const REG_WEB3FORMS_KEY = "b8d90ff4-9ffd-422f-a59d-c0c2d5e120c6";

async function regSubmitRegistrationEmail(data) {
  const division = DIVISIONS.find(d => d.id === data.division);
  const total = regComputeTotal(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} (${REG_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: REG_WEB3FORMS_KEY,
    subject,
    from_name: "London LOGIC Basketball — Registration Form (Mobile)",
    "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 recommendDivisionId(grade) {
  const g = parseInt(grade, 10);
  if (g >= 11) return "elite";
  if (g >= 9) return "performance";
  if (g >= 7) return "development";
  if (g >= 4) return "foundation";
  if (g >= 1) return "rookie";
  return null;
}

function RegisterPage({ onGo }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState(() => {
    let initialMode = "paid";
    let initialDivision = "";
    let initialWeeks = [1, 2, 3];
    try {
      const stored = localStorage.getItem("ll_register_mode");
      if (stored === "scholarship") {
        initialMode = "scholarship";
        localStorage.removeItem("ll_register_mode");
      }
      const div = localStorage.getItem("ll_register_division");
      if (div) {
        initialDivision = div;
        localStorage.removeItem("ll_register_division");
      }
      const w = localStorage.getItem("ll_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: initialDivision, 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 };
    if (patch.selectedWeeks) {
      try { localStorage.setItem("ll_register_weeks", JSON.stringify(next.selectedWeeks)); } catch (e) {}
    }
    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;
  };

  // scroll to top on step change
  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, [step, submitted]);

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

  return (
    <main className="page" style={{ paddingBottom: "calc(120px + env(safe-area-inset-bottom, 0px))" }}>
      {/* Hero */}
      <section style={{ padding: "10px var(--gutter) 18px" }}>
        <span className="eyebrow">Registration · 2026 cohort</span>
        <h1 className="display" style={{ margin: "10px 0 0", fontSize: 48, lineHeight: 0.95 }}>
          Reserve your <span style={{ color: "var(--c-red)" }}>spot.</span>
        </h1>
        <p style={{ marginTop: 12, color: "var(--c-ink-soft)", fontSize: 14.5, lineHeight: 1.55 }}>
          120 spots total — 24 per division. We'll save your place once you complete the steps below.
        </p>
      </section>

      {/* Mode toggle */}
      <section style={{ padding: "0 var(--gutter) 14px" }}>
        <div style={{
          background: "var(--c-paper)",
          border: "1px solid var(--c-line)",
          borderRadius: 14, padding: 5,
          display: "flex", flexDirection: "column", gap: 5,
        }}>
          {[
            { v: "paid",        lbl: "Paid Registration",      sub: "1, 2, or 3 weeks",                     icon: "💳" },
            { v: "scholarship", lbl: "Scholarship Application", sub: "1 of 10 fully-funded spots · 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 })} className="tappable" style={{
                display: "flex", alignItems: "center", gap: 12, textAlign: "left",
                background: on
                  ? (isScholar ? "var(--c-red)" : "#15110d")
                  : "transparent",
                color: on ? "#fff" : "rgba(255,255,255,0.78)",
                border: "none", borderRadius: 10,
                padding: "12px 12px",
                cursor: "pointer", width: "100%",
              }}>
                <div style={{
                  flex: "0 0 auto", width: 34, height: 34, borderRadius: 8,
                  background: on ? "rgba(255,255,255,0.18)" : (isScholar ? "var(--c-red)" : "#15110d"),
                  color: "#fff",
                  display: "grid", placeItems: "center",
                  fontSize: 16, fontWeight: 700,
                }}>{o.icon}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="display" style={{ fontSize: 15.5, lineHeight: 1.1 }}>{o.lbl}</div>
                  <div className="mono" style={{
                    marginTop: 4, fontSize: 9.5,
                    color: on ? "rgba(255,255,255,0.85)" : "rgba(255,255,255,0.5)",
                  }}>{o.sub}</div>
                </div>
                {on && (
                  <span style={{
                    flex: "0 0 auto", width: 22, height: 22, borderRadius: 999,
                    background: "rgba(255,255,255,0.22)",
                    display: "grid", placeItems: "center",
                    fontSize: 12, fontWeight: 700,
                  }}>✓</span>
                )}
              </button>
            );
          })}
        </div>
      </section>

      {/* Scholarship banner */}
      {data.mode === "scholarship" && (
        <section style={{ padding: "0 var(--gutter) 14px" }}>
          <div className="card card-red" style={{ padding: "20px 20px" }}>
            <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
              <div style={{
                flex: "0 0 auto", width: 48, height: 48, borderRadius: 10,
                background: "rgba(0,0,0,0.28)", display: "grid", placeItems: "center",
              }}>
                <span className="display" style={{ fontSize: 22, color: "#fff", lineHeight: 1 }}>10</span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="mono" style={{ color: "rgba(255,255,255,0.92)", fontSize: 9.5 }}>
                  Applying for Scholarship · FREE
                </div>
                <div className="display" style={{ marginTop: 6, fontSize: 18, lineHeight: 1.1, color: "#fff" }}>
                  1 boy &amp; 1 girl per division — full ride.
                </div>
                <p style={{ marginTop: 6, fontSize: 12.5, color: "rgba(255,255,255,0.88)", lineHeight: 1.45, margin: "6px 0 0" }}>
                  Awarded on need + character. Short answer in Step 4. Recipients announced mid-June.
                </p>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Stepper */}
      <section style={{ padding: "4px var(--gutter) 14px" }}>
        <RegStepper step={step} onJump={(i) => i < step && setStep(i)}/>
      </section>

      {/* Step body */}
      <section style={{ padding: "0 var(--gutter) 20px" }}>
        <div key={step} className="card" style={{ padding: "22px 20px", animation: "pageIn 320ms var(--ease-snap) both" }}>
          {step === 0 && <RegStepAthlete data={data} update={update}/>}
          {step === 1 && <RegStepDivision data={data} update={update}/>}
          {step === 2 && <RegStepSchedule data={data} update={update}/>}
          {step === 3 && <RegStepGuardian data={data} update={update}/>}
          {step === 4 && <RegStepReview data={data}/>}
        </div>
      </section>

      {/* Submission error banner (above sticky nav) */}
      {submitError && (
        <div style={{
          position: "fixed", left: 12, right: 12, bottom: 78,
          zIndex: 31,
          background: "#15110d",
          border: "1px solid var(--c-red)",
          borderRadius: 12,
          padding: "12px 14px",
          color: "#fff", fontSize: 13, lineHeight: 1.45,
          boxShadow: "0 12px 32px rgba(0,0,0,0.45)",
        }}>
          <strong style={{ color: "var(--c-red)" }}>Couldn't send.</strong> {submitError}
          <br/>
          <span style={{ color: "rgba(255,255,255,0.7)" }}>
            Try again, or email{" "}
            <a href="mailto:coach_ad@londonlogicbasketball.com" style={{ color: "#fff" }}>coach_ad@londonlogicbasketball.com</a>{" "}directly.
          </span>
        </div>
      )}

      {/* Sticky bottom nav */}
      <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%)",
        display: "flex", gap: 8,
      }}>
        <button
          onClick={() => setStep(s => Math.max(0, s - 1))}
          disabled={step === 0}
          className="tappable"
          style={{
            flex: "0 0 90px", height: 52, borderRadius: 12,
            background: "transparent", color: step === 0 ? "var(--c-ink-dim)" : "#fff",
            border: `1px solid ${step === 0 ? "rgba(255,255,255,0.08)" : "rgba(255,255,255,0.35)"}`,
            fontFamily: "var(--font-display)", fontSize: 14,
            letterSpacing: "0.06em", textTransform: "uppercase",
            cursor: step === 0 ? "default" : "pointer",
          }}
        >← Back</button>
        {step < REG_STEPS.length - 1 ? (
          <button
            onClick={() => canAdvance() && setStep(s => s + 1)}
            disabled={!canAdvance()}
            className="tappable"
            style={{
              flex: 1, height: 52, borderRadius: 12,
              background: canAdvance() ? "var(--c-red)" : "rgba(230,24,44,0.35)",
              color: "#fff", border: "none",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
              fontFamily: "var(--font-display)", fontSize: 15.5,
              letterSpacing: "0.06em", textTransform: "uppercase",
              cursor: canAdvance() ? "pointer" : "default",
              boxShadow: canAdvance() ? "0 12px 32px rgba(230,24,44,0.45)" : "none",
            }}
          >
            Continue
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M2 7h10M8 3l4 4-4 4" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        ) : (
          <button
            onClick={async () => {
              if (sending) return;
              setSending(true); setSubmitError(null);
              try {
                await regSubmitRegistrationEmail(data);
                setSubmitted(true);
              } catch (err) {
                setSubmitError(err.message || "Network error.");
              } finally {
                setSending(false);
              }
            }}
            disabled={sending}
            className="tappable"
            style={{
              flex: 1, height: 52, borderRadius: 12,
              background: sending ? "rgba(230,24,44,0.55)" : "var(--c-red)",
              color: "#fff", border: "none",
              fontFamily: "var(--font-display)", fontSize: 15.5,
              letterSpacing: "0.06em", textTransform: "uppercase",
              cursor: sending ? "default" : "pointer",
              boxShadow: "0 12px 32px rgba(230,24,44,0.45)",
            }}
          >{sending ? "Sending…" : "Submit registration"}</button>
        )}
      </div>
    </main>
  );
}

function RegStepper({ step, onJump }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: `repeat(${REG_STEPS.length}, 1fr)`,
      gap: 6,
    }}>
      {REG_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: 5, borderRadius: 999,
              background: done || on ? "var(--c-red)" : "var(--c-line)",
              transition: "background 200ms ease",
            }}/>
            <div style={{ marginTop: 7, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span className="mono" style={{ color: on ? "var(--c-red)" : "var(--c-ink-dim)", fontSize: 8.5 }}>0{i + 1}</span>
              <span style={{
                fontSize: 9.5, fontWeight: 700,
                color: done || on ? "#fff" : "var(--c-ink-dim)",
                fontFamily: "var(--font-mono)", letterSpacing: "0.08em", textTransform: "uppercase",
              }}>{s}</span>
            </div>
          </button>
        );
      })}
    </div>
  );
}

/* ---------- STEPS ---------- */

function RegStepHead({ n, title }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <span className="mono" style={{ color: "var(--c-red)" }}>Step {n}</span>
      <h3 className="display" style={{ margin: "8px 0 0", fontSize: 28, lineHeight: 1.05, color: "#fff" }}>{title}</h3>
    </div>
  );
}

function RegField({ label, value, onChange, type = "text", placeholder }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="mono" style={{ color: "var(--c-ink-soft)", fontSize: 9.5 }}>{label}</span>
      <input
        value={value}
        onChange={e => onChange(e.target.value)}
        type={type}
        placeholder={placeholder}
        style={{
          padding: "14px 14px", borderRadius: 10,
          border: "1.5px solid var(--c-line)",
          background: "#0a0a0a", color: "#fff",
          fontFamily: "inherit", fontSize: 16,
          WebkitAppearance: "none",
        }}
      />
    </label>
  );
}

function RegSelect({ label, value, onChange, options }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="mono" style={{ color: "var(--c-ink-soft)", fontSize: 9.5 }}>{label}</span>
      <select
        value={value}
        onChange={e => onChange(e.target.value)}
        style={{
          padding: "14px 14px", borderRadius: 10,
          border: "1.5px solid var(--c-line)",
          background: "#0a0a0a", color: "#fff",
          fontFamily: "inherit", fontSize: 16,
          WebkitAppearance: "none",
          backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 12 12\'><path d=\'M3 5l3 3 3-3\' stroke=\'%23ffffff66\' stroke-width=\'1.6\' fill=\'none\' stroke-linecap=\'round\'/></svg>")',
          backgroundRepeat: "no-repeat",
          backgroundPosition: "right 14px center",
          paddingRight: 36,
        }}
      >
        {options.map(o => <option key={o} value={o} style={{ background: "#0a0a0a" }}>{o || "Select…"}</option>)}
      </select>
    </label>
  );
}

function RegRadio({ label, value, onChange, options }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="mono" style={{ color: "var(--c-ink-soft)", fontSize: 9.5 }}>{label}</span>
      <div style={{ display: "flex", gap: 8 }}>
        {options.map(([v, l]) => (
          <button
            key={v}
            onClick={() => onChange(v)}
            className="tappable"
            style={{
              flex: 1, padding: "13px 10px", borderRadius: 10,
              border: `1.5px solid ${value === v ? "#fff" : "var(--c-line)"}`,
              background: value === v ? "#fff" : "transparent",
              color: value === v ? "#0a0a0a" : "#fff",
              fontFamily: "inherit", fontSize: 14.5, fontWeight: 700, cursor: "pointer",
            }}
          >{l}</button>
        ))}
      </div>
    </div>
  );
}

function RegCheck({ label, value, onChange }) {
  return (
    <label style={{
      display: "flex", gap: 12, alignItems: "flex-start",
      padding: "12px 14px",
      border: `1px solid ${value ? "rgba(230,24,44,0.6)" : "var(--c-line)"}`,
      borderRadius: 10, cursor: "pointer",
      background: value ? "rgba(230,24,44,0.08)" : "transparent",
    }}>
      <span style={{
        flex: "0 0 auto", marginTop: 2,
        width: 20, height: 20, borderRadius: 5,
        background: value ? "var(--c-red)" : "transparent",
        border: `1.5px solid ${value ? "var(--c-red)" : "rgba(255,255,255,0.4)"}`,
        display: "grid", placeItems: "center",
        color: "#fff", fontSize: 12, fontWeight: 700,
      }}>{value ? "✓" : ""}</span>
      <input
        type="checkbox"
        checked={value}
        onChange={e => onChange(e.target.checked)}
        style={{ position: "absolute", opacity: 0, pointerEvents: "none" }}
      />
      <span style={{ fontSize: 13.5, color: "#fff", lineHeight: 1.45 }}>{label}</span>
    </label>
  );
}

function RegStepAthlete({ data, update }) {
  return (
    <div>
      <RegStepHead n="01" title="Tell us about the athlete"/>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <RegField label="First name" value={data.firstName} onChange={v => update({ firstName: v })}/>
        <RegField label="Last name"  value={data.lastName}  onChange={v => update({ lastName: v })}/>
        <RegSelect 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"]}/>
        <RegRadio label="Gender" value={data.gender} onChange={v => update({ gender: v })}
          options={[["boys", "Boys"], ["girls", "Girls"]]}/>
      </div>
    </div>
  );
}

function RegStepDivision({ data, update }) {
  const recId = recommendDivisionId(data.grade);
  const recommended = DIVISIONS.find(d => d.id === recId);
  return (
    <div>
      <RegStepHead n="02" title="Choose a division"/>
      {recommended && (
        <div style={{
          padding: "11px 14px", marginBottom: 14, borderRadius: 10,
          background: "rgba(230,24,44,0.10)",
          border: "1px solid rgba(230,24,44,0.35)",
          fontSize: 13, color: "#fff", lineHeight: 1.4,
        }}>
          Based on Grade {data.grade}, we recommend{" "}
          <b style={{ color: recommended.color }}>{recommended.name} LOGIC</b>.
        </div>
      )}
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {DIVISIONS.map(d => {
          const on = data.division === d.id;
          return (
            <button
              key={d.id}
              onClick={() => update({ division: d.id })}
              className="tappable"
              style={{
                background: on ? d.color : "#0a0a0a",
                color: on ? "#fff" : "#fff",
                border: `1.5px solid ${on ? d.color : "var(--c-line)"}`,
                borderRadius: 12, padding: "14px 16px",
                textAlign: "left", cursor: "pointer",
                display: "flex", alignItems: "center", gap: 14,
              }}
            >
              <span className="display" style={{
                fontSize: 22, lineHeight: 1, color: on ? "#fff" : d.color, flex: "0 0 32px",
              }}>{d.roman}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="display" style={{ fontSize: 17, lineHeight: 1.1, color: "#fff" }}>{d.name}</div>
                <div className="mono" style={{
                  marginTop: 4, fontSize: 9.5,
                  color: on ? "rgba(255,255,255,0.92)" : "var(--c-ink-soft)",
                }}>{d.grades} · {d.tagline}</div>
              </div>
              {on && (
                <span style={{
                  flex: "0 0 auto", width: 22, height: 22, borderRadius: 999,
                  background: "rgba(0,0,0,0.28)", display: "grid", placeItems: "center",
                  fontSize: 12, fontWeight: 700, color: "#fff",
                }}>✓</span>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function RegStepSchedule({ data, update }) {
  const eliteOnly = data.division === "elite";
  const division = DIVISIONS.find(d => d.id === data.division);
  const total = regComputeTotal(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>
      <RegStepHead n="03" title="Choose your weeks"/>
      <p style={{ marginTop: -12, marginBottom: 14, color: "var(--c-ink-soft)", fontSize: 13.5, lineHeight: 1.5 }}>
        Families may register for 1, 2, or 3 weeks. The full 3-week experience is recommended for the complete LOGIC pathway and best weekly value.
      </p>

      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {[1, 2, 3].map(n => {
          const on = data.selectedWeeks.includes(n);
          return (
            <button
              key={n}
              onClick={() => toggleWeek(n)}
              className="tappable"
              style={{
                background: on ? "var(--c-red)" : "#15110d",
                color: "#fff",
                border: `1.5px solid ${on ? "var(--c-red)" : "rgba(255,255,255,0.06)"}`,
                borderRadius: 12, padding: "14px 16px",
                display: "flex", justifyContent: "space-between", alignItems: "center", gap: 14,
                width: "100%", textAlign: "left", cursor: "pointer",
                transition: "background 180ms ease, border-color 180ms ease",
              }}
            >
              <div style={{ minWidth: 0 }}>
                <span className="mono" style={{ color: on ? "rgba(255,255,255,0.9)" : "var(--c-red)" }}>Week {n}</span>
                <div className="display" style={{ marginTop: 4, fontSize: 22, lineHeight: 1, color: "#fff" }}>{REG_WEEK_RANGES[n - 1]}</div>
                <div className="mono" style={{ marginTop: 4, color: on ? "rgba(255,255,255,0.75)" : "rgba(255,255,255,0.5)", fontSize: 9.5 }}>Mon – Fri</div>
              </div>
              <span style={{
                flex: "0 0 auto", width: 28, height: 28, borderRadius: 6,
                background: on ? "rgba(255,255,255,0.22)" : "transparent",
                border: `1.5px solid ${on ? "rgba(255,255,255,0.55)" : "rgba(255,255,255,0.25)"}`,
                color: "#fff",
                display: "grid", placeItems: "center", fontSize: 14, fontWeight: 700,
              }}>{on ? "✓" : ""}</span>
            </button>
          );
        })}
      </div>

      {data.selectedWeeks.length === 0 && (
        <div style={{
          marginTop: 12, padding: "11px 14px", borderRadius: 10,
          background: "rgba(230,24,44,0.12)",
          border: "1px solid rgba(230,24,44,0.4)",
          fontSize: 13, color: "#fff",
        }}>
          Select at least one week to continue.
        </div>
      )}

      {/* Live price summary — paid only */}
      {data.mode !== "scholarship" && (
      <div style={{
        marginTop: 16,
        background: "#15110d", color: "#fff",
        borderRadius: 12, padding: "18px 18px",
        position: "relative", overflow: "hidden",
      }}>
        {allThree && (
          <div style={{
            display: "inline-block",
            background: "var(--c-red)", color: "#fff",
            padding: "4px 10px", borderRadius: 999,
            fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.12em",
            textTransform: "uppercase", fontWeight: 600,
            marginBottom: 10,
          }}>★ Best Value · Full LOGIC</div>
        )}
        <div className="mono" style={{ color: "var(--c-red)" }}>Your selection</div>
        <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12 }}>
            <span className="mono" style={{ color: "rgba(255,255,255,0.55)", fontSize: 9.5 }}>Division</span>
            <span style={{ color: "#fff", fontWeight: 700, fontSize: 14, textAlign: "right" }}>
              {division ? `${division.name} LOGIC` : "—"}
            </span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12 }}>
            <span className="mono" style={{ color: "rgba(255,255,255,0.55)", fontSize: 9.5 }}>Weeks</span>
            <span style={{ color: "#fff", fontWeight: 700, fontSize: 14, textAlign: "right" }}>
              {data.selectedWeeks.length === 0 ? "—" :
                data.selectedWeeks.length === 3 ? "All 3 weeks" :
                data.selectedWeeks.map(w => `Wk ${w}`).join(" + ")}
            </span>
          </div>
          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12,
            paddingTop: 12, borderTop: "1px solid rgba(255,255,255,0.12)",
          }}>
            <span className="mono" style={{ color: "rgba(255,255,255,0.55)", fontSize: 10 }}>Total</span>
            <span className="display" style={{
              fontSize: 30, lineHeight: 1,
              color: total ? "var(--c-red)" : "rgba(255,255,255,0.4)",
            }}>
              {total ? `$${total.toLocaleString()}` : "—"}
            </span>
          </div>
        </div>
        {!data.division && (
          <div className="mono" style={{
            marginTop: 10, color: "rgba(255,255,255,0.5)", fontSize: 9.5,
          }}>
            Choose a division in Step 02 to see your total.
          </div>
        )}
      </div>
      )}

      {showSponsor && (
        <div style={{
          marginTop: 16,
          background: "#15110d", color: "#fff",
          borderRadius: 12, padding: "20px 18px",
        }}>
          <span className="mono" style={{ color: "var(--c-red)" }}>Optional · Sponsor-a-Week</span>
          <div className="display" style={{ marginTop: 8, fontSize: 20, color: "#fff", lineHeight: 1.1 }}>
            Can't make one of your weeks? Donate it.
          </div>
          <p style={{ marginTop: 8, fontSize: 13, color: "rgba(255,255,255,0.78)", lineHeight: 1.5, margin: "8px 0 0" }}>
            If your athlete genuinely can't attend one of the weeks you've registered for,
            you can donate that week to a family in need — the spot funds a London athlete
            on scholarship instead of being lost.{" "}
            <a href="#scholarship" style={{ color: "#fff", textDecoration: "underline" }}>How it works →</a>
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, marginTop: 14 }}>
            {[
              { v: null, label: "Attending all" },
              ...data.selectedWeeks.map(w => ({ v: w, label: `Donate Week ${w}` })),
            ].map(o => {
              const on = data.donateWeek === o.v;
              return (
                <button key={String(o.v)} onClick={() => update({ donateWeek: o.v })} className="tappable" style={{
                  background: on ? "var(--c-red)" : "transparent",
                  color: "#fff",
                  border: `1.5px solid ${on ? "var(--c-red)" : "rgba(255,255,255,0.22)"}`,
                  borderRadius: 10, padding: "11px 8px",
                  fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.06em",
                  textTransform: "uppercase", fontWeight: 600, cursor: "pointer",
                }}>{o.label}</button>
              );
            })}
          </div>
        </div>
      )}

      {eliteOnly && (
        <div style={{
          marginTop: 14, padding: "16px 16px",
          background: "var(--c-red)", color: "#fff",
          borderRadius: 12,
        }}>
          <span className="mono" style={{ color: "rgba(255,255,255,0.9)" }}>Elite athletes</span>
          <div className="display" style={{ marginTop: 6, fontSize: 20, color: "#fff" }}>Aug 22 · Community Game</div>
          <p style={{ margin: "6px 0 12px", fontSize: 13, color: "rgba(255,255,255,0.95)" }}>
            Included for all Elite registrants.
          </p>
          <label style={{
            display: "flex", alignItems: "center", gap: 10, cursor: "pointer",
            padding: "10px 12px",
            background: "rgba(0,0,0,0.25)", borderRadius: 8,
          }}>
            <span style={{
              width: 20, height: 20, borderRadius: 5,
              background: data.wantsCommunityGame ? "#fff" : "transparent",
              border: "1.5px solid #fff",
              display: "grid", placeItems: "center",
              color: "var(--c-red)", fontSize: 12, fontWeight: 700,
            }}>{data.wantsCommunityGame ? "✓" : ""}</span>
            <input
              type="checkbox"
              checked={data.wantsCommunityGame}
              onChange={e => update({ wantsCommunityGame: e.target.checked })}
              style={{ position: "absolute", opacity: 0, pointerEvents: "none" }}
            />
            <span style={{ fontSize: 14, fontWeight: 600 }}>Confirm participation</span>
          </label>
        </div>
      )}
    </div>
  );
}

function RegStepGuardian({ data, update }) {
  return (
    <div>
      <RegStepHead n="04" title="Parent / guardian"/>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <RegField label="Full name" value={data.guardianName} onChange={v => update({ guardianName: v })}/>
        <RegField label="Phone" value={data.phone} onChange={v => update({ phone: v })} type="tel"/>
        <RegField label="Email" value={data.email} onChange={v => update({ email: v })} type="email"/>
      </div>

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

      {data.mode === "scholarship" && (
        <div style={{
          marginTop: 18, padding: "18px 16px",
          background: "rgba(230,24,44,0.08)",
          border: "1.5px solid rgba(230,24,44,0.35)",
          borderRadius: 12,
        }}>
          <span className="mono" style={{ color: "var(--c-red)" }}>Scholarship · short answer</span>
          <div className="display" style={{ fontSize: 19, marginTop: 6, lineHeight: 1.15, color: "#fff" }}>
            What would a LOGIC spot mean for your athlete?
          </div>
          <p style={{ fontSize: 12.5, color: "var(--c-ink-soft)", margin: "6px 0 10px", lineHeight: 1.5 }}>
            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: "12px 12px", borderRadius: 10,
              border: "1px solid var(--c-line)", background: "#0a0a0a",
              fontFamily: "inherit", fontSize: 14, lineHeight: 1.5, color: "#fff",
              WebkitAppearance: "none",
            }}
          />
          <div className="mono" style={{ marginTop: 6, color: "var(--c-ink-soft)", fontSize: 9.5 }}>
            {data.scholarshipReason.trim().length} chars · min 30
          </div>
        </div>
      )}

      <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 10 }}>
        <RegWaiverReview/>
        <RegCheck label="I have read and accept the program waiver, code of conduct, and policies."
          value={data.waiver} onChange={v => update({ waiver: v })}/>
        <RegCheck label="I consent to media coverage (photo / video) for the registered athlete."
          value={data.mediaConsent} onChange={v => update({ mediaConsent: v })}/>
        <RegCheck label="I consent to LOGIC recording a private player portfolio (training clips, skill assessments, growth notes) — for development feedback shared with our family."
          value={data.portfolioConsent} onChange={v => update({ portfolioConsent: v })}/>
        <RegCheck 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 RegReviewBlock({ title, children }) {
  return (
    <div style={{
      padding: "14px 16px", background: "#0a0a0a", 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 RegLine({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, fontSize: 13.5 }}>
      <span style={{ color: "var(--c-ink-soft)" }}>{k}</span>
      <span style={{ fontWeight: 600, color: "#fff", textAlign: "right" }}>{v || "—"}</span>
    </div>
  );
}

function RegStepReview({ data }) {
  const division = DIVISIONS.find(d => d.id === data.division);
  const total = regComputeTotal(data.division, data.selectedWeeks);
  const weeksLabel = data.selectedWeeks.length === 0 ? "—" :
    data.selectedWeeks.length === 3 ? "All 3 weeks" :
    data.selectedWeeks.map(w => `Wk ${w}`).join(" + ");
  return (
    <div>
      <RegStepHead n="05" title="Review & submit"/>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <RegReviewBlock title="Athlete">
          <RegLine k="Name" v={`${data.firstName} ${data.lastName}`.trim()}/>
          <RegLine k="Grade" v={data.grade}/>
          <RegLine k="Gender" v={data.gender}/>
        </RegReviewBlock>
        <RegReviewBlock title="Program">
          <RegLine k="Mode" v={data.mode === "scholarship" ? "Scholarship application" : "Paid registration"}/>
          <RegLine k="Division" v={division ? `${division.name} LOGIC` : ""}/>
          <RegLine k="Weeks" v={weeksLabel}/>
          <RegLine k="Total" v={data.mode === "scholarship" ? "Free (scholarship)" : (total ? `$${total.toLocaleString()}` : "—")}/>
          {data.donateWeek && <RegLine k="Sponsor-a-Week" v={`Donating Week ${data.donateWeek}`}/>}
          {data.division === "elite" && <RegLine k="Aug 22 game" v={data.wantsCommunityGame ? "Yes" : "No"}/>}
        </RegReviewBlock>
        <RegReviewBlock title="Guardian">
          <RegLine k="Name" v={data.guardianName}/>
          <RegLine k="Email" v={data.email}/>
          <RegLine k="Phone" v={data.phone}/>
        </RegReviewBlock>
        {data.mode !== "scholarship" && (
          <RegReviewBlock title="Billing address">
            <RegLine k="Street" v={data.billingStreet}/>
            <RegLine k="City" v={data.billingCity}/>
            <RegLine k="Province / State" v={data.billingProvince}/>
            <RegLine k="Postal / ZIP" v={data.billingPostal}/>
            <RegLine k="Country" v={data.billingCountry}/>
          </RegReviewBlock>
        )}
        <RegReviewBlock title="Consents">
          <RegLine k="Waiver" v={data.waiver ? "Accepted" : "—"}/>
          <RegLine k="Media" v={data.mediaConsent ? "Yes" : "No"}/>
          <RegLine k="Player portfolio" v={data.portfolioConsent ? "Yes" : "No"}/>
          <RegLine k="Email updates" v={data.emailConsent ? "Yes" : "No"}/>
        </RegReviewBlock>
      </div>
      <p style={{ marginTop: 14, color: "var(--c-ink-soft)", fontSize: 12.5, lineHeight: 1.5 }}>
        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 (mobile lives in /mobile, so paths go up one level). */
const REG_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 RegThankYou({ data, onGo }) {
  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;
      setTimeout(() => a.click(), i * 600);
    });
  }, []);

  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 (
      <main className="page" style={{ paddingBottom: 80 }}>
        <section style={{ padding: "60px var(--gutter) 40px", textAlign: "center" }}>
          <span className="eyebrow" style={{ justifyContent: "center" }}>Application received</span>
          <h1 className="display" style={{ margin: "16px 0 0", fontSize: 76, lineHeight: 0.92, color: "#fff" }}>
            You have <span style={{ color: "var(--c-red)" }}>applied.</span>
          </h1>
          <p style={{ marginTop: 16, color: "var(--c-ink-soft)", fontSize: 15, lineHeight: 1.55, padding: "0 8px" }}>
            Thanks {data.firstName || "—"}. We've logged your scholarship application and will email{" "}
            <span style={{ color: "#fff" }}>{data.email || "you"}</span> within 2 business days to confirm.
          </p>
        </section>
        <section style={{ padding: "0 var(--gutter) 24px", display: "flex", flexDirection: "column", gap: 10 }}>
          <button className="btn tappable" onClick={() => onGo("camp")}>Camp details →</button>
          <button className="btn btn-ghost tappable" onClick={() => onGo("home")}>Back home</button>
        </section>
      </main>
    );
  }

  return (
    <main className="page" style={{ paddingBottom: 80 }}>
      <section style={{ padding: "52px var(--gutter) 24px", textAlign: "center" }}>
        <span className="eyebrow" style={{ justifyContent: "center" }}>Application received</span>
        <h1 className="display" style={{ margin: "16px 0 0", fontSize: 64, lineHeight: 0.92, color: "#fff" }}>
          You have <span style={{ color: "var(--c-red)" }}>applied.</span>
        </h1>
        <p style={{ marginTop: 14, color: "var(--c-ink-soft)", fontSize: 14.5, lineHeight: 1.55, padding: "0 4px" }}>
          Thanks {data.firstName || "—"} — your spot is being held, but your registration is{" "}
          <strong style={{ color: "#fff" }}>not complete yet</strong>. We've sent the details to{" "}
          <span style={{ color: "#fff" }}>{data.email || "you"}</span>.
        </p>
      </section>

      {/* What's left to finalize */}
      <section style={{ padding: "0 var(--gutter) 14px" }}>
        <div style={{
          background: "rgba(230,24,44,0.08)",
          border: "1.5px solid rgba(230,24,44,0.4)",
          borderRadius: 14, padding: "18px 16px", textAlign: "left",
        }}>
          <span className="mono" style={{ color: "var(--c-red)", fontSize: 10 }}>Not complete until both steps are done</span>
          <ol style={{ margin: "12px 0 0", padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 12 }}>
            <li style={{ display: "flex", gap: 11, alignItems: "flex-start" }}>
              <span style={{ flex: "0 0 auto", width: 22, height: 22, 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: 13.5, lineHeight: 1.5, color: "#fff" }}>
                <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>
            <li style={{ display: "flex", gap: 11, alignItems: "flex-start" }}>
              <span style={{ flex: "0 0 auto", width: 22, height: 22, 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: 13.5, lineHeight: 1.5, color: "#fff" }}>
                <strong>Pay your invoice.</strong> We'll email an invoice to {data.email || "you"} shortly. Your spot is confirmed only once both your completed forms and your invoice payment are received.
              </span>
            </li>
          </ol>
        </div>
      </section>

      {/* Document package */}
      <section style={{ padding: "0 var(--gutter) 18px" }}>
        <div style={{ background: "var(--c-paper)", border: "1px solid var(--c-line)", borderRadius: 14, overflow: "hidden", textAlign: "left" }}>
          <div style={{ padding: "18px 16px", borderBottom: "1px solid var(--c-line)" }}>
            <span className="mono" style={{ color: "var(--c-red)", fontSize: 10 }}>Your registration package · 3 forms</span>
            <div className="display" style={{ fontSize: 19, marginTop: 6, lineHeight: 1.1, color: "#fff" }}>
              Complete &amp; return before registration is finalized
            </div>
            <p style={{ fontSize: 12.5, color: "var(--c-ink-soft)", margin: "8px 0 0", lineHeight: 1.5 }}>
              Your forms should download automatically. Complete all three and return them — printed or by email to{" "}
              <a href="mailto:coach_ad@londonlogicbasketball.com" style={{ color: "#fff", textDecoration: "underline" }}>coach_ad@londonlogicbasketball.com</a>{" "}
              — before your registration can be completed.
            </p>
          </div>

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

          <div style={{ padding: "14px 16px", borderTop: "1px solid var(--c-line)", background: "#0a0a0a" }}>
            <button className="btn tappable" onClick={triggerAll}>
              {autoTried ? "Download all 3 forms again" : "Download all 3 forms"}
            </button>
          </div>
        </div>
      </section>

      <section style={{ padding: "0 var(--gutter) 24px", display: "flex", flexDirection: "column", gap: 10 }}>
        <button className="btn btn-ghost tappable" onClick={() => onGo("camp")}>Camp details →</button>
        <button className="btn btn-ghost tappable" onClick={() => onGo("home")}>Back home</button>
      </section>
    </main>
  );
}

Object.assign(window, { RegisterPage });
