// ── Fellowship Application page ─────────────────────────────────────────

const FELLOWSHIP_AREAS = [
  'Interpretability & Explainability',
  'Alignment & Safety',
  'Autonomous Agents',
  'Multimodal & Scientific ML',
  'Cognitive Foundations',
  'Human–AI Collaboration',
];

const FELLOWSHIP_TYPES = [
  { id: 'doctoral', label: 'Doctoral Fellowship', desc: 'For PhD students in residence at a partner institution.' },
  { id: 'postdoc', label: 'Postdoctoral Fellowship', desc: 'For researchers with a PhD, joining for 1–2 years.' },
  { id: 'visiting', label: 'Visiting Scholarship', desc: 'For established researchers on sabbatical or leave.' },
];

function FellowshipPage() {
  const [form, setForm] = React.useState({
    name: '', email: '', affiliation: '', fellowship_type: '', area: '', cv_url: '', statement: '',
  });
  const [status, setStatus] = React.useState('idle');
  const [errorMsg, setErrorMsg] = React.useState('');

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('loading');
    setErrorMsg('');
    try {
      const res = await fetch('/api/fellowship', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Request failed');
      setStatus('success');
    } catch (err) {
      setErrorMsg(err.message);
      setStatus('error');
    }
  };

  return (
    <main className="relative min-h-screen pt-36 pb-24">
      <div className="absolute inset-0 grid-bg pointer-events-none opacity-50"></div>
      <div className="aurora" style={{ top: '-80px', right: '8%', width: 560, height: 440, background: 'radial-gradient(circle, rgba(164,118,255,0.22), transparent 68%)', animation: 'drift-b 18s ease-in-out infinite' }}></div>
      <div className="aurora" style={{ bottom: '5%', left: '5%', width: 480, height: 360, background: 'radial-gradient(circle, rgba(91,134,255,0.16), transparent 68%)', animation: 'drift-a 22s ease-in-out infinite' }}></div>

      <div className="relative max-w-2xl mx-auto px-6 lg:px-8">
        {/* Header */}
        <div className="reveal text-center mb-14">
          <Eyebrow><span className="mx-auto">Fellowships</span></Eyebrow>
          <h1 className="font-display font-semibold tracking-[-0.025em] text-[clamp(2.2rem,4vw,3.2rem)] mt-6 leading-tight">
            Join the Lab as a{' '}
            <span className="grad-text">Research Fellow</span>
          </h1>
          <p className="mt-6 text-[1.08rem] text-muted leading-relaxed max-w-xl mx-auto">
            We welcome doctoral fellows, postdoctoral researchers, and visiting scholars committed
            to careful, open, and consequential science at the intersection of disciplines.
          </p>
        </div>

        {/* Fellowship type cards */}
        <div className="reveal grid sm:grid-cols-3 gap-4 mb-10">
          {FELLOWSHIP_TYPES.map((ft) => (
            <button key={ft.id} type="button"
              onClick={() => setForm((f) => ({ ...f, fellowship_type: ft.id }))}
              className={`text-left p-5 rounded-xl transition-all duration-200 border ${
                form.fellowship_type === ft.id
                  ? 'border-ebl/60 bg-ebl/8'
                  : 'border-white/10 bg-white/[0.03] hover:bg-white/[0.05]'
              }`}>
              <div className={`font-display text-[0.92rem] font-medium mb-1.5 ${form.fellowship_type === ft.id ? 'text-soft' : 'text-muted'}`}>{ft.label}</div>
              <div className="text-[0.82rem] text-faint leading-snug">{ft.desc}</div>
            </button>
          ))}
        </div>

        {status === 'success' ? (
          <div className="reveal glass rounded-2xl p-12 text-center">
            <div className="w-14 h-14 rounded-full grid place-items-center mx-auto mb-6"
              style={{ background: 'rgba(91,134,255,0.12)', border: '1px solid rgba(91,134,255,0.3)' }}>
              <svg viewBox="0 0 24 24" width="26" height="26" fill="none" stroke="#5B86FF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6L9 17l-5-5" />
              </svg>
            </div>
            <h2 className="font-display text-[1.5rem] font-medium text-soft mb-3">Application received</h2>
            <p className="text-muted text-[1rem] leading-relaxed max-w-sm mx-auto">
              Our admissions committee reviews on a rolling basis. We'll be in touch. Check your inbox for a confirmation.
            </p>
          </div>
        ) : (
          <form className="reveal glass rounded-2xl p-8 lg:p-10 space-y-6" onSubmit={handleSubmit}>
            <div className="grid sm:grid-cols-2 gap-6">
              <FormField label="Full name" required>
                <input type="text" value={form.name} onChange={set('name')} placeholder="Dr. Jane Smith" required className="form-input" />
              </FormField>
              <FormField label="Email" required>
                <input type="email" value={form.email} onChange={set('email')} placeholder="jane@university.edu" required className="form-input" />
              </FormField>
            </div>
            <div className="grid sm:grid-cols-2 gap-6">
              <FormField label="Current affiliation" required>
                <input type="text" value={form.affiliation} onChange={set('affiliation')} placeholder="MIT, Stanford, etc." required className="form-input" />
              </FormField>
              <FormField label="Primary research area" required>
                <select value={form.area} onChange={set('area')} required className="form-input">
                  <option value="">Select area</option>
                  {FELLOWSHIP_AREAS.map((a) => <option key={a} value={a}>{a}</option>)}
                </select>
              </FormField>
            </div>
            <FormField label="CV / Portfolio URL">
              <input type="url" value={form.cv_url} onChange={set('cv_url')} placeholder="https://your-cv.pdf or personal site" className="form-input" />
            </FormField>
            <FormField label="Research statement" required>
              <textarea value={form.statement} onChange={set('statement')} required rows={7} maxLength={3000}
                placeholder="Describe your research background, what questions you want to pursue at CIRA Labs, and why this is the right environment for that work."
                className="form-input resize-none" />
              <div className="text-right mt-1.5 font-mono text-[11px] text-faint">{form.statement.length}/3000</div>
            </FormField>

            {status === 'error' && (
              <p className="text-[13px] text-red-400 bg-red-400/10 border border-red-400/20 rounded-lg px-4 py-3">{errorMsg}</p>
            )}

            <button type="submit" disabled={status === 'loading'}
              className="btn-primary rounded-full px-8 py-3.5 text-[15px] inline-flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
              {status === 'loading' ? (
                <><FellowshipSpinner /> Submitting…</>
              ) : (
                <>Submit Application <ArrowRight size={16} /></>
              )}
            </button>
          </form>
        )}
      </div>
    </main>
  );
}

