// ── Partnership / Contact page ──────────────────────────────────────────

const PARTNERSHIP_TYPES = [
  'University / Research Institute',
  'Industry',
  'Government / Public Sector',
  'Nonprofit',
  'Other',
];

function ContactPage() {
  const [form, setForm] = React.useState({ name: '', email: '', organization: '', type: '', message: '' });
  const [status, setStatus] = React.useState('idle'); // idle | loading | success | error
  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/contact', {
        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: '-100px', left: '10%', width: 560, height: 400, background: 'radial-gradient(circle, rgba(91,134,255,0.22), transparent 68%)', animation: 'drift-a 16s ease-in-out infinite' }}></div>
      <div className="aurora" style={{ bottom: '0', right: '5%', width: 480, height: 380, background: 'radial-gradient(circle, rgba(164,118,255,0.16), transparent 68%)', animation: 'drift-b 20s 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">Partnership</span></Eyebrow>
          <h1 className="font-display font-semibold tracking-[-0.025em] text-[clamp(2.2rem,4vw,3.2rem)] mt-6 leading-tight">
            Build the Science of Intelligence{' '}
            <span className="grad-text">With Us</span>
          </h1>
          <p className="mt-6 text-[1.08rem] text-muted leading-relaxed max-w-xl mx-auto">
            We partner with universities, research institutes, and industry teams committed
            to rigorous and open inquiry. Tell us about your work and how you'd like to collaborate.
          </p>
        </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">Inquiry received</h2>
            <p className="text-muted text-[1rem] leading-relaxed max-w-sm mx-auto">
              We'll be in touch within a few business days. 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="Organization" required>
                <input type="text" value={form.organization} onChange={set('organization')} placeholder="MIT, DeepMind, etc." required className="form-input" />
              </FormField>
              <FormField label="Organization type">
                <select value={form.type} onChange={set('type')} className="form-input">
                  <option value="">Select type</option>
                  {PARTNERSHIP_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
                </select>
              </FormField>
            </div>
            <FormField label="How would you like to collaborate?" required>
              <textarea value={form.message} onChange={set('message')} placeholder="Describe your research interests, what you're working on, and the kind of collaboration you have in mind." required rows={5} maxLength={2000} className="form-input resize-none" />
              <div className="text-right mt-1.5 font-mono text-[11px] text-faint">{form.message.length}/2000</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' ? (
                <><Spinner /> Sending…</>
              ) : (
                <>Send Inquiry <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 Spinner() {
  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 ContactApp() {
  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 />
        <ContactPage />
        <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}`;
document.head.appendChild(_formStyle);

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