// Enroll page — 5-step flow with SofAI helper + dynamic "what's next" rail

const { useState: useStateE, useMemo: useMemoE } = React;

const STEPS = [
  { id: 1, key: 'who', label: 'Who is enrolling' },
  { id: 2, key: 'grade', label: 'Grade & current school' },
  { id: 3, key: 'subjects', label: 'Subjects of interest' },
  { id: 4, key: 'contact', label: 'Contact information' },
  { id: 5, key: 'review', label: 'Review & submit' },
];

const SUBJECTS = [
  { id: 'math', name: 'Math', area: 'C', world: 'Math. Universe' },
  { id: 'sci', name: 'Lab Science', area: 'D', world: 'Deep Space · Cell' },
  { id: 'eng', name: 'English', area: 'B', world: 'Story Library' },
  { id: 'hist', name: 'History & Social Studies', area: 'A', world: 'Ancient Civ.' },
  { id: 'lang', name: 'Language Other than English', area: 'E', world: null },
  { id: 'arts', name: 'Visual & Performing Arts', area: 'F', world: null },
  { id: 'cs', name: 'Computer Science', area: 'G', world: null },
  { id: 'ai', name: 'AI & Machine Learning', area: 'G', world: 'Future City' },
  { id: 'engr', name: 'Engineering & Robotics', area: 'G', world: 'Future City' },
];

const SOFAI_HINTS = {
  1: { who: 'SOFAI · WELCOME', text: "I'll help you through this. About 10 minutes. You can pause and resume — your progress is saved. Start by picking who's enrolling." },
  2: { who: 'SOFAI · GRADE', text: "We serve grades 6 through 12. If you're transferring mid-year, choose the grade you'll be entering with us in August 2026." },
  3: { who: 'SOFAI · SUBJECTS', text: "Pick the areas you care most about — I'll match courses and worlds to your shortlist. You can change everything later with your advisor." },
  4: { who: 'SOFAI · CONTACT', text: "We use this to send the application decision (5–7 days) and the aid decision in the same window. No marketing emails." },
  5: { who: 'SOFAI · LAST STEP', text: "Looks complete. After you submit, you'll get a confirmation in your inbox and a calendar invite for a 20-minute orientation with me." },
};

const ProgressList = ({ step, setStep, complete }) => (
  <div className="progress-list">
    {STEPS.map(s => {
      const isActive = s.id === step;
      const isDone = s.id < step || complete;
      return (
        <div
          key={s.id}
          className={`progress-step ${isActive ? 'active' : ''} ${isDone ? 'done' : ''}`}
          onClick={() => { if (isDone || isActive) setStep(s.id); }}
        >
          <div className="marker">
            {isDone && !isActive ? <Icon name="check" size={14}/> : String(s.id).padStart(2, '0')}
          </div>
          <div className="label">{s.label}</div>
        </div>
      );
    })}
  </div>
);

const SofAIHelper = ({ step, complete }) => {
  const hint = complete ? { who: 'SOFAI · SUBMITTED', text: "Application in. I'll be in touch within five business days. In the meantime, your orientation invite is in your inbox." } : SOFAI_HINTS[step];
  return (
    <div className="sofai-helper">
      <div className="sofai-avatar"></div>
      <div>
        <div className="who">{hint.who}</div>
        <div className="text">{hint.text}</div>
      </div>
    </div>
  );
};