function FormField({ label, required, children }) {
  return (
    <div>
      <label className="block font-mono text-[11px] tracking-[0.18em] uppercase text-faint mb-2.5">
        {label}{required && <span className="text-ebl ml-1">*</span>}
      </label>
      {children}
    </div>
  );
}

function FellowshipSpinner() {
  return (
    <svg className="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" strokeLinecap="round" />
    </svg>
  );
}

function FellowshipApp() {
  const neuralRef = React.useRef(null);
  React.useEffect(() => {
    neuralRef.current = initNeural();
    return () => neuralRef.current && neuralRef.current.destroy();
  }, []);
  React.useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.1 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
  return (
    <>
      <CustomCursor />
      <ScrollProgress />
      <div className="relative z-10">
        <Nav />
        <FellowshipPage />
        <Footer />
      </div>
    </>
  );
}

// Inject form-input style
const _formStyle = document.createElement('style');
_formStyle.textContent = `.form-input{width:100%;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.1);border-radius:10px;padding:11px 14px;color:#EAECF3;font-size:14px;font-family:inherit;outline:none;transition:border-color .2s}.form-input::placeholder{color:#5B6273}.form-input:focus{border-color:rgba(91,134,255,0.5);background:rgba(91,134,255,0.04)}select.form-input option{background:#0A0C12}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}`;
document.head.appendChild(_formStyle);

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