// Conversational intake flow — one question at a time
const IntakePage = ({ onNav }) => {
  const { useState } = React;
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});

  const questions = [
    {
      key: 'role', q: 'Who is requesting the match?',
      sub: 'We tailor process and confidentiality posture based on requesting party.',
      options: ['Outside counsel', 'In-house counsel', 'Court / chambers', 'Party (pro se)', 'Other neutral / co-mediator'],
    },
    {
      key: 'engagement', q: 'What kind of engagement?',
      sub: 'Each role has a different scope, deliverable, and timeline.',
      options: ['Mediation', 'Special Master / Discovery Referee', 'Forensic Neutral', 'Arbitration (sole)', 'Arbitration (panel)', 'Neutral Evaluation'],
    },
    {
      key: 'typology', q: 'What is the closest characterization of the matter?',
      sub: 'Used to surface neutrals with subject-matter fluency.',
      options: ['AI / model output liability', 'Trade secret — software, ML weights, schematics', 'Smart contract — on-chain auto-execution', 'Cyber insurance coverage', 'eDiscovery / ESI dispute', 'Cross-border commercial', 'Patent — software / hardware', 'Other'],
    },
    {
      key: 'complexity', q: 'How would you scope technical complexity?',
      sub: 'Determines whether a single neutral or co-mediator pairing is appropriate.',
      options: [
        { label: 'Foundational', desc: 'One technical question, accessible to lay finders' },
        { label: 'Substantial', desc: 'Multiple technical witnesses; protective order needed' },
        { label: 'Acute', desc: 'Source code, model weights, or proprietary algorithm at issue' },
        { label: 'Frontier', desc: 'No prevailing case law; novel technical instrument' },
      ],
    },
    {
      key: 'exposure', q: 'Approximate exposure?',
      sub: 'A confidential range only — informs panel selection.',
      options: ['Under $1M', '$1M – $10M', '$10M – $100M', '$100M – $1B', 'Over $1B', 'Prefer not to specify'],
    },
    {
      key: 'posture', q: 'Where is the matter currently?',
      sub: 'Different stages call for different intervention.',
      options: ['Pre-suit', 'Filed, pre-discovery', 'In discovery', 'Dispositive briefing', 'Pre-trial', 'On appeal', 'Post-judgment / enforcement'],
    },
    {
      key: 'urgency', q: 'When would you need a first session?',
      sub: 'We will be candid if availability cannot meet your window.',
      options: ['Within 14 days', '15–30 days', '30–60 days', '60–90 days', 'Flexible'],
    },
    {
      key: 'jurisdiction', q: 'Primary jurisdiction(s)?',
      sub: 'For conflicts check and seat / venue logistics.',
      options: ['California', 'New York', 'Delaware', 'Other U.S. state', 'U.S. federal', 'Israel / Middle East', 'United Kingdom / Switzerland / EU', 'Singapore / Hong Kong / Asia-Pacific', 'Multiple cross-border'],
    },
  ];

  const total = questions.length;

  const onAnswer = (val) => {
    const q = questions[step];
    setAnswers({ ...answers, [q.key]: val });
    setTimeout(() => setStep(step + 1), 280);
  };

  const reset = () => { setStep(0); setAnswers({}); };

  if (step >= total) {
    return <MatchResult answers={answers} onNav={onNav} onReset={reset}/>;
  }

  const q = questions[step];
  const pct = Math.round((step / total) * 100);

  return (
    <div className="page-fade" style={{ background: 'var(--ink)', color: 'var(--paper)', minHeight: 'calc(100vh - 65px)' }}>
      {/* Progress */}
      <div style={{ borderBottom: '1px solid rgba(212,185,122,0.18)' }}>
        <div className="container" style={{ padding: '24px 32px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', color: 'var(--gold)' }}>
            MATCH INTAKE · CONFIDENTIAL
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--slate-300)', letterSpacing: '0.18em' }}>
            Q.{String(step + 1).padStart(2, '0')} / {String(total).padStart(2, '0')} · {pct}%
          </div>
        </div>
        <div style={{ height: 1, background: 'rgba(255,255,255,0.05)', position: 'relative' }}>
          <div style={{
            position: 'absolute', left: 0, top: 0, bottom: 0,
            width: `${(step / total) * 100}%`, background: 'var(--gold)',
            transition: 'width 0.4s ease'
          }}/>
        </div>
      </div>

      <div className="container" style={{ padding: '88px 32px', maxWidth: 980 }}>
        {/* Stepper */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 56 }}>
          {questions.map((qq, i) => (
            <div key={i} style={{
              flex: 1, height: 3,
              background: i < step ? 'var(--gold)' : i === step ? 'var(--gold)' : 'rgba(255,255,255,0.08)',
              opacity: i === step ? 1 : i < step ? 0.6 : 1,
              transition: 'all 0.3s'
            }}/>
          ))}
        </div>

        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', color: 'var(--gold)', marginBottom: 24 }}>
          QUESTION {String(step + 1).padStart(2, '0')}
        </div>
        <h1 className="display" style={{
          fontSize: 'clamp(36px, 5.5vw, 68px)', color: 'var(--paper)',
          lineHeight: 1.05, maxWidth: 880
        }}>
          {q.q}
        </h1>
        {q.sub && (
          <p className="serif" style={{
            fontSize: 19, color: 'var(--slate-300)', marginTop: 24,
            fontStyle: 'italic', maxWidth: 640
          }}>
            {q.sub}
          </p>
        )}

        <div style={{ marginTop: 56, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {q.options.map((opt, i) => {
            const label = typeof opt === 'string' ? opt : opt.label;
            const desc = typeof opt === 'string' ? null : opt.desc;
            const selected = answers[q.key] === label;
            return (
              <button key={label} onClick={() => onAnswer(label)} style={{
                textAlign: 'left',
                padding: '22px 28px',
                border: `1px solid ${selected ? 'var(--gold)' : 'rgba(255,255,255,0.12)'}`,
                background: selected ? 'rgba(212,185,122,0.08)' : 'transparent',
                color: 'var(--paper)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                gap: 24, transition: 'all 0.18s',
              }}
              onMouseEnter={(e) => { if (!selected) { e.currentTarget.style.borderColor = 'rgba(212,185,122,0.6)'; e.currentTarget.style.background = 'rgba(212,185,122,0.04)'; } }}
              onMouseLeave={(e) => { if (!selected) { e.currentTarget.style.borderColor = 'rgba(255,255,255,0.12)'; e.currentTarget.style.background = 'transparent'; } }}
              >
                <div>
                  <div className="serif" style={{ fontSize: 22, lineHeight: 1.3 }}>{label}</div>
                  {desc && <div style={{ fontSize: 14, color: 'var(--slate-300)', marginTop: 4 }}>{desc}</div>}
                </div>
                <span className="mono" style={{ fontSize: 10, letterSpacing: '0.2em', color: 'var(--gold)' }}>
                  {String.fromCharCode(65 + i)} →
                </span>
              </button>
            );
          })}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 48, paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
          {step > 0 ? (
            <button onClick={() => setStep(step - 1)} className="mono" style={{ fontSize: 12, color: 'var(--slate-300)', letterSpacing: '0.16em' }}>
              ← BACK
            </button>
          ) : <span/>}
          <button onClick={() => onNav('home')} className="mono" style={{ fontSize: 12, color: 'var(--slate-300)', letterSpacing: '0.16em' }}>
            CANCEL ✕
          </button>
        </div>
      </div>
    </div>
  );
};

