// become-instructor.jsx — Full-page instructor signup form
// Creates auth.users + profiles (role=instructor) + instructors row in one go.

const BecomeInstructorPage = ({ setPage }) => {
  const data = window.useSiteData();
  const { categories } = data;
  const auth = window.useAuth();
  const isMobile = window.useIsMobile();

  const [email, setEmail]       = React.useState('');
  const [password, setPassword] = React.useState('');
  const [fullName, setFullName] = React.useState(auth.profile?.full_name || '');
  const [city, setCity]         = React.useState(auth.profile?.city || '');
  const [state, setState]       = React.useState(auth.profile?.state || '');
  const [category, setCategory] = React.useState('music');
  const [subject, setSubject]   = React.useState('Piano');
  // v19: multi-topic. Defaults to the legacy `subject` so existing form
  // state migrates cleanly.
  const [topicsSel, setTopicsSel] = React.useState(['Piano']);
  const [specialtiesStr, setSpecialtiesStr] = React.useState('');
  const [bio, setBio]           = React.useState('');
  const [rate, setRate]         = React.useState(75);
  const [experience, setExperience] = React.useState(5);

  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [success, setSuccess] = React.useState(null);
  // Captcha only matters on the new-account path (auth.user is null). For
  // an already-logged-in user clicking "become an instructor", they
  // already passed captcha at signup — skip it.
  const captcha = (window.useCaptcha && !auth.user) ? window.useCaptcha() : { token: null, widget: null, required: false };

  const subjects = (categories.find(c => c.id === category)?.subjects) || [];
  React.useEffect(() => {
    if (!subjects.includes(subject) && subjects.length) setSubject(subjects[0]);
  }, [category]);

  const submit = async (e) => {
    e.preventDefault();
    setError(null); setSuccess(null);
    if (!city || !state) { setError('Please add your city and state.'); return; }
    if (state.length !== 2) { setError('State must be a 2-letter abbreviation (e.g. NY).'); return; }
    if (!bio.trim() || bio.length < 40) { setError('Please write a bio (40 characters minimum).'); return; }
    if (!rate || rate < 10) { setError('Please set a rate of $10/hr or more.'); return; }

    const specialties = specialtiesStr
      .split(',').map(s => s.trim()).filter(Boolean).slice(0, 5);

    setBusy(true);
    try {
      if (auth.user) {
        // Already logged in — just promote them to instructor
        const initials = (fullName.match(/\b\w/g) || []).slice(0, 2).join('').toUpperCase();
        const hue = Math.floor(Math.random() * 360);
        // Update profile to instructor role
        await window.supa.from('profiles').upsert({
          id: auth.user.id, role: 'instructor', full_name: fullName,
          avatar_initials: initials, hue, city, state: state.toUpperCase(),
        });
        const { error: insErr } = await window.supa.from('instructors').upsert({
          id: auth.user.id, user_id: auth.user.id, full_name: fullName,
          avatar_initials: initials, hue, subject, topics: topicsSel, category,
          specialties, city, state: state.toUpperCase(),
          bio, rate: Number(rate), experience: Number(experience),
          badges: [], available: true, is_sample: false,
        });
        if (insErr) { setError(insErr.message); return; }
        await window.supa.auth.refreshSession();
        await window.SITE_DATA.refresh();
        setSuccess('Welcome aboard! Your instructor profile is live.');
        setTimeout(() => setPage('dashboard'), 1200);
      } else {
        if (!email || !password) { setError('Please enter email and password.'); return; }
        if (captcha.required) { setError('Please complete the captcha.'); return; }
        const { error } = await window.AUTH.signUpInstructor({
          email, password, fullName, city, state: state.toUpperCase(),
          subject, topics: topicsSel, category, specialties, bio,
          rate: Number(rate), experience: Number(experience), badges: [],
          captchaToken: captcha.token,
        });
        captcha.reset && captcha.reset();
        if (error) { setError(error.message); return; }
        await window.SITE_DATA.refresh();
        // Supabase signUp has already emailed a confirm/login link — same
        // behavior as the admin-create flow (see MagicLinkPostCreate). The
        // user just clicks the email link to land on their dashboard, no
        // separate "send magic link" step.
        setSuccess('Account created! We just sent a login link to ' + email + ' — click it to access your dashboard.');
        setTimeout(() => setPage('home'), 2800);
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ background: 'oklch(98% 0.008 60)', minHeight: '100vh', paddingTop: isMobile ? 60 : 100, position:'relative' }}>
      {/* X close at top-right — Joe asked for this instead of needing to use
          the NavBar's home link to escape. */}
      <button onClick={() => setPage('home')} aria-label="Close" title="Back to home"
        style={{ position:'fixed', top:18, right:18, width:42, height:42, borderRadius:'50%', background:'rgba(255,255,255,0.92)', border:'1px solid oklch(88% 0.02 265)', cursor:'pointer', fontSize:20, lineHeight:1, color:'oklch(28% 0.05 265)', fontFamily:"'Plus Jakarta Sans', sans-serif", display:'flex', alignItems:'center', justifyContent:'center', zIndex:100, boxShadow:'0 2px 10px rgba(0,0,0,0.08)' }}>
        ×
      </button>
      {/* Hero */}
      <section style={{
        background: 'oklch(20% 0.065 265)',
        padding: isMobile ? '40px 18px 60px' : '60px 80px 80px',
        color: '#fff',
        marginTop: isMobile ? -60 : -100,
        paddingTop: isMobile ? 100 : 160,
      }}>
        <div style={{ maxWidth: 900, margin: '0 auto', textAlign: 'center' }}>
          <p style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.14em', color: 'oklch(72% 0.17 80)', textTransform: 'uppercase', marginBottom: 14 }}>For Instructors</p>
          <h1 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: isMobile ? 'clamp(28px, 9vw, 40px)' : 'clamp(38px, 5vw, 60px)', fontWeight: 600, lineHeight: 1.05, marginBottom: 16 }}>
            Teach what you love.{isMobile ? ' ' : <br />}Reach students nationwide.
          </h1>
          <p style={{ fontSize: isMobile ? 15 : 17, color: 'rgba(255,255,255,0.7)', lineHeight: 1.6, maxWidth: 640, margin: '0 auto' }}>
            Set your own schedule, your own rate, and connect with students who genuinely want to learn from you. No platform fee for v1 — every dollar a student pays goes to you.
          </p>
          <div style={{ marginTop: 18, fontSize: 14, color: 'rgba(255,255,255,0.6)' }}>
            Already an instructor?{' '}
            <button onClick={() => setPage('instructor-portal')} style={{ background:'none', border:'none', color:'oklch(72% 0.17 80)', cursor:'pointer', fontSize:14, fontWeight:600, textDecoration:'underline', fontFamily:"'Plus Jakarta Sans', sans-serif", padding:0 }}>
              Log in →
            </button>
          </div>
        </div>
      </section>

      {/* Form */}
      <section style={{
        maxWidth: 720,
        margin: isMobile ? '-30px 16px 60px' : '-40px auto 80px',
        background: '#fff', borderRadius: 18,
        padding: isMobile ? 22 : 40,
        boxShadow: '0 12px 48px rgba(0,0,0,0.08)',
        position: 'relative',
      }}>
        <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 28, fontWeight: 600, color: 'oklch(22% 0.06 265)', marginBottom: 6 }}>
          {auth.user ? 'Create your instructor profile' : 'Apply to teach'}
        </h2>
        <p style={{ fontSize: 14, color: 'oklch(50% 0.03 265)', marginBottom: 28 }}>
          Takes about 3 minutes. You can edit anything later from your dashboard.
        </p>

        <form onSubmit={submit}>
          {!auth.user && (
            <Section title="Account">
              <Row>
                <FieldI label="Email">
                  <input type="email" required value={email} onChange={e => setEmail(e.target.value)} style={inputI} placeholder="you@example.com" />
                </FieldI>
                <FieldI label="Password">
                  <input type="password" required minLength={6} value={password} onChange={e => setPassword(e.target.value)} style={inputI} placeholder="6+ characters" />
                </FieldI>
              </Row>
            </Section>
          )}

          <Section title="About you">
            <FieldI label="Full name">
              <input type="text" required value={fullName} onChange={e => setFullName(e.target.value)} style={inputI} placeholder="Jane Doe" />
            </FieldI>
            <Row>
              <FieldI label="City">
                <input type="text" required value={city} onChange={e => setCity(e.target.value)} style={inputI} placeholder="Austin" />
              </FieldI>
              <FieldI label="State (2-letter)">
                <input type="text" required value={state} onChange={e => setState(e.target.value.toUpperCase())} style={inputI} placeholder="TX" maxLength={2} />
              </FieldI>
            </Row>
          </Section>

          <Section title="What you teach">
            <Row>
              <FieldI label="Category">
                <select value={category} onChange={e => setCategory(e.target.value)} style={inputI}>
                  {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </FieldI>
              <FieldI label="Topics (pick all you teach)">
                <div style={{ display:'flex', flexWrap:'wrap', gap:6, padding:10, border:'1.5px solid oklch(88% 0.02 265)', borderRadius:8, background:'oklch(99% 0.003 60)', maxHeight:140, overflowY:'auto' }}>
                  {subjects.map(s => {
                    const on = topicsSel.includes(s);
                    return (
                      <button key={s} type="button"
                        onClick={() => {
                          const next = on ? topicsSel.filter(x=>x!==s) : [...topicsSel, s];
                          setTopicsSel(next);
                          if (next.length) setSubject(next[0]);
                        }}
                        style={{ padding:'5px 11px', borderRadius:14, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif",
                          background: on ? 'oklch(22% 0.06 265)' : '#fff',
                          color: on ? '#fff' : 'oklch(40% 0.04 265)',
                          border: on ? '1.5px solid oklch(22% 0.06 265)' : '1.5px solid oklch(88% 0.02 265)' }}>
                        {on ? '✓ ' : ''}{s}
                      </button>
                    );
                  })}
                </div>
              </FieldI>
            </Row>
            <FieldI label="Specialties (comma-separated, up to 5)">
              <input type="text" value={specialtiesStr} onChange={e => setSpecialtiesStr(e.target.value)} style={inputI}
                placeholder="Classical, Jazz, Beginner-Friendly" />
            </FieldI>
            <FieldI label="Short bio">
              <textarea required value={bio} onChange={e => setBio(e.target.value)}
                style={{ ...inputI, minHeight: 110, resize: 'vertical', lineHeight: 1.55 }}
                placeholder="Tell students about your background, teaching style, and what makes you a great instructor (40+ characters)" />
            </FieldI>
          </Section>

          <Section title="Pricing & experience">
            <Row>
              <FieldI label="Rate (USD per hour)">
                <input type="number" required min={10} max={500} value={rate} onChange={e => setRate(e.target.value)} style={inputI} />
              </FieldI>
              <FieldI label="Years of experience">
                <input type="number" required min={0} max={60} value={experience} onChange={e => setExperience(e.target.value)} style={inputI} />
              </FieldI>
            </Row>
          </Section>

          {captcha.widget}

          {error && <div style={errorBoxI}>{error}</div>}
          {success && <div style={successBoxI}>{success}</div>}

          <button type="submit" disabled={busy || captcha.required} style={{
            width: '100%', background: 'oklch(22% 0.06 265)', color: '#fff',
            border: 'none', borderRadius: 12, padding: '15px 0',
            fontWeight: 700, fontSize: 15, cursor: busy ? 'wait' : 'pointer',
            fontFamily: "'Plus Jakarta Sans', sans-serif",
            opacity: busy ? 0.7 : 1, marginTop: 10,
          }}>
            {busy ? 'Submitting…' : auth.user ? 'Create instructor profile' : 'Apply to teach'}
          </button>
        </form>
      </section>
    </div>
  );
};

