/* AXION — "Apply" page. Typeform-style conversational flow. Self-contained, earth theme. */
(function () {
  const C = {
    cream: 'var(--earth-cream)', linen: 'var(--earth-linen)',
    ink: 'var(--espresso)', umber: 'var(--umber-600)', faint: 'var(--umber-500)',
    clay: 'var(--clay-500)', forest: '#22301B', forestD: '#16210F', gold: '#9A7A24',
    line: 'rgba(244,236,216,0.16)', lineGold: 'rgba(217,184,90,0.5)',
  };
  const SERIF = 'var(--font-display)', BODY = 'var(--font-sans)', MONO = 'var(--font-mono)', PROSE = 'var(--font-serif)';
  const A = 'assets/';
  /* Applications are emailed via Formspree (same inbox as the job form). */
  const FORM_ENDPOINT = 'https://formspree.io/f/mojoezon';
  const { useState, useEffect, useRef } = React;

  function Icon({ name, size = 20, color = 'currentColor', sw = 1.7 }) {
    const P = {
      arrow: 'M5 12h14M13 6l6 6-6 6', down: 'M12 5v14M6 13l6 6 6-6', up: 'M12 19V5M6 11l6-6 6 6',
      check: 'M20 6L9 17l-5-5', ok: 'M20 6L9 17l-5-5',
    };
    return (<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={P[name] || P.arrow} /></svg>);
  }

  // ---- Question script ----
  const QUESTIONS = [
    { id: 'intro', type: 'statement', title: 'Build with AXION', body: 'AXION is a Civilizational Venture Studio \u2014 we ideate, validate, build, spin out, and scale ventures that become the infrastructure of future civilization. A few questions to understand what you\u2019re building. About 2 minutes.', cta: 'Begin' },
    { id: 'name', type: 'short', q: 'First, what\u2019s your name?', placeholder: 'Type your name here\u2026', required: true },
    { id: 'email', type: 'short', q: 'Where can we reach you?', sub: 'Your best email.', placeholder: 'name@domain.com', inputType: 'email', required: true },
    { id: 'pathway', type: 'choice', q: 'Which pathway brings you to AXION?', sub: 'Every venture enters through one of three gateways.', options: [
      ['A', 'Internal \u2014 I want to build a venture from within the studio'],
      ['B', 'Community \u2014 I represent a community, land, or place to build with'],
      ['C', 'External \u2014 I have an independent venture seeking AXION\u2019s architecture'],
      ['D', 'Capital \u2014 I\u2019m an aligned investor or institution'],
    ] },
    { id: 'ring', type: 'choice', q: 'Which Focus Area does your work serve?', sub: 'The ten domains of civilization AXION rebuilds.', options: [
      ['I', 'Human Health & Longevity'],
      ['II', 'Consciousness Development'],
      ['III', 'Education Systems'],
      ['IV', 'Economic Systems'],
      ['V', 'Infrastructure & Habitat'],
      ['VI', 'Agriculture & Food Systems'],
      ['VII', 'Energy Systems'],
      ['VIII', 'Governance Systems'],
      ['IX', 'Media & Cultural Systems'],
      ['X', 'Technology & Intelligence'],
    ] },
    { id: 'stage', type: 'choice', q: 'Where is it in the venture lifecycle?', sub: 'Ideation \u2192 Validation \u2192 Creation \u2192 Spin Out \u2192 Scale.', options: [
      ['A', 'Ideation \u2014 a vision or insight'],
      ['B', 'Validation \u2014 researching & testing it'],
      ['C', 'Creation \u2014 building the first version'],
      ['D', 'Scale \u2014 operating & ready to grow'],
    ] },
    { id: 'vision', type: 'long', q: 'What system are you building \u2014 and why does it matter for the future?', sub: 'AXION builds ventures that expand human sovereignty, regeneration, and coherence. Tell us how yours does.', placeholder: 'Share your vision\u2026', required: true },
    { id: 'contribution', type: 'choice', q: 'How do you most want to participate?', options: [
      ['A', 'As a founder / builder of a venture'],
      ['B', 'As a community or land partner'],
      ['C', 'As a researcher, steward, or contributor'],
      ['D', 'As aligned capital or a strategic partner'],
    ] },
    { id: 'link', type: 'short', q: 'Anything we should look at?', sub: 'A website, deck, or profile (optional).', placeholder: 'https:// \u2026', required: false },
    { id: 'done', type: 'end', title: 'Received into the field.', body: 'Thank you. AXION reviews every submission personally. Where there is alignment with the work of building future civilization, we\u2019ll reach out to begin the conversation.' },
  ];

  function ProgressBar({ pct }) {
    return (
      <div style={{ position: 'fixed', top: 0, left: 0, right: 0, height: 4, background: 'rgba(244,236,216,0.12)', zIndex: 30 }}>
        <div style={{ height: '100%', width: `${pct}%`, background: 'var(--grad-gold)', transition: 'width .4s var(--ease-out, cubic-bezier(0.16,1,0.3,1))' }} />
      </div>
    );
  }

  function Shell({ children, kicker }) {
    return (
      <div className="ap-step" style={{ width: '100%', maxWidth: 720, margin: '0 auto', padding: '0 32px' }}>
        {kicker && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
            <span style={{ fontFamily: MONO, fontSize: 12, fontWeight: 600, color: C.clay }}>{kicker}</span>
            <Icon name="arrow" size={15} color={C.clay} />
          </div>
        )}
        {children}
      </div>
    );
  }

  function OkButton({ onClick, label = 'OK', enabled = true }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 30 }}>
        <button onClick={enabled ? onClick : undefined} disabled={!enabled} style={{
          display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: BODY, fontSize: 15, fontWeight: 600,
          color: '#1a230f', background: enabled ? 'var(--grad-gold)' : 'rgba(217,184,90,0.3)',
          padding: '13px 26px', borderRadius: 8, border: 'none', cursor: enabled ? 'pointer' : 'not-allowed',
          opacity: enabled ? 1 : 0.6, transition: 'all .2s',
        }}>{label} <Icon name="check" size={16} color="#1a230f" /></button>
      </div>
    );
  }

  function App() {
    const [i, setI] = useState(0);
    const [ans, setAns] = useState({});
    const inputRef = useRef(null);
    const sentRef = useRef(false);
    const q = QUESTIONS[i];

    // Fire the submission once, when the flow reaches the "end" step.
    useEffect(() => {
      if (q.type !== 'end' || sentRef.current) return;
      sentRef.current = true;
      if (FORM_ENDPOINT.indexOf('YOUR_FORM_ID') !== -1) return; // demo mode
      const payload = { _subject: 'AXION — New Inquiry (Enter AXION flow)', Source: 'Enter AXION / Apply flow' };
      QUESTIONS.forEach((x) => {
        if (x.type === 'statement' || x.type === 'end') return;
        const label = (x.q || x.id).replace(/\s*\*?$/, '');
        payload[label] = ans[x.id] || '';
      });
      fetch(FORM_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      }).catch(function () { /* silent — user still sees confirmation */ });
    }, [i]);
    const answered = QUESTIONS.filter((x) => x.type !== 'statement' && x.type !== 'end').length;
    const answeredIdx = QUESTIONS.slice(0, i).filter((x) => x.type !== 'statement' && x.type !== 'end').length;
    const pct = Math.round((i / (QUESTIONS.length - 1)) * 100);

    useEffect(() => { if (inputRef.current) setTimeout(() => inputRef.current.focus(), 220); }, [i]);

    const val = ans[q.id] || '';
    const canAdvance = !q.required || (val && val.trim().length > 0);

    const next = () => { if (i < QUESTIONS.length - 1 && canAdvance) setI(i + 1); };
    const prev = () => { if (i > 0) setI(i - 1); };
    const set = (v) => setAns((a) => ({ ...a, [q.id]: v }));
    const choose = (label) => { setAns((a) => ({ ...a, [q.id]: label })); setTimeout(() => setI((n) => Math.min(n + 1, QUESTIONS.length - 1)), 260); };

    const onKey = (e) => {
      if (e.key === 'Enter' && !(q.type === 'long' && e.shiftKey)) { e.preventDefault(); next(); }
    };

    const num = (n) => String(n).padStart(2, '0');

    return (
      <div onKeyDown={onKey} style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', background: 'radial-gradient(125% 100% at 50% 0%, #243019 0%, #1a2412 45%, #11180c 100%)', color: '#F4ECD8', position: 'relative' }}>
        <ProgressBar pct={pct} />
        {/* faint centered logo backdrop */}
        <img src={A + 'axion-logo-mark.png'} alt="" aria-hidden="true" style={{ position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', width: 'min(1100px, 120vw)', maxHeight: '120vh', objectFit: 'contain', opacity: 0.05, pointerEvents: 'none' }} />

        {/* top bar */}
        <header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 28px', position: 'relative', zIndex: 20 }}>
          <a href="index.html" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
            <img src={A + 'axion-logo.png'} alt="AXION" style={{ height: 38, width: 'auto' }} />
            <span style={{ fontFamily: SERIF, fontSize: 21, fontWeight: 700, letterSpacing: '0.14em', color: '#D9B85A' }}>AXION</span>
          </a>
          <a href="index.html" style={{ fontFamily: MONO, fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(244,236,216,0.5)', textDecoration: 'none' }}>Close ×</a>
        </header>

        {/* body */}
        <main style={{ flex: 1, display: 'flex', alignItems: 'center', position: 'relative', zIndex: 10, paddingBottom: 60 }}>
          {q.type === 'statement' && (
            <Shell>
              <h1 style={{ fontFamily: SERIF, fontWeight: 700, fontSize: 'clamp(34px,5vw,58px)', letterSpacing: '0.04em', lineHeight: 1.08, margin: 0, color: '#FBF3DA' }}>{q.title}</h1>
              <p style={{ fontFamily: PROSE, fontSize: 'clamp(18px,2.2vw,23px)', lineHeight: 1.55, color: '#CFC2A0', margin: '20px 0 0', maxWidth: 540 }}>{q.body}</p>
              <OkButton onClick={next} label={q.cta} />
            </Shell>
          )}

          {q.type === 'end' && (
            <Shell>
              <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(217,184,90,0.12)', border: '1px solid rgba(217,184,90,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 26 }}>
                <Icon name="check" size={30} color="#D9B85A" />
              </div>
              <h1 style={{ fontFamily: SERIF, fontWeight: 700, fontSize: 'clamp(32px,4.6vw,54px)', letterSpacing: '0.04em', lineHeight: 1.1, margin: 0, color: '#FBF3DA' }}>{q.title}</h1>
              <p style={{ fontFamily: PROSE, fontSize: 'clamp(18px,2.2vw,23px)', lineHeight: 1.55, color: '#CFC2A0', margin: '20px 0 0', maxWidth: 540 }}>{q.body}</p>
              <div style={{ display: 'flex', gap: 14, marginTop: 32, flexWrap: 'wrap' }}>
                <a href="index.html" style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontFamily: BODY, fontSize: 15, fontWeight: 600, color: '#1a230f', background: 'var(--grad-gold)', padding: '13px 26px', borderRadius: 8, textDecoration: 'none' }}>Back to AXION <Icon name="arrow" size={16} color="#1a230f" /></a>
              </div>
            </Shell>
          )}

          {(q.type === 'short' || q.type === 'long') && (
            <Shell kicker={`${num(answeredIdx + 1)} \u2192`}>
              <h2 style={{ fontFamily: SERIF, fontWeight: 600, fontSize: 'clamp(26px,3.4vw,40px)', letterSpacing: '0.02em', lineHeight: 1.18, margin: 0, color: '#FBF3DA' }}>
                {q.q}{q.required && <span style={{ color: C.clay }}> *</span>}
              </h2>
              {q.sub && <p style={{ fontFamily: BODY, fontSize: 16, color: 'rgba(244,236,216,0.6)', margin: '12px 0 0' }}>{q.sub}</p>}
              {q.type === 'short' ? (
                <input ref={inputRef} type={q.inputType || 'text'} value={val} onChange={(e) => set(e.target.value)} placeholder={q.placeholder}
                  style={{ width: '100%', marginTop: 28, background: 'transparent', border: 'none', borderBottom: '2px solid rgba(217,184,90,0.4)', outline: 'none', color: '#FBF3DA', fontFamily: SERIF, fontSize: 'clamp(22px,2.8vw,30px)', padding: '8px 2px' }} />
              ) : (
                <textarea ref={inputRef} value={val} onChange={(e) => set(e.target.value)} placeholder={q.placeholder} rows={3}
                  style={{ width: '100%', marginTop: 26, background: 'transparent', border: 'none', borderBottom: '2px solid rgba(217,184,90,0.4)', outline: 'none', color: '#FBF3DA', fontFamily: PROSE, fontSize: 'clamp(20px,2.4vw,26px)', lineHeight: 1.4, padding: '8px 2px', resize: 'none' }} />
              )}
              <OkButton onClick={next} enabled={canAdvance} />
            </Shell>
          )}

          {q.type === 'choice' && (
            <Shell kicker={`${num(answeredIdx + 1)} \u2192`}>
              <h2 style={{ fontFamily: SERIF, fontWeight: 600, fontSize: 'clamp(26px,3.4vw,40px)', letterSpacing: '0.02em', lineHeight: 1.18, margin: 0, color: '#FBF3DA' }}>{q.q}</h2>
              {q.sub && <p style={{ fontFamily: BODY, fontSize: 16, color: 'rgba(244,236,216,0.6)', margin: '12px 0 0' }}>{q.sub}</p>}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 30 }}>
                {q.options.map(([k, label]) => {
                  const on = val === label;
                  return (
                    <button key={k} className="ap-choice" onClick={() => choose(label)} style={{
                      display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left', cursor: 'pointer',
                      background: on ? 'rgba(217,184,90,0.16)' : 'rgba(244,236,216,0.05)',
                      border: `1.5px solid ${on ? C.lineGold : 'rgba(244,236,216,0.18)'}`,
                      borderRadius: 10, padding: '16px 18px', transition: 'all .18s',
                    }}>
                      <span style={{ width: 28, height: 28, flexShrink: 0, borderRadius: 6, border: `1.5px solid ${on ? C.lineGold : 'rgba(244,236,216,0.3)'}`, background: on ? 'rgba(217,184,90,0.2)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: MONO, fontSize: 12, fontWeight: 600, color: on ? '#FBF3DA' : 'rgba(244,236,216,0.7)' }}>{on ? <Icon name="check" size={15} color="#FBF3DA" /> : k}</span>
                      <span style={{ fontFamily: BODY, fontSize: 16.5, color: '#F0E4C2' }}>{label}</span>
                    </button>
                  );
                })}
              </div>
            </Shell>
          )}
        </main>

        {/* nav arrows */}
        {q.type !== 'statement' && (
          <div style={{ position: 'fixed', right: 24, bottom: 24, display: 'flex', gap: 4, zIndex: 25 }}>
            <button onClick={prev} disabled={i === 0} style={navBtn(i === 0)} aria-label="Previous"><Icon name="up" size={18} color="#1a230f" /></button>
            <button onClick={next} disabled={i >= QUESTIONS.length - 1 || !canAdvance} style={navBtn(i >= QUESTIONS.length - 1 || !canAdvance)} aria-label="Next"><Icon name="down" size={18} color="#1a230f" /></button>
          </div>
        )}
      </div>
    );
  }

  function navBtn(disabled) {
    return {
      width: 42, height: 42, borderRadius: 8, border: 'none',
      background: disabled ? 'rgba(217,184,90,0.25)' : 'var(--grad-gold)',
      cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.5 : 1,
      display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all .2s',
    };
  }

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