const WhatsNext = ({ step, data, complete }) => {
  if (complete) {
    return (
      <div className="enroll-rail-right">
        <div className="next-title">YOUR WELCOME PACKET</div>
        <div className="next-card">
          <div className="when">NOW</div>
          <h6>Confirmation email</h6>
          <p>Sent to {data.email || 'your inbox'}. Includes your application ID.</p>
        </div>
        <div className="next-card">
          <div className="when">+ 1 DAY</div>
          <h6>SofAI orientation</h6>
          <p>20-minute call. She'll preview the worlds matched to your subjects.</p>
        </div>
        <div className="next-card">
          <div className="when">+ 5–7 DAYS</div>
          <h6>Admissions decision</h6>
          <p>Aid decision in the same window.</p>
        </div>
        <div className="next-card">
          <div className="when">AUGUST 18, 2026</div>
          <h6>First day. First world.</h6>
          <p>Your cohort meets in the world that matches your top subject.</p>
        </div>
      </div>
    );
  }
  if (step <= 2) {
    return (
      <div className="enroll-rail-right">
        <div className="next-title">WHAT HAPPENS NEXT</div>
        <div className="next-card">
          <div className="when">STEP 3</div>
          <h6>Pick subjects</h6>
          <p>I'll match Marble worlds and AP courses to your interests.</p>
        </div>
        <div className="next-card">
          <div className="when">STEP 5 → 5 DAYS</div>
          <h6>Decision</h6>
          <p>Admissions and aid decisions arrive in the same window.</p>
        </div>
        <div className="next-card">
          <div className="when">AUG 18, 2026</div>
          <h6>Orientation in-world</h6>
          <p>20-minute walkthrough with SofAI and your cohort.</p>
        </div>
      </div>
    );
  }
  if (step === 3) {
    const matched = (data.subjects || []).map(id => SUBJECTS.find(s => s.id === id)).filter(Boolean);
    return (
      <div className="enroll-rail-right">
        <div className="next-title">MATCHED FOR YOU</div>
        {matched.length === 0 ? (
          <div className="next-card"><p style={{ color: 'var(--ink-3)' }}>Pick subjects and I'll surface matching worlds and courses.</p></div>
        ) : matched.map((s, i) => (
          <div className="next-card" key={i}>
            <div className="when">AREA {s.area} · UC A–G</div>
            <h6>{s.name}</h6>
            <p>{s.world ? <>Taught inside <span style={{ color: 'var(--accent)' }}>{s.world}</span>. AP + Honors tracks open.</> : 'Cohort-based. Honors and AP tracks where applicable.'}</p>
          </div>
        ))}
      </div>
    );
  }
  if (step === 4) {
    return (
      <div className="enroll-rail-right">
        <div className="next-title">PRIVACY · WE USE THIS FOR</div>
        <div className="next-card"><h6>Admissions decision</h6><p>Sent by email within 5–7 business days of submission.</p></div>
        <div className="next-card"><h6>Aid decision</h6><p>Same window. Same email.</p></div>
        <div className="next-card"><h6>SofAI orientation invite</h6><p>Calendar invite to a 20-minute orientation.</p></div>
        <div style={{ marginTop: 16, fontSize: 11, color: 'var(--ink-4)', fontFamily: 'Geist Mono', letterSpacing: '0.04em', lineHeight: 1.6 }}>
          NOT USED FOR MARKETING · NOT SOLD · FERPA-COMPLIANT · DELETED ON REQUEST
        </div>
      </div>
    );
  }
  // Step 5 — preview welcome
  return (
    <div className="enroll-rail-right">
      <div className="next-title">YOUR WELCOME PACKET · PREVIEW</div>
      <div className="next-card">
        <div className="when">DRAFTED · AWAITING SUBMIT</div>
        <h6>Welcome, {data.firstName || '_____'}</h6>
        <p>You'll meet SofAI on {new Date(Date.now() + 86400000).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} for a 20-minute orientation.</p>
      </div>
      <div className="next-card">
        <h6>Your matched worlds</h6>
        <p>{(data.subjects || []).map(id => SUBJECTS.find(s => s.id === id)?.world).filter(Boolean).slice(0,3).join(' · ') || '—'}</p>
      </div>
    </div>
  );
};

