// DEMIURGE — OPERATORS WANTED (/operators)
// Real expression-of-interest form → /api/contact (intent: operator).
// No invented vacancies/salaries/offices. Openings render from OPENINGS
// (empty = honest "no listed openings, general interest welcome").
const OPENINGS = []; // { slug, title, focus, blurb } — add real roles here.

const FOCUS = [
  ['Deployment operator', 'You own live operator stacks end-to-end: configure, tune, monitor, and keep them delivering in production.'],
  ['Engineer', 'You build the systems and integrations behind the operators — reliability, tooling, and clean deployment.'],
  ['Researcher', 'You design and evaluate operator behaviours, guardrails, and human-oversight patterns.'],
  ['Designer', 'You make consoles and interfaces that make autonomous systems legible and controllable.'],
  ['Domain expert', 'You bring deep industry knowledge (trades, medical, legal, real estate…) that tunes operators to real workflows.']
];

const EOIForm = () => {
  const [form, setForm] = React.useState({ name: '', email: '', role: '', message: '', links: '', consent: false, website: '' });
  const [errors, setErrors] = React.useState({});
  const [phase, setPhase] = React.useState('idle');
  const [serverError, setServerError] = React.useState(null);
  const up = (k) => (e) => {
    const v = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm(f => ({ ...f, [k]: v }));
    if (errors[k]) setErrors(er => { const n = { ...er }; delete n[k]; return n; });
  };
  const submit = async (e) => {
    e.preventDefault();
    if (phase === 'submitting') return;
    const er = {};
    if (!form.name.trim()) er.name = 'Your name is required.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) er.email = 'A valid email is required.';
    if (!form.message.trim()) er.message = 'Tell us a little about you.';
    if (!form.consent) er.consent = 'Please acknowledge the applicant privacy notice.';
    setErrors(er);
    if (Object.keys(er).length) { const f = document.getElementById('o-' + Object.keys(er)[0]); if (f) f.focus(); return; }
    setPhase('submitting'); setServerError(null);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name, email: form.email, role: form.role,
          intent: 'operator', source: 'operators',
          message: `Focus: ${form.role || '—'}\nLinks: ${form.links || '—'}\n\n${form.message}`,
          consent: form.consent, website: form.website
        })
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) { setServerError(data.error || `Could not submit (HTTP ${res.status}). Your details are preserved.`); setPhase('error'); return; }
      setPhase('success');
    } catch { setServerError('Network error — your details are preserved. Please try again.'); setPhase('error'); }
  };

  const fieldStyle = (bad) => ({
    background: 'rgba(3,4,12,0.6)', border: `1px solid ${bad ? 'rgba(255,95,95,0.55)' : 'rgba(255,255,255,0.1)'}`,
    borderRadius: 3, color: '#f5f1e6', fontFamily: 'Geist, system-ui, sans-serif', fontSize: 14,
    padding: '11px 14px', outline: 'none', width: '100%', boxSizing: 'border-box'
  });
  const lab = { fontFamily: 'Geist Mono', fontSize: 10, color: '#8388a8', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 6, display: 'block' };
  const err = { color: '#ff8b8b', fontSize: 11.5, fontFamily: 'Geist Mono' };

  if (phase === 'success') {
    return (
      <div className="lp-ind-panel" style={{padding: '48px 32px', textAlign: 'center'}} role="status" aria-live="polite">
        <div className="corner tl"></div><div className="corner tr"></div><div className="corner bl"></div><div className="corner br"></div>
        <div style={{width: 56, height: 56, margin: '0 auto 18px', borderRadius: '50%', background: 'radial-gradient(circle at 35% 35%, #fff, #5dffb0 50%, #1a5c3a 100%)', boxShadow: '0 0 32px rgba(93,255,176,0.4)'}}/>
        <h3 style={{fontFamily: 'Instrument Serif', fontStyle: 'italic', fontWeight: 400, color: '#f5f1e6', fontSize: 26, margin: '0 0 10px'}}>Application received.</h3>
        <p style={{color: '#8388a8', fontSize: 14, maxWidth: 400, margin: '0 auto', lineHeight: 1.6}}>
          Thanks{form.name ? `, ${form.name.split(/\s+/)[0]}` : ''}. We review every expression of interest and will be in touch if there’s a fit.
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={submit} noValidate className="lp-ind-panel" style={{padding: '32px', display: 'flex', flexDirection: 'column', gap: 14}}>
      <div className="corner tl"></div><div className="corner tr"></div><div className="corner bl"></div><div className="corner br"></div>
      <div aria-hidden="true" style={{position: 'absolute', left: '-9999px', width: 1, height: 1, overflow: 'hidden'}}>
        <label>Company URL<input tabIndex={-1} autoComplete="off" value={form.website} onChange={up('website')}/></label>
      </div>
      <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14}} className="cf-row2">
        <div><label htmlFor="o-name" style={lab}>Name *</label><input id="o-name" style={fieldStyle(errors.name)} value={form.name} onChange={up('name')} autoComplete="name" aria-invalid={!!errors.name}/>{errors.name && <div style={err}>{errors.name}</div>}</div>
        <div><label htmlFor="o-email" style={lab}>Email *</label><input id="o-email" type="email" style={fieldStyle(errors.email)} value={form.email} onChange={up('email')} autoComplete="email" aria-invalid={!!errors.email}/>{errors.email && <div style={err}>{errors.email}</div>}</div>
      </div>
      <div><label htmlFor="o-role" style={lab}>Focus area</label>
        <select id="o-role" style={fieldStyle(false)} value={form.role} onChange={up('role')}>
          <option value="">Select</option>
          {FOCUS.map(([t]) => <option key={t} value={t}>{t}</option>)}
          <option value="Other">Other</option>
        </select>
      </div>
      <div><label htmlFor="o-links" style={lab}>Links (portfolio / GitHub / LinkedIn)</label><input id="o-links" style={fieldStyle(false)} value={form.links} onChange={up('links')} placeholder="https://…"/></div>
      <div><label htmlFor="o-message" style={lab}>About you *</label><textarea id="o-message" rows={4} style={{...fieldStyle(errors.message), resize: 'vertical'}} value={form.message} onChange={up('message')} placeholder="What you build, what you want to work on, and why operator systems." aria-invalid={!!errors.message}/>{errors.message && <div style={err}>{errors.message}</div>}</div>
      <label htmlFor="o-consent" style={{display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 12.5, color: '#8388a8', lineHeight: 1.5}}>
        <input id="o-consent" type="checkbox" checked={form.consent} onChange={up('consent')} style={{marginTop: 3, accentColor: '#8b6bff'}} aria-invalid={!!errors.consent}/>
        <span>I agree that Demiurge Systems may store and use these details to assess my interest, per the applicant privacy notice below and the <a href="/legal/privacy" style={{color: '#4be8ff'}}>Privacy Policy</a>.</span>
      </label>
      {errors.consent && <div style={err}>{errors.consent}</div>}
      {phase === 'error' && serverError && <div style={{padding: '12px 14px', background: 'rgba(255,95,95,0.08)', border: '1px solid rgba(255,95,95,0.3)', borderRadius: 3, color: '#ff8b8b', fontSize: 13, fontFamily: 'Geist Mono'}} role="alert">{serverError}</div>}
      <button type="submit" className="lp-btn primary lg" disabled={phase === 'submitting'} style={{justifyContent: 'center', opacity: phase === 'submitting' ? 0.6 : 1}}>
        {phase === 'submitting' ? 'Sending…' : 'Express interest'}
      </button>
    </form>
  );
};

