/* global React, Star, Icon, SHOWS */
const { useState: useStateR } = React;

function Stepper({ steps, current }) {
  return (
    <div className="row" style={{ gap: 0, marginBottom: 36, flexWrap: "wrap" }}>
      {steps.map((s, i) => {
        const done = i < current, active = i === current;
        return (
          <div key={s} className="row" style={{ flex: "1 1 0", minWidth: 110 }}>
            <div className="row gap-8" style={{ flexShrink: 0 }}>
              <div style={{ width: 34, height: 34, borderRadius: "50%", flexShrink: 0,
                border: "var(--bd-ink)", display: "grid", placeItems: "center",
                background: done ? "var(--mint)" : active ? "var(--gold)" : "var(--white)",
                fontFamily: "var(--display)", fontWeight: 600, fontSize: 15 }}>
                {done ? <Icon name="check" size={17} stroke={3} /> : i + 1}
              </div>
              <span style={{ fontFamily: "var(--display)", fontWeight: 500, fontSize: 14.5,
                color: active ? "var(--ink)" : "var(--ink-soft)" }} className="step-label">{s}</span>
            </div>
            {i < steps.length - 1 && (
              <div style={{ flex: 1, height: 2.5, background: done ? "var(--mint)" : "var(--paper-2)",
                margin: "0 12px", borderRadius: 2, minWidth: 16 }} />
            )}
          </div>
        );
      })}
    </div>
  );
}

const TUITION = { full: 600, deposit: 50 };
const HEAR = ["Facebook / Instagram", "Dance Studio", "School", "Church", "Website", "Word of mouth", "Other"];
const SHOW_PREF = [
  { id: "either", label: "Either show — place my student" },
  { id: "frozen", label: "Disney's Frozen (ages 7–20)" },
  { id: "butterknife", label: "The Legend of the Butter Knife (ages 5–12)" },
  { id: "both", label: "Both shows (additional $200)" },
];

function SubHead({ children }) {
  return (
    <h4 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 15, letterSpacing: ".06em",
      textTransform: "uppercase", color: "var(--gold-deep)", marginTop: 8, marginBottom: 12 }}>{children}</h4>
  );
}