// Match result screen
const MatchResult = ({ answers, onNav, onReset }) => {
  const { useState } = React;
  const matchType = answers.engagement || 'Mediation';
  const typology = answers.typology || 'Technical Dispute';
  const FORM_ENDPOINT = (window.SITE_CONFIG && window.SITE_CONFIG.FORM_ENDPOINT) || 'https://formspree.io/f/YOUR_FORMSPREE_ID';
  const FORM_SUBJECT  = (window.SITE_CONFIG && window.SITE_CONFIG.FORM_SUBJECT_INTAKE) || 'Tailored Mediation — new match intake';

  const [confirm, setConfirm] = useState(false);          // contact-detail step shown?
  const [status, setStatus] = useState('idle');            // idle | submitting | submitted | error
  const [errMsg, setErrMsg] = useState('');
  const [contact, setContact] = useState({ name: '', organization: '', email: '', phone: '', notes: '' });

  const onField = (k) => (e) => setContact({ ...contact, [k]: e.target.value });

  async function submitMatch(e) {
    e.preventDefault();
    if (!contact.name || !contact.email) {
      setErrMsg('Name and email are required so we can respond.');
      setStatus('error');
      return;
    }
    if (window.SITE_CONFIG && !window.SITE_CONFIG.isFormEndpointConfigured()) {
      setErrMsg('The match intake is not yet wired to a delivery endpoint. Please email matters@tailoredmediation.com with the details below.');
      setStatus('error');
      return;
    }
    setStatus('submitting');
    setErrMsg('');
    try {
      const fd = new FormData();
      fd.append('_subject', FORM_SUBJECT);
      fd.append('_source', 'match-intake');
      fd.append('name', contact.name);
      fd.append('organization', contact.organization);
      fd.append('email', contact.email);
      fd.append('phone', contact.phone);
      fd.append('notes', contact.notes);
      // Intake answers — flat fields so they show up nicely in the email body.
      Object.entries(answers).forEach(([k, v]) => fd.append('intake_' + k, v));

      const res = await fetch(FORM_ENDPOINT, {
        method: 'POST',
        body: fd,
        headers: { Accept: 'application/json' },
      });
      if (res.ok) {
        setStatus('submitted');
      } else {
        const j = await res.json().catch(() => ({}));
        setErrMsg(j.error || 'Something went wrong. Please email matters@tailoredmediation.com directly.');
        setStatus('error');
      }
    } catch (err) {
      setErrMsg('Network error. Please email matters@tailoredmediation.com directly.');
      setStatus('error');
    }
  }

  if (status === 'submitted') {
    return (
      <div className="page-fade" style={{ background: 'var(--paper)', minHeight: 'calc(100vh - 65px)' }}>
        <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '64px 0' }}>
          <div className="container">
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', color: 'var(--gold)', marginBottom: 16 }}>
              MATCH REQUEST · RECEIVED · {new Date().toISOString().slice(0,10)}
            </div>
            <h1 className="display" style={{ fontSize: 'clamp(40px, 5vw, 64px)', color: 'var(--paper)' }}>
              Thank you. Your match request has been received.
            </h1>
            <p className="serif" style={{ fontSize: 20, color: 'var(--slate-300)', marginTop: 16, fontStyle: 'italic', maxWidth: 620 }}>
              A case manager will respond within one business day with conflicts-check status and proposed scheduling. For urgent matters call +1 (213) 620-1133.
            </p>
            <div style={{ marginTop: 32, display: 'flex', gap: 12 }}>
              <button className="btn btn-gold" onClick={() => onNav('home')}>Return home <span className="arrow">→</span></button>
              <button className="btn btn-ghost" style={{ color: 'var(--paper)', borderColor: 'rgba(212,185,122,0.4)' }} onClick={onReset}>Submit another</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page-fade" style={{ background: 'var(--paper)', minHeight: 'calc(100vh - 65px)' }}>
      <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '64px 0' }}>
        <div className="container">
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.2em', color: 'var(--gold)', marginBottom: 16 }}>
            MATCH REQUEST · GENERATED · {new Date().toISOString().slice(0,10)}
          </div>
          <h1 className="display" style={{ fontSize: 'clamp(40px, 5vw, 64px)', color: 'var(--paper)' }}>
            One match identified.
          </h1>
          <p className="serif" style={{ fontSize: 20, color: 'var(--slate-300)', marginTop: 16, fontStyle: 'italic', maxWidth: 600 }}>
            Based on your responses, the following neutral has the highest subject-matter alignment with the matter you described.
          </p>
        </div>
      </div>

      <div className="container" style={{ padding: '64px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 64 }}>
          {/* Match summary */}
          <div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--slate-700)', marginBottom: 16 }}>
              MATTER SUMMARY
            </div>
            <div style={{ border: '1px solid var(--line-soft)', background: 'var(--paper-2)' }}>
              {Object.entries(answers).map(([k, v], i, arr) => (
                <div key={k} style={{
                  padding: '16px 20px',
                  borderBottom: i < arr.length - 1 ? '1px solid var(--line-soft)' : 'none'
                }}>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--slate-700)', textTransform: 'uppercase' }}>
                    {k}
                  </div>
                  <div className="serif" style={{ fontSize: 15, marginTop: 4, color: 'var(--ink)' }}>{v}</div>
                </div>
              ))}
            </div>
            <button onClick={onReset} className="mono" style={{ marginTop: 20, fontSize: 11, letterSpacing: '0.18em', color: 'var(--slate-700)' }}>
              ← REVISE INTAKE
            </button>
          </div>

          {/* Matched neutral */}
          <div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--gold-deep)', marginBottom: 16 }}>
              MATCH 01 · CONFIDENCE 96% · IN-NETWORK
            </div>
            <div style={{ border: '1px solid var(--navy)', padding: 36, background: 'var(--paper)' }}>
              <div style={{ display: 'flex', gap: 32 }}>
                <div style={{ width: 120, height: 150, flexShrink: 0, position: 'relative', overflow: 'hidden' }}>
                  <PhotoPortrait src="assets/dg-portrait-sm.jpg" caption="MATCH 01" cornerStamp="96% CONF."/>
                </div>
                <div>
                  <h2 className="display" style={{ fontSize: 36, lineHeight: 1.05 }}>
                    Daniel B. Garrie, Esq.
                  </h2>
                  <div className="serif" style={{ fontSize: 16, color: 'var(--slate-700)', marginTop: 8, fontStyle: 'italic' }}>
                    Mediator · Arbitrator · Special Master · Forensic Neutral
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 16 }}>
                    <span className="tag gold">Harvard · Adjunct</span>
                    <span className="tag gold">Acad. of Court Appointed Masters</span>
                    <span className="tag gold">L.C.I.A.</span>
                    <span className="tag gold">H.K.I.A.C.</span>
                  </div>
                </div>
              </div>

              <div style={{ marginTop: 32, paddingTop: 24, borderTop: '1px solid var(--line-soft)' }}>
                <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--slate-700)', marginBottom: 14 }}>
                  WHY THIS MATCH
                </div>
                <ul style={{ listStyle: 'none' }}>
                  {[
                    `${matchType} experience in matters substantially similar to yours`,
                    `Subject-matter fluency in: ${typology}`,
                    'Co-inventor on four cybersecurity patents; certified forensic engineer',
                    'Author of 400+ technical-legal publications; cited in 500+ opinions',
                    'Distinguished Neutral, Academy of Court Appointed Masters',
                  ].map(r => (
                    <li key={r} style={{ display: 'flex', gap: 12, padding: '8px 0', fontSize: 15, color: 'var(--ink)' }}>
                      <span className="mono" style={{ color: 'var(--gold-deep)', flexShrink: 0 }}>✓</span>
                      <span>{r}</span>
                    </li>
                  ))}
                </ul>
              </div>

              {!confirm ? (
                <div style={{ display: 'flex', gap: 12, marginTop: 32 }}>
                  <button className="btn btn-primary" onClick={() => setConfirm(true)}>
                    Confirm match request <span className="arrow">→</span>
                  </button>
                  <button className="btn btn-ghost" onClick={() => onNav('about')}>
                    Full biography
                  </button>
                </div>
              ) : (
                <form onSubmit={submitMatch} style={{ marginTop: 32, paddingTop: 24, borderTop: '1px solid var(--line-soft)' }}>
                  <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--slate-700)', marginBottom: 14 }}>
                    YOUR CONTACT — SO WE CAN RESPOND
                  </div>
                  {[
                    ['Name *', 'name', 'text', true, 'name'],
                    ['Firm / Organization', 'organization', 'text', false, 'organization'],
                    ['Email *', 'email', 'email', true, 'email'],
                    ['Phone', 'phone', 'tel', false, 'tel'],
                  ].map(([label, key, type, req, ac]) => (
                    <div key={key} style={{ marginBottom: 14 }}>
                      <label htmlFor={'mi-' + key} className="mono" style={{ fontSize: 10, color: 'var(--slate-700)', letterSpacing: '0.16em', textTransform: 'uppercase' }}>{label}</label>
                      <input id={'mi-' + key} type={type} required={req} autoComplete={ac}
                        value={contact[key]} onChange={onField(key)}
                        style={{ display: 'block', width: '100%', marginTop: 6, padding: '10px 12px',
                                 border: '1px solid var(--line-soft)', background: 'var(--paper)',
                                 fontFamily: 'var(--serif)', fontSize: 16, color: 'var(--ink)' }}/>
                    </div>
                  ))}
                  <div style={{ marginBottom: 14 }}>
                    <label htmlFor="mi-notes" className="mono" style={{ fontSize: 10, color: 'var(--slate-700)', letterSpacing: '0.16em', textTransform: 'uppercase' }}>Anything else (optional)</label>
                    <textarea id="mi-notes" rows={3}
                      value={contact.notes} onChange={onField('notes')}
                      placeholder="Conflicts to flag, scheduling constraints, opposing parties, etc."
                      style={{ display: 'block', width: '100%', marginTop: 6, padding: '10px 12px',
                               border: '1px solid var(--line-soft)', background: 'var(--paper)',
                               fontFamily: 'var(--serif)', fontSize: 16, color: 'var(--ink)', resize: 'vertical' }}/>
                  </div>
                  {status === 'error' && (
                    <div style={{ background: 'var(--paper-2)', border: '1px solid #c33', padding: 12, marginBottom: 12, fontSize: 14, color: '#c33' }}>
                      {errMsg}
                    </div>
                  )}
                  <div style={{ display: 'flex', gap: 12 }}>
                    <button type="submit" disabled={status === 'submitting'} className="btn btn-primary">
                      {status === 'submitting' ? 'Sending…' : 'Send match request'} <span className="arrow">→</span>
                    </button>
                    <button type="button" className="btn btn-ghost" onClick={() => setConfirm(false)}>
                      Cancel
                    </button>
                  </div>
                  <p style={{ fontSize: 12, color: 'var(--slate-700)', marginTop: 14, lineHeight: 1.5 }}>
                    Submissions are forwarded by email and are not protected by attorney-client privilege. For privileged information, please call before transmitting.
                  </p>
                </form>
              )}
            </div>

            {/* Secondary panel */}
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--slate-700)', margin: '36px 0 16px' }}>
              ALTERNATE PANEL · IF CONFLICT
            </div>
            <div style={{ border: '1px solid var(--line-soft)', background: 'var(--paper-2)', padding: 24 }}>
              <p style={{ fontSize: 14, color: 'var(--slate-700)', lineHeight: 1.6 }}>
                Should a conflicts check disqualify the primary match, our network includes
                vetted neutrals with overlapping subject-matter expertise. We will surface
                two alternates with disclosure-cleared availability within 48 hours.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.IntakePage = IntakePage;