const EnrollForm = () => {
  const [step, setStep] = useStateE(1);
  const [complete, setComplete] = useStateE(false);
  const [data, setData] = useStateE({
    role: '', firstName: '', lastName: '', grade: '', currentSchool: '',
    subjects: [], email: '', phone: '', country: '', notes: ''
  });
  const [errors, setErrors] = useStateE({});

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const toggleSubject = (id) => setData(d => ({
    ...d,
    subjects: d.subjects.includes(id) ? d.subjects.filter(s => s !== id) : [...d.subjects, id],
  }));

  const validateStep = () => {
    const e = {};
    if (step === 1 && !data.role) e.role = 'Pick one to continue.';
    if (step === 2) {
      if (!data.grade) e.grade = 'Pick a grade.';
      if (!data.currentSchool) e.currentSchool = 'Required.';
    }
    if (step === 3 && data.subjects.length === 0) e.subjects = 'Pick at least one.';
    if (step === 4) {
      if (!data.firstName) e.firstName = 'Required.';
      if (!data.lastName) e.lastName = 'Required.';
      if (!data.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = 'Valid email required.';
      if (!data.country) e.country = 'Required.';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (!validateStep()) return;
    setErrors({});
    if (step < STEPS.length) setStep(step + 1);
  };

  const submit = () => {
    setComplete(true);
    setStep(5);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div className="enroll-shell">
      <aside className="enroll-rail-left">
        <div className="page-eyebrow"><span className="bar"></span>ENROLLMENT · 2026–27</div>
        <ProgressList step={step} setStep={setStep} complete={complete}/>
        <SofAIHelper step={step} complete={complete}/>
      </aside>

      <main className="enroll-main">
        {complete ? (
          <div className="success-stage">
            <div className="check"><Icon name="check" size={32}/></div>
            <h2 style={{ marginBottom: 16 }}>Application in.</h2>
            <p className="ink-2" style={{ fontSize: 17, maxWidth: 480, margin: '0 auto 16px' }}>
              Confirmation on its way to <b style={{ color: 'var(--ink-0)' }}>{data.email}</b>. SofAI will follow up to schedule your orientation.
            </p>
            <p className="mono ink-3" style={{ fontSize: 12, letterSpacing: '0.06em', marginTop: 24 }}>
              APPLICATION ID · TVS-2026-{Math.floor(Math.random()*9000+1000)}
            </p>
            <div style={{ marginTop: 40, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <a className="btn btn-primary btn-lg" href="index.html">Back to homepage</a>
              <a className="btn btn-secondary btn-lg" href="courses.html">Browse courses while you wait</a>
            </div>
          </div>
        ) : (
        <>
          <div className="mono ink-3" style={{ fontSize: 12, letterSpacing: '0.08em', marginBottom: 16 }}>STEP {String(step).padStart(2,'0')} OF 05</div>

          {step === 1 && (
            <div>
              <h2>Who is enrolling?</h2>
              <p className="sub">Pick one. You can switch roles later — many parents fill in for younger students.</p>
              <div className="choice-grid">
                {[
                  { id: 'student', ttl: 'I am the student.', desc: 'Grade 9–12 typically. You\'ll add a guardian email at step 4.' },
                  { id: 'parent', ttl: 'I am a parent or guardian.', desc: 'Enrolling on behalf of a student. You will be cc\'d on every email.' },
                  { id: 'school', ttl: 'I represent a school or district.', desc: 'Licensing rather than individual enrollment. Different flow.' },
                  { id: 'partner', ttl: 'I represent a partner organization.', desc: 'Research, sponsorship, or platform partnership.' },
                ].map(o => (
                  <button
                    key={o.id}
                    className={`choice ${data.role === o.id ? 'active' : ''}`}
                    onClick={() => update('role', o.id)}
                  >
                    <span className="ttl">{o.ttl}</span>
                    <span className="desc">{o.desc}</span>
                  </button>
                ))}
              </div>
              {errors.role && <div className="field-error" style={{ marginTop: 12 }}>{errors.role}</div>}
            </div>
          )}

          {step === 2 && (
            <div>
              <h2>Grade and current school.</h2>
              <p className="sub">We serve grades 6 through 12. Pick the grade the student will be entering in August 2026.</p>
              <div className="field-group">
                <div className="field">
                  <label className="field-label">Grade in 2026–27 <span className="req">*</span></label>
                  <div className="grade-row">
                    {['6','7','8','9','10','11','12'].map(g => (
                      <button key={g} className={`grade-btn ${data.grade === g ? 'active' : ''}`} onClick={() => update('grade', g)}>{g}</button>
                    ))}
                  </div>
                  {errors.grade && <div className="field-error">{errors.grade}</div>}
                </div>
                <div className="field">
                  <label className="field-label">Current school <span className="req">*</span></label>
                  <input
                    className={`field-input ${errors.currentSchool ? 'err' : ''}`}
                    placeholder="e.g. Palo Alto High School, or 'homeschooled'"
                    value={data.currentSchool}
                    onChange={(e) => update('currentSchool', e.target.value)}
                  />
                  {errors.currentSchool && <div className="field-error">{errors.currentSchool}</div>}
                </div>
                <div className="field">
                  <label className="field-label">Anything we should know? (optional)</label>
                  <textarea
                    className="field-input"
                    rows="3"
                    placeholder="Learning differences, scheduling constraints, sport commitments. SofAI uses this to plan placement."
                    value={data.notes}
                    onChange={(e) => update('notes', e.target.value)}
                  ></textarea>
                </div>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <h2>Subjects of interest.</h2>
              <p className="sub">Pick three to six. We use this to match Marble worlds and AP placement. Nothing here is final.</p>
              <div className="subj-grid">
                {SUBJECTS.map(s => {
                  const on = data.subjects.includes(s.id);
                  return (
                    <button key={s.id} className={`subj-btn ${on ? 'active' : ''}`} onClick={() => toggleSubject(s.id)}>
                      <span style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                        <span>{s.name}</span>
                        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.04em' }}>
                          AREA {s.area}{s.world ? <> · {s.world.toUpperCase()}</> : ''}
                        </span>
                      </span>
                      <span className="ck">{on && <Icon name="check" size={11}/>}</span>
                    </button>
                  );
                })}
              </div>
              {errors.subjects && <div className="field-error" style={{ marginTop: 12 }}>{errors.subjects}</div>}
              <div style={{ marginTop: 16, fontSize: 12, color: 'var(--ink-3)', fontFamily: 'Geist Mono', letterSpacing: '0.04em' }}>
                {data.subjects.length} SELECTED · {data.subjects.filter(id => SUBJECTS.find(s => s.id === id)?.world).length} IN A LIVE WORLD
              </div>
            </div>
          )}

          {step === 4 && (
            <div>
              <h2>Contact information.</h2>
              <p className="sub">Where should we send the decision? We never share this — see the rail on the right.</p>
              <div className="field-group">
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                  <div className="field">
                    <label className="field-label">First name <span className="req">*</span></label>
                    <input
                      className={`field-input ${errors.firstName ? 'err' : ''}`}
                      value={data.firstName}
                      onChange={(e) => update('firstName', e.target.value)}
                    />
                    {errors.firstName && <div className="field-error">{errors.firstName}</div>}
                  </div>
                  <div className="field">
                    <label className="field-label">Last name <span className="req">*</span></label>
                    <input
                      className={`field-input ${errors.lastName ? 'err' : ''}`}
                      value={data.lastName}
                      onChange={(e) => update('lastName', e.target.value)}
                    />
                    {errors.lastName && <div className="field-error">{errors.lastName}</div>}
                  </div>
                </div>
                <div className="field">
                  <label className="field-label">Email <span className="req">*</span></label>
                  <input
                    type="email"
                    className={`field-input ${errors.email ? 'err' : ''}`}
                    placeholder="you@thevr.school"
                    value={data.email}
                    onChange={(e) => update('email', e.target.value)}
                  />
                  {errors.email && <div className="field-error">{errors.email}</div>}
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                  <div className="field">
                    <label className="field-label">Phone (optional)</label>
                    <input
                      className="field-input"
                      placeholder="+1 (650) 555-0100"
                      value={data.phone}
                      onChange={(e) => update('phone', e.target.value)}
                    />
                  </div>
                  <div className="field">
                    <label className="field-label">Country <span className="req">*</span></label>
                    <input
                      className={`field-input ${errors.country ? 'err' : ''}`}
                      placeholder="United States"
                      value={data.country}
                      onChange={(e) => update('country', e.target.value)}
                    />
                    {errors.country && <div className="field-error">{errors.country}</div>}
                  </div>
                </div>
              </div>
            </div>
          )}

          {step === 5 && (
            <div>
              <h2>Review and submit.</h2>
              <p className="sub">Double-check. You'll get a confirmation email immediately, and a decision within 5–7 business days.</p>
              <div style={{ marginTop: 24 }}>
                <div className="review-row"><span className="lbl">Role</span><span className="val">{({student:'Student',parent:'Parent / Guardian',school:'School / District',partner:'Partner'})[data.role] || '—'}</span></div>
                <div className="review-row"><span className="lbl">Grade 2026–27</span><span className="val">{data.grade ? `Grade ${data.grade}` : '—'}</span></div>
                <div className="review-row"><span className="lbl">Current school</span><span className="val">{data.currentSchool || '—'}</span></div>
                <div className="review-row"><span className="lbl">Subjects</span><span className="val">{data.subjects.map(id => SUBJECTS.find(s => s.id === id)?.name).join(' · ') || '—'}</span></div>
                <div className="review-row"><span className="lbl">Name</span><span className="val">{data.firstName} {data.lastName}</span></div>
                <div className="review-row"><span className="lbl">Email</span><span className="val">{data.email || '—'}</span></div>
                <div className="review-row"><span className="lbl">Country</span><span className="val">{data.country || '—'}</span></div>
                {data.notes && <div className="review-row"><span className="lbl">Notes</span><span className="val" style={{ maxWidth: 360, textAlign: 'right' }}>{data.notes}</span></div>}
              </div>
              <div style={{ marginTop: 32, padding: 16, background: 'rgba(125,255,196,0.04)', border: '1px solid rgba(125,255,196,0.2)', borderRadius: 8, fontSize: 13, color: 'var(--ink-1)', display: 'flex', gap: 12 }}>
                <Icon name="check" size={16} style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 2 }}/>
                <span>By submitting, you authorize The VR School to contact your current school to request transcripts on your behalf. No fee.</span>
              </div>
            </div>
          )}

          <div className="enroll-nav">
            <button className="btn btn-secondary" onClick={() => step > 1 && setStep(step - 1)} disabled={step === 1} style={{ opacity: step === 1 ? 0.4 : 1, cursor: step === 1 ? 'not-allowed' : 'pointer' }}>
              ← Back
            </button>
            {step < 5 ? (
              <button className="btn btn-primary" onClick={next}>
                Continue <Icon name="arrowRight" size={14}/>
              </button>
            ) : (
              <button className="btn btn-primary btn-lg" onClick={submit}>
                Submit application <Icon name="arrowRight" size={16}/>
              </button>
            )}
          </div>
        </>
        )}
      </main>

      <WhatsNext step={step} data={data} complete={complete}/>
    </div>
  );
};

const EnrollPage = () => (
  <div className="enroll-page">
    <Nav current="enroll"/>
    <div className="container">
      <EnrollForm/>
    </div>
    <Footer/>
  </div>
);

ReactDOM.createRoot(document.getElementById('root')).render(<EnrollPage/>);