function RegisterPage({ navigate, setEnrollment }) {
  const STEPS = ["Student", "Interests", "Family", "Review"];
  const [step, setStep] = useStateR(0);
  const [done, setDone] = useStateR(false);
  const [f, setF] = useStateR({
    // Step 1 — Student
    first: "", last: "", age: "", studentEmail: "",
    // Step 2 — Interests
    showPref: "either", experience: "", conflicts: "",
    // Step 3 — Family & contact
    parentName: "", email: "", phone: "", street: "", city: "", state: "CA", zip: "",
    emergency: "", sae: "No", hear: "",
    // Step 4 — Plan
    plan: "deposit",
  });
  const up = (k) => (e) => setF({ ...f, [k]: e.target ? e.target.value : e });

  const canNext = () => {
    if (step === 0) return f.first && f.last && f.age;
    if (step === 1) return true;
    if (step === 2) return f.parentName && /.+@.+\..+/.test(f.email) && f.phone;
    return true;
  };
  const prefShow = SHOW_PREF.find(s => s.id === f.showPref);
  const totalTuition = f.sae === "Yes" ? 0 : f.showPref === "both" ? 800 : 600;
  const deposit = totalTuition === 0 ? 0 : 50;

  const submit = () => {
    // In production this POSTs to a webhook that creates the Airtable record
    // and a Square Checkout Link parameterized with the new Student ID.
    setEnrollment({
      student: `${f.first} ${f.last}`, show: prefShow.label, email: f.email,
      tuition: totalTuition, amount: deposit, sae: f.sae === "Yes",
    });
    setDone(true);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  if (done) {
    return (
      <div className="wrap" style={{ paddingBlock: "clamp(48px,8vw,90px)", maxWidth: 720 }}>
        <div className="card pop" style={{ padding: "clamp(28px,5vw,52px)", textAlign: "center" }}>
          <div style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--mint)", border: "var(--bd-ink)",
            display: "grid", placeItems: "center", margin: "0 auto 20px", boxShadow: "var(--shadow-sm)" }}>
            <Icon name="check" size={38} stroke={3} />
          </div>
          <h1 style={{ fontSize: "clamp(30px,4.5vw,44px)" }}>You're on the list, {f.first}! 🎭</h1>
          <p className="muted" style={{ fontSize: 17, marginTop: 12, maxWidth: 480, margin: "12px auto 0" }}>
            We've added {f.first}'s registration to our roster and emailed a confirmation to <b style={{ color: "var(--ink)" }}>{f.email}</b>.
            {totalTuition === 0 ? " SAE tuition is fully sponsored — nothing else to do." : " Lock in the spot with the $50 deposit now."}
          </p>
          <div className="card" style={{ background: "var(--gold-tint)", padding: 18, margin: "26px auto", maxWidth: 440 }}>
            <div className="row between" style={{ alignItems: "center" }}>
              <div style={{ textAlign: "left" }}>
                <div style={{ fontFamily: "var(--display)", fontWeight: 600 }}>{f.first} {f.last}</div>
                <div className="muted" style={{ fontSize: 13.5 }}>{totalTuition === 0 ? "SAE — sponsored" : `${prefShow.label.split(" (")[0]} · $${totalTuition} tuition`}</div>
              </div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 26 }}>
                {totalTuition === 0 ? "$0" : `$${deposit}`}
              </div>
            </div>
            {totalTuition > 0 && (
              <div className="muted" style={{ fontSize: 12.5, marginTop: 10, paddingTop: 10, borderTop: "1.5px dashed rgba(33,29,23,.2)" }}>
                Remaining ${totalTuition - deposit} due by <b style={{ color: "var(--ink)" }}>July 13, 2026</b>. Pay any amount, anytime.
              </div>
            )}
          </div>
          <div className="row gap-12" style={{ justifyContent: "center", flexWrap: "wrap" }}>
            {totalTuition === 0 ? (
              <button className="btn btn--gold btn--lg" onClick={() => navigate("hub")}>
                Go to Family Hub <Icon name="arrow" size={18} stroke={2.6} />
              </button>
            ) : (
              <>
                <button className="btn btn--gold btn--lg" onClick={() => navigate("payment")}>
                  <Icon name="card" size={18} /> Pay $50 deposit with Square
                </button>
                <button className="btn btn--lg" onClick={() => navigate("hub")}>Go to Family Hub</button>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="wrap" style={{ paddingBlock: "clamp(36px,6vw,72px)", maxWidth: 880 }}>
      <div style={{ marginBottom: 28 }}>
        <span className="kicker"><Star size={13} fill="var(--gold-deep)" /> Summer 2026 enrollment</span>
        <h1 style={{ fontSize: "clamp(30px,4.5vw,48px)", marginTop: 10 }}>Register & request an audition</h1>
        <p className="muted" style={{ fontSize: 16.5, marginTop: 8, maxWidth: 560 }}>
          One form holds your student's place. We'll confirm by email and follow up with audition details.
        </p>
      </div>

      <div className="card" style={{ padding: "clamp(22px,4vw,40px)" }}>
        <Stepper steps={STEPS} current={step} />

        {step === 0 && (
          <div className="pop">
            <SubHead>About the student</SubHead>
            <div className="form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div className="field"><label>First name *</label>
                <input className="input" value={f.first} onChange={up("first")} placeholder="Ava" /></div>
              <div className="field"><label>Last name *</label>
                <input className="input" value={f.last} onChange={up("last")} placeholder="Reyes" /></div>
              <div className="field"><label>Age this summer *</label>
                <input className="input" value={f.age} onChange={up("age")} placeholder="11" inputMode="numeric" /></div>
              <div className="field"><label>Student email (optional)</label>
                <input className="input" value={f.studentEmail} onChange={up("studentEmail")} placeholder="if they have one" /></div>
            </div>
          </div>
        )}

        {step === 1 && (
          <div className="pop">
            <SubHead>Show preference</SubHead>
            <p className="muted" style={{ fontSize: 14, marginBottom: 14, marginTop: -4 }}>
              Casting decisions happen after auditions — this just tells us where they'd love to be.
            </p>
            <div className="field" style={{ marginBottom: 18 }}>
              <select className="select" value={f.showPref} onChange={up("showPref")}>
                {SHOW_PREF.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
              </select>
            </div>
            <SubHead>A little more</SubHead>
            <div className="form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div className="field"><label>Stage experience</label>
                <select className="select" value={f.experience} onChange={up("experience")}>
                  <option value="">Select…</option>
                  <option>This is my first show!</option>
                  <option>A little (school / church)</option>
                  <option>Several productions</option>
                  <option>Lots — I'm a veteran</option>
                </select></div>
              <div className="field"><label>SAE student? *</label>
                <select className="select" value={f.sae} onChange={up("sae")}>
                  <option>No</option>
                  <option>Yes</option>
                </select>
                <span className="hint">SAE students have tuition fully sponsored by the school.</span></div>
              <div className="field" style={{ gridColumn: "1 / -1" }}>
                <label>Known schedule conflicts</label>
                <textarea className="textarea" value={f.conflicts} onChange={up("conflicts")}
                  placeholder="e.g. Away July 6–10. Helps us plan around your student." />
              </div>
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="pop">
            <SubHead>Parent / guardian</SubHead>
            <div className="form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div className="field" style={{ gridColumn: "1 / -1" }}><label>Your name *</label>
                <input className="input" value={f.parentName} onChange={up("parentName")} placeholder="Jordan Reyes" /></div>
              <div className="field"><label>Email *</label>
                <input className="input" value={f.email} onChange={up("email")} placeholder="you@email.com" /></div>
              <div className="field"><label>Mobile phone *</label>
                <input className="input" value={f.phone} onChange={up("phone")} placeholder="(626) 555-0143" /></div>
            </div>

            <SubHead>Mailing address</SubHead>
            <div className="form-grid" style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr", gap: 14 }}>
              <div className="field" style={{ gridColumn: "1 / -1" }}><label>Street address</label>
                <input className="input" value={f.street} onChange={up("street")} placeholder="123 Main St" /></div>
              <div className="field"><label>City</label>
                <input className="input" value={f.city} onChange={up("city")} placeholder="Pomona" /></div>
              <div className="field"><label>State</label>
                <input className="input" value={f.state} onChange={up("state")} placeholder="CA" /></div>
              <div className="field"><label>ZIP</label>
                <input className="input" value={f.zip} onChange={up("zip")} placeholder="91766" inputMode="numeric" /></div>
            </div>

            <SubHead>Just one more thing</SubHead>
            <div className="form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <div className="field" style={{ gridColumn: "1 / -1" }}><label>Emergency contact</label>
                <input className="input" value={f.emergency} onChange={up("emergency")}
                  placeholder="Name, relationship & phone — e.g. Jenny Reyes, mother, (626) 555-0143" /></div>
              <div className="field" style={{ gridColumn: "1 / -1" }}><label>How did you hear about us?</label>
                <select className="select" value={f.hear} onChange={up("hear")}>
                  <option value="">Select…</option>
                  {HEAR.map(o => <option key={o}>{o}</option>)}
                </select></div>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="pop">
            <SubHead>Review</SubHead>
            <div className="review-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 22 }}>
              {[["Student", `${f.first} ${f.last}`], ["Age", f.age || "—"], ["Show preference", prefShow.label.split(" (")[0]],
                ["Parent", f.parentName || "—"], ["Email", f.email || "—"], ["Phone", f.phone || "—"],
                ["City / ZIP", `${f.city || "—"} ${f.zip || ""}`.trim()],
                ["SAE student", f.sae]].map(([k, v]) => (
                <div key={k} className="row between" style={{ background: "var(--paper)", border: "1.5px solid var(--paper-2)",
                  borderRadius: 12, padding: "10px 14px" }}>
                  <span className="muted" style={{ fontSize: 14 }}>{k}</span>
                  <span style={{ fontFamily: "var(--display)", fontWeight: 500, fontSize: 15 }}>{v}</span>
                </div>
              ))}
            </div>

            <SubHead>Your tuition</SubHead>
            <div className="card" style={{ background: "var(--gold-tint)", padding: 22, marginBottom: 14 }}>
              <div className="row between" style={{ alignItems: "flex-start", flexWrap: "wrap", gap: 12 }}>
                <div>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 17 }}>
                    {f.sae === "Yes" ? "SAE student — fully sponsored" : f.showPref === "both" ? "Both shows" : "One show"}
                  </div>
                  <div className="muted" style={{ fontSize: 13.5, marginTop: 4, maxWidth: 360 }}>
                    {totalTuition === 0
                      ? "Tuition is covered by the school — no payment required."
                      : <>$50 deposit holds the spot. Pay any amount, anytime — the balance is due in full by <b style={{ color: "var(--ink)" }}>July 13, 2026</b>.</>}
                  </div>
                </div>
                <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 32 }}>
                  {totalTuition === 0 ? "Sponsored" : `$${totalTuition}`}
                </div>
              </div>
            </div>
            <p className="muted" style={{ fontSize: 13 }}>
              {f.sae === "Yes"
                ? "Have a sibling who isn't an SAE student? Their balance will appear in your Family Hub after they register."
                : "Need-based scholarships are available — no student is turned away for cost. Reply to the confirmation email and we'll set one up quietly."}
            </p>
          </div>
        )}

        {/* nav */}
        <div className="row between" style={{ marginTop: 30, gap: 12 }}>
          <button className="btn btn--ghost" onClick={() => step === 0 ? navigate("home") : setStep(step - 1)}>
            {step === 0 ? "Cancel" : "Back"}
          </button>
          {step < STEPS.length - 1 ? (
            <button className="btn btn--gold" disabled={!canNext()} onClick={() => setStep(step + 1)}>
              Continue <Icon name="arrow" size={17} stroke={2.6} />
            </button>
          ) : (
            <button className="btn btn--gold" onClick={submit}>
              {totalTuition === 0 ? "Submit registration" : "Submit & pay deposit with Square"} <Icon name="arrow" size={17} stroke={2.6} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RegisterPage, TUITION });