const Operators = () => (
  <React.Fragment>
    <a href="#main" className="lp-skip">Skip to content</a>
    <div className="lp-starfield" aria-hidden="true"></div>
    <div className="lp-vignette" aria-hidden="true"></div>
    <SiteNav/>
    <main id="main" className="page-wrap">
      <section className="page-hero">
        <div className="lp">
          <div className="lp-eyebrow">/ Operators wanted</div>
          <h1 className="page-h1">Build systems that <em className="lp-brass">do the work</em>.</h1>
          <p className="page-lede">
            We are a small team that deploys autonomous operators into real businesses. We work with people who
            care about systems that actually run — and about the human oversight that keeps them accountable.
          </p>
        </div>
      </section>
      <section className="page-body">
        <div className="lp">
          <div className="prose" style={{maxWidth: 820}}>
            <h2>What an “operator” means here</h2>
            <p>Two things. First, our product: a narrow, accountable digital worker that carries a defined operational job. Second, the people who deploy and steward them — that could be you. Both live by the same rule: real work, with a human holding the wheel.</p>
            <h2>Who we’re looking for</h2>
            <ul>{FOCUS.map(([t, d]) => <li key={t}><strong>{t}.</strong> {d}</li>)}</ul>
            <h2>Working principles</h2>
            <ul>
              <li>Ship production-capable, not demo-shaped.</li>
              <li>Bound autonomy; make the off-switch first.</li>
              <li>Be honest about what works and what doesn’t — including in your own work.</li>
              <li>Small surface, high reliability, clear ownership.</li>
            </ul>
            <h2>Current openings</h2>
            {OPENINGS.length === 0 ? (
              <p>We don’t have named vacancies listed right now, but we always want to meet strong operators, engineers, researchers, designers, and domain experts. Express your interest below and we’ll reach out when there’s a fit.</p>
            ) : (
              <ul>{OPENINGS.map(o => <li key={o.slug}><strong>{o.title}</strong> — {o.blurb}</li>)}</ul>
            )}
          </div>

          <div style={{display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,0.85fr)', gap: 32, marginTop: 40, alignItems: 'start'}} className="lp-contact-grid">
            <EOIForm/>
            <div className="prose">
              <h3>Applicant privacy notice</h3>
              <p>Details you submit here are used only to assess your interest in working with Demiurge Systems. They are stored in our contact/CRM system and shared internally with the people involved in that assessment. We keep application data for a reasonable period and then delete it; you can ask us to delete it sooner.</p>
              <p>Your full rights, and the processors we use, are described in the <a href="/legal/privacy">Privacy Policy</a>. Questions: <a href="mailto:ops@demiurge.systems">ops@demiurge.systems</a>.</p>
            </div>
          </div>
        </div>
      </section>
    </main>
    <SiteFooter/>
  </React.Fragment>
);

if (typeof document !== 'undefined' && !document.getElementById('op-styles')) {
  const s = document.createElement('style'); s.id = 'op-styles';
  s.textContent = `@media (max-width:880px){.cf-row2{grid-template-columns:1fr !important}}`;
  document.head.appendChild(s);
}
ReactDOM.createRoot(document.getElementById('root')).render(<Operators/>);