const Section = ({ title, children }) => (
  <div style={{ marginBottom: 22, borderBottom: '1px solid oklch(94% 0.01 265)', paddingBottom: 18 }}>
    <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.06em', color: 'oklch(38% 0.06 265)', textTransform: 'uppercase', marginBottom: 14 }}>{title}</div>
    {children}
  </div>
);
const Row = ({ children }) => {
  const isMobile = window.useIsMobile();
  return <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 12 }}>{children}</div>;
};
const FieldI = ({ label, children }) => (
  <div style={{ marginBottom: 12 }}>
    <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'oklch(38% 0.04 265)', marginBottom: 6 }}>{label}</label>
    {children}
  </div>
);
const inputI = {
  width: '100%', padding: '12px 14px',
  border: '1.5px solid oklch(88% 0.01 265)', borderRadius: 10,
  fontSize: 16, fontFamily: "'Plus Jakarta Sans', sans-serif",
  outline: 'none', background: '#fff', minHeight: 44,
};
const errorBoxI = {
  background: 'oklch(96% 0.03 25)', color: 'oklch(40% 0.15 25)',
  padding: '10px 14px', borderRadius: 8, fontSize: 13, marginBottom: 12,
  border: '1px solid oklch(88% 0.06 25)',
};
const successBoxI = {
  background: 'oklch(96% 0.04 158)', color: 'oklch(32% 0.1 155)',
  padding: '10px 14px', borderRadius: 8, fontSize: 13, marginBottom: 12,
  border: '1px solid oklch(88% 0.06 155)',
};

window.BecomeInstructorPage = BecomeInstructorPage;
