const { useState: useState_ap } = React;
const { Link: Link_ap, useParams: useParams_ap } = ReactRouterDOM;

function Apply() {
  const { slug } = useParams_ap();
  const job = slug ? window.getJob(slug) : null;

  useSEO({
    title: job ? `Apply — ${job.title} | Cyrion AI` : 'Apply | Cyrion AI Careers',
    description: 'Apply to join the Cyrion AI team.',
    path: slug ? `/careers/${slug}/apply` : '/apply',
  });

  const [form, setForm] = useState_ap({ name: '', email: '', phone: '', role: job ? job.title : '', linkedin: '', resumeUrl: '', message: '' });
  const [status, setStatus] = useState_ap('idle');
  const [msg, setMsg] = useState_ap('');

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim() || !form.role.trim()) {
      setStatus('error'); setMsg('Name, email, and role are required.'); return;
    }
    setStatus('loading'); setMsg('');
    try {
      const res = await fetch('/api/apply', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setStatus('error'); setMsg(data.error || 'Something went wrong'); return; }
      setStatus('success'); setMsg("Application received. We'll follow up within a week.");
    } catch (err) { setStatus('error'); setMsg('Network error. Please try again.'); }
  };

  const sent = status === 'success';

  return (
    <div data-screen-label="apply">
      <section className="page-hero" style={{ paddingBottom: 40 }}>
        <div className="page">
          <div className="breadcrumb" style={{ marginBottom: 20 }}>
            <Link_ap to="/">Home</Link_ap><span>/</span><Link_ap to="/careers">Careers</Link_ap>
            {job && <><span>/</span><Link_ap to={`/careers/${job.slug}`}>{job.title}</Link_ap></>}
            <span>/</span><span className="ink">Apply</span>
          </div>
          <div className="eyebrow" style={{ marginBottom: 18 }}><span className="dot" />{job ? job.title : 'General application'}</div>
          <h1 className="h1" style={{ maxWidth: 760 }}>{job ? 'Apply for this role.' : "Don't see your role? Tell us anyway."}</h1>
          <p className="body-lg" style={{ maxWidth: 620, marginTop: 22 }}>{job ? job.summary : "We're always open to meeting strong offensive-security, infrastructure, and go-to-market people. Tell us what you'd want to work on."}</p>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 40 }}>
        <div className="page" style={{ maxWidth: 640 }}>
          <form className="card" style={{ padding: 28, position: 'relative' }} onSubmit={handleSubmit}>
            <span className="ticks"><i /><b /></span>
            <div className="bracket" style={{ marginBottom: 14 }}>APPLICATION · SECURE INTAKE</div>

            <div className="field-row">
              <Field label="Full name *" placeholder="Jane Doe" value={form.name} onChange={update('name')} />
              <Field label="Email *" placeholder="jane@email.com" type="email" value={form.email} onChange={update('email')} />
            </div>
            <div className="field-row">
              <Field label="Phone" placeholder="+1 555 000 0000" value={form.phone} onChange={update('phone')} />
              <Field label="LinkedIn / portfolio" placeholder="https://linkedin.com/in/you" value={form.linkedin} onChange={update('linkedin')} />
            </div>
            {!job && <Field label="Role you're interested in *" placeholder="e.g. Offensive Research, Infra, Sales" value={form.role} onChange={update('role')} />}
            {job && (
              <div className="field-label"><span className="caption" style={{ display: 'block', marginBottom: 8 }}>Applying for</span><div className="field-input" style={{ color: 'var(--ink)' }}>{job.title}</div></div>
            )}
            <Field label="Resume / CV link" placeholder="Google Drive, Dropbox, or personal site URL" value={form.resumeUrl} onChange={update('resumeUrl')} />
            <Field label="Anything else we should know?" placeholder="A note, a project you're proud of, why this role" as="textarea" value={form.message} onChange={update('message')} />

            <button type="submit" className="btn btn-primary" disabled={status === 'loading' || sent} style={{ width: '100%', justifyContent: 'center', marginTop: 12 }}>
              {status === 'loading' ? 'Sending…' : sent ? '✓ Application sent' : 'Submit application →'}
            </button>
            {msg && <div style={{ marginTop: 12, fontSize: 11.5, textAlign: 'center', color: status === 'error' ? 'var(--red)' : 'var(--green)' }}>{msg}</div>}
            <div className="dim" style={{ marginTop: 12, fontSize: 11, textAlign: 'center' }}>We respond to every application, usually within a week.</div>
          </form>

          {!job && (
            <div style={{ marginTop: 32 }}>
              <div className="caption" style={{ marginBottom: 14 }}>Or apply directly to an open role</div>
              <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
                {window.JOBS.map((j) => <Link_ap key={j.slug} to={`/careers/${j.slug}`} className="tag-chip" style={{ color: 'var(--ink-mute)' }}>{j.title}</Link_ap>)}
              </div>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { Apply });
