// EvaluationSOC2.jsx — Verigo Global: SOC 2 online readiness evaluation (live, gated, resumable)
const { V: EV, MAXW: EMW, FONT: EFT } = window;

/* ── PROGRESS PERSISTENCE (localStorage) ─────────────────── */
const PROG_KEY = 'verigo_soc2_eval';
const loadProg = () => { try { return JSON.parse(localStorage.getItem(PROG_KEY) || 'null'); } catch (e) { return null; } };
const saveProg = (p) => { try { localStorage.setItem(PROG_KEY, JSON.stringify(p)); } catch (e) {} };
const clearProg = () => { try { localStorage.removeItem(PROG_KEY); } catch (e) {} };

const sPreviewThemes = [
  ['lock', 'CC6 · Access', 54],
  ['refresh', 'CC7 · Operations', 66],
  ['gauge', 'Availability', 78],
  ['users', 'Privacy', 46],
];

/* ── RESUME BANNER ───────────────────────────────────────── */
const SResumeBanner = ({ prog, onResume, onStartOver }) => {
  const done = prog.stage === 'results';
  const when = prog.ts ? new Date(prog.ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + ' · ' + new Date(prog.ts).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' }) : '';
  return (
    <div style={{ background: EV.purpleSubtle, borderBottom: `1px solid ${EV.g200}` }}>
      <div style={{ maxWidth: EMW, margin: '0 auto', padding: '14px 32px', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        <span style={{ width: 34, height: 34, background: EV.purple, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <window.Icon name={done ? 'check' : 'refresh'} size={18} color="#fff" />
        </span>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: EV.black, fontFamily: EFT }}>
            {done ? 'Your last evaluation is complete and saved.' : 'You have an evaluation in progress.'}
          </div>
          <div style={{ fontSize: 12.5, color: EV.g600 }}>
            {prog.scope && prog.scope.company ? prog.scope.company + ' · ' : ''}{when ? 'Saved ' + when : 'Pick up where you left off.'}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <window.Btn kind="primary" onClick={onResume}>{done ? 'View saved results' : 'Resume evaluation'} <window.Icon name="arrow" size={15} color="#fff" /></window.Btn>
          <window.Btn kind="ghost" onClick={onStartOver}>Start over</window.Btn>
        </div>
      </div>
    </div>
  );
};

/* ── PREVIEW DASHBOARD (illustrative, intro only) ────────── */
const SScorePreview = () => (
  <div style={{ background: '#fff', border: `1px solid ${EV.g200}`, boxShadow: '0 20px 48px rgba(63,30,104,0.18)', overflow: 'hidden' }}>
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 20px', borderBottom: `1px solid ${EV.g200}`, background: EV.g50 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <window.BrandMark size={22} />
        <span style={{ fontSize: 13, fontWeight: 700, color: EV.g700, fontFamily: EFT }}>Readiness report</span>
      </div>
      <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: EV.g400, fontFamily: "'JetBrains Mono', monospace" }}>Sample</span>
    </div>
    <div style={{ padding: '24px 22px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 22 }}>
        <div style={{ width: 92, height: 92, borderRadius: '50%', background: `conic-gradient(${EV.purple} 0% 64%, ${EV.g100} 64% 100%)`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <div style={{ width: 70, height: 70, borderRadius: '50%', background: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <span style={{ fontSize: 26, fontWeight: 800, color: EV.black, fontFamily: EFT, letterSpacing: '-0.02em', lineHeight: 1 }}>64</span>
            <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: EV.g400 }}>/ 100</span>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: EV.g400, marginBottom: 4 }}>Overall maturity</div>
          <div style={{ fontSize: 19, fontWeight: 800, color: EV.black, fontFamily: EFT, letterSpacing: '-0.01em' }}>Established</div>
          <div style={{ fontSize: 12.5, color: EV.g500, marginTop: 2 }}>18 of 61 criteria need work before the examination.</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {sPreviewThemes.map(([ic, name, pct], i) => (
          <div key={i}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, fontWeight: 600, color: EV.g700 }}>
                <window.Icon name={ic} size={15} color={EV.purple} />{name}
              </span>
              <span style={{ fontSize: 12, fontWeight: 700, color: pct < 60 ? EV.orange : EV.purple, fontFamily: "'JetBrains Mono', monospace" }}>{pct}%</span>
            </div>
            <div style={{ height: 7, background: EV.g100, borderRadius: 9999, overflow: 'hidden' }}>
              <div style={{ width: pct + '%', height: '100%', background: pct < 60 ? EV.orange : EV.purple, borderRadius: 9999 }}></div>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

/* ── INTRO STAGE ─────────────────────────────────────────── */
const SEvalIntro = ({ onStart, onNav, resume, onResume, onStartOver }) => {
  const steps = [
    ['clipboard', 'Self-assessment', 'Answer ~30 statements mapped to specific SOC 2 criteria — across the CC1–CC9 Common Criteria and every optional category you put in scope. About 12 minutes, no prep needed.'],
    ['gauge', 'Instant scoring', 'Get a weighted maturity score with a category-by-category breakdown showing exactly where you stand.'],
    ['flag', 'Mapped action plan', 'Every gap links straight to the toolkit document, policy, or procedure that closes it — so you know the next move.'],
  ];
  return (
    <div>
      {resume && <SResumeBanner prog={resume} onResume={onResume} onStartOver={onStartOver} />}
      <section style={{ position: 'relative', background: EV.g50, borderBottom: `1px solid ${EV.g200}`, overflow: 'hidden', padding: '56px 0 64px' }}>
        <window.HeroWatermark variant="rings" color={EV.purpleDark} opacity={0.14} style={{ top: -30, right: -20, width: 460, height: 420 }} />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: EMW, margin: '0 auto', padding: '0 32px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 600, color: EV.g500, marginBottom: 22, fontFamily: EFT }}>
            <button onClick={() => onNav('toolkit:soc2')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#7A7A8A', fontSize: 13, fontWeight: 600, padding: 0, fontFamily: EFT }}>SOC 2 Toolkit</button>
            <span style={{ color: EV.g300 }}>/</span>
            <span style={{ color: EV.purple }}>Online Evaluation</span>
          </div>
          <div className="vg-detail-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 400px', gap: 64, alignItems: 'center' }}>
            <div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: EV.purpleSubtle, color: EV.purple, fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '6px 13px', marginBottom: 20 }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: EV.orange }}></span> ~30 questions · ~12 minutes · free
              </div>
              <h1 className="vg-hero-title" style={{ fontSize: 54, fontWeight: 800, color: EV.black, letterSpacing: '-0.035em', lineHeight: 1.04, margin: '0 0 18px', fontFamily: EFT }}>
                Know where you stand on SOC 2.
              </h1>
              <p style={{ fontSize: 19, color: EV.g600, lineHeight: 1.6, margin: '0 0 28px', maxWidth: 560 }}>
                Measure your current state against the Trust Services Criteria — criterion by criterion across CC1–CC9 and the optional categories you choose to scope in. Get an instant maturity score and a prioritized action plan mapped straight to the toolkit documents that close each gap.
              </p>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
                <window.Btn kind="primary" onClick={onStart}>{resume ? 'Start a new evaluation' : 'Start the evaluation'} <window.Icon name="arrow" size={17} color="#fff" /></window.Btn>
                <window.Btn kind="ghost" onClick={() => onNav('contact')}>Talk to a practitioner</window.Btn>
              </div>
              <p style={{ fontSize: 12.5, color: EV.g400, marginTop: 14 }}>Free and confidential. We'll ask for a few details so we can send your results.</p>
            </div>
            <SScorePreview />
          </div>
        </div>
      </section>

      <window.Section bg="#fff" pad="80px 0">
        <window.SectionHeader overline="How it works" align="center"
          title="From a blank slate to a clear plan"
          sub="Three steps take you from “where do we even stand?” to a prioritized, toolkit-mapped action list." maxSub={620} />
        <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          {steps.map(([ic, t, d], i) => (
            <div key={i} style={{ border: `1px solid ${EV.g200}`, padding: '28px 26px', background: '#fff' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
                <div style={{ width: 48, height: 48, background: EV.purpleSubtle, color: EV.purple, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <window.Icon name={ic} size={24} />
                </div>
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13, fontWeight: 700, color: EV.g300 }}>{String(i + 1).padStart(2, '0')}</span>
              </div>
              <h3 style={{ fontSize: 18.5, fontWeight: 700, color: EV.black, margin: '0 0 8px', fontFamily: EFT, letterSpacing: '-0.01em' }}>{t}</h3>
              <p style={{ fontSize: 14, color: EV.g600, lineHeight: 1.6, margin: 0 }}>{d}</p>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 40 }}>
          <window.Btn kind="primary" onClick={onStart}>{resume ? 'Start a new evaluation' : 'Start the evaluation'} <window.Icon name="arrow" size={17} color="#fff" /></window.Btn>
        </div>
      </window.Section>
    </div>
  );
};

/* ── SCOPE FORM ──────────────────────────────────────────── */
const SCOPE_FIELDS_SOC2 = {
  industry: ['Software / SaaS', 'Financial services', 'Healthcare', 'Manufacturing', 'Professional services', 'Government / public sector', 'Retail / e-commerce', 'Other'],
  employees: ['1–50', '51–200', '201–1,000', '1,000+'],
  region: ['United States', 'India', 'United Kingdom', 'European Union', 'Singapore', 'Other'],
  locations: ['1 site', '2–5 sites', '6–20 sites', '20+ sites'],
  target: ['Type I — within 3 months', 'Type II — within 6 months', 'Type II — 6–12 months', '12+ months', 'Just exploring'],
};
// Trust Services categories selectable as in-scope parameters. Security is mandatory.
const CRITERIA_OPTIONS = [
  ['Security', 'lock', 'The mandatory Common Criteria (CC1–CC9). Always in scope.', true],
  ['Availability', 'gauge', 'Uptime, capacity, backup and disaster recovery commitments.', false],
  ['Confidentiality', 'shield', 'Protection of information designated as confidential.', false],
  ['Processing Integrity', 'check', 'Complete, valid, accurate, timely processing.', false],
  ['Privacy', 'users', 'Collection, use, retention and disposal of personal data.', false],
];
const evInput = { fontFamily: EFT, fontSize: 14, color: EV.black, background: '#fff', border: `1.5px solid ${EV.g200}`, borderRadius: 8, padding: '11px 14px', outline: 'none', width: '100%' };
const evLabel = { fontSize: 12.5, fontWeight: 600, color: EV.black, display: 'block', marginBottom: 7 };
const evSelect = { ...evInput, appearance: 'none', backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%239A9AAA' stroke-width='2.5'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E\")", backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', paddingRight: 32, cursor: 'pointer' };

const SScopeForm = ({ onSubmit, onBack, saved }) => {
  const u = (() => { try { return window.TK_SOC2.getUser() || {}; } catch (e) { return {}; } })();
  const sv = saved || {};
  const [f, setF] = React.useState({
    company: sv.company || u.company || '', name: sv.name || u.name || '', email: sv.email || u.email || '', phone: sv.phone || u.phone || '', role: sv.role || u.role || '',
    industry: sv.industry || u.industry || SCOPE_FIELDS_SOC2.industry[0], employees: sv.employees || u.employees || SCOPE_FIELDS_SOC2.employees[0],
    region: sv.region || u.region || SCOPE_FIELDS_SOC2.region[0], locations: sv.locations || u.locations || SCOPE_FIELDS_SOC2.locations[0],
    systems: sv.systems || u.systems || '', certs: sv.certs || u.certs || '', target: sv.target || u.target || SCOPE_FIELDS_SOC2.target[1],
  });
  // Optional categories chosen as in scope (Security implicit & mandatory).
  const [criteria, setCriteria] = React.useState(() => (saved && Array.isArray(saved.criteria)) ? saved.criteria : []);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const toggleCat = (name) => setCriteria((prev) => prev.indexOf(name) !== -1 ? prev.filter((c) => c !== name) : [...prev, name]);
  const text = (k, lbl, props = {}) => <div><label style={evLabel}>{lbl}</label><input style={evInput} value={f[k]} onChange={(e) => set(k, e.target.value)} {...props} /></div>;
  const sel = (k, lbl) => <div><label style={evLabel}>{lbl}</label><select style={evSelect} value={f[k]} onChange={(e) => set(k, e.target.value)}>{SCOPE_FIELDS_SOC2[k].map((o) => <option key={o}>{o}</option>)}</select></div>;

  return (
    <div>
      <section style={{ position: 'relative', background: EV.g50, borderBottom: `1px solid ${EV.g200}`, overflow: 'hidden', padding: '44px 0 40px' }}>
        <window.HeroWatermark variant="rings" color={EV.purpleDark} opacity={0.12} style={{ top: -30, right: -20, width: 420, height: 380 }} />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: EMW, margin: '0 auto', padding: '0 32px' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: EV.purple, marginBottom: 14 }}>Step 1 of 2 · Scope your assessment</div>
          <h1 className="vg-hero-title" style={{ fontSize: 40, fontWeight: 800, color: EV.black, letterSpacing: '-0.03em', lineHeight: 1.06, margin: '0 0 12px', fontFamily: EFT }}>Tell us about your organization</h1>
          <p style={{ fontSize: 17, color: EV.g600, lineHeight: 1.6, margin: 0, maxWidth: 620 }}>A few details set the scope and let us tailor your results and quote. Then you’ll move on to the technical evaluation.</p>
        </div>
      </section>

      <window.Section bg="#fff" pad="40px 0 84px">
        <form onSubmit={(e) => { e.preventDefault(); onSubmit({ ...f, criteria }); }} style={{ maxWidth: 860, margin: '0 auto' }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: EV.g400, marginBottom: 14 }}>Your organization</div>
          <div style={{ background: '#fff', border: `1px solid ${EV.g200}`, padding: '24px', display: 'flex', flexDirection: 'column', gap: 16, marginBottom: 28 }}>
            <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {text('company', 'Company', { required: true, placeholder: 'Acme Technologies' })}
              {text('name', 'Your name', { required: true, placeholder: 'Jane Smith' })}
            </div>
            <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {text('email', 'Work email', { required: true, type: 'email', placeholder: 'jane@company.com' })}
              {text('phone', 'Phone number', { required: true, type: 'tel', placeholder: '+1 555 000 1234' })}
            </div>
            <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
              {text('role', 'Role / title', { placeholder: 'CISO' })}
              {sel('industry', 'Industry')}
              {sel('employees', 'Company size')}
            </div>
          </div>

          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: EV.g400, marginBottom: 14 }}>Assessment scope</div>
          <div style={{ background: '#fff', border: `1px solid ${EV.g200}`, padding: '24px', display: 'flex', flexDirection: 'column', gap: 20 }}>
            <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
              {sel('region', 'Primary region')}
              {sel('locations', 'Sites / locations')}
              {sel('target', 'Target report')}
            </div>
            <div><label style={evLabel}>Systems & services in scope</label><textarea style={{ ...evInput, minHeight: 76, resize: 'vertical' }} value={f.systems} onChange={(e) => set('systems', e.target.value)} placeholder="e.g. production SaaS platform, corporate IT, AWS & Azure environments…" /></div>
            {text('certs', 'Existing certifications (optional)', { placeholder: 'e.g. ISO 27001, none yet' })}

            {/* In-scope Trust Services categories */}
            <div>
              <label style={evLabel}>Which Trust Services categories should be in scope?</label>
              <p style={{ fontSize: 12.5, color: EV.g500, lineHeight: 1.55, margin: '0 0 12px' }}>Security (the Common Criteria) is mandatory in every SOC 2 examination. Add the optional categories that match the commitments you make to customers — the evaluation will only assess what you scope in.</p>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 10 }}>
                {CRITERIA_OPTIONS.map(([name, icon, desc, required]) => {
                  const on = required || criteria.indexOf(name) !== -1;
                  return (
                    <button type="button" key={name} onClick={() => { if (!required) toggleCat(name); }}
                      aria-pressed={on}
                      style={{ display: 'flex', alignItems: 'flex-start', gap: 12, textAlign: 'left', fontFamily: EFT, cursor: required ? 'default' : 'pointer', background: on ? EV.purpleSubtle : '#fff', border: `1.5px solid ${on ? EV.purple : EV.g200}`, borderRadius: 8, padding: '14px 16px', transition: 'all 150ms' }}>
                      <span style={{ width: 22, height: 22, borderRadius: 5, border: `1.5px solid ${on ? EV.purple : EV.g300}`, background: on ? EV.purple : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                        {on && <window.Icon name="check" size={14} color="#fff" />}
                      </span>
                      <span style={{ flex: 1 }}>
                        <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <window.Icon name={icon} size={16} color={on ? EV.purple : EV.g400} />
                          <span style={{ fontSize: 14, fontWeight: 700, color: EV.black }}>{name}</span>
                          <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: required ? EV.orange : EV.g400, background: required ? EV.orangeSubtle : EV.g100, padding: '2px 7px', borderRadius: 4, marginLeft: 'auto' }}>{required ? 'Required' : 'Optional'}</span>
                        </span>
                        <span style={{ display: 'block', fontSize: 12, color: EV.g500, lineHeight: 1.45, marginTop: 5 }}>{desc}</span>
                      </span>
                    </button>
                  );
                })}
              </div>
              <p style={{ fontSize: 12, color: EV.g400, margin: '12px 0 0' }}>
                In scope: <strong style={{ color: EV.purple }}>Security{criteria.length ? ', ' + criteria.join(', ') : ''}</strong> · 1 mandatory + {criteria.length} optional categor{criteria.length === 1 ? 'y' : 'ies'}
              </p>
            </div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 24 }}>
            <window.Btn kind="ghost" onClick={onBack}>Back</window.Btn>
            <window.Btn kind="primary">Start the technical evaluation <window.Icon name="arrow" size={16} color="#fff" /></window.Btn>
          </div>
          <p style={{ textAlign: 'right', fontSize: 12.5, color: EV.g400, marginTop: 10 }}>~30 quick questions · about 12 minutes · saved automatically</p>
        </form>
      </window.Section>
    </div>
  );
};

/* ── PAGE ────────────────────────────────────────────────── */
const EvaluationSOC2Page = ({ onNav }) => {
  const [stage, setStage] = React.useState('intro'); // intro | scope | quiz | results
  const [gate, setGate] = React.useState(false);
  const [results, setResults] = React.useState(null);
  const [user, setUser] = React.useState(null);
  const [scopeData, setScopeData] = React.useState(null); // { form, criteria }
  const [resume, setResume] = React.useState(null);       // saved progress for the intro banner
  const [seed, setSeed] = React.useState(null);           // { answers, step } to resume the quiz

  React.useEffect(() => {
    try { setUser(window.TK_SOC2.getUser()); } catch (e) {}
    const p = loadProg();
    if (p && p.stage && p.stage !== 'intro') setResume(p);
  }, []);

  const persist = (patch) => { const base = loadProg() || {}; saveProg({ ...base, ...patch, ts: Date.now() }); };
  const contactOk = () => { try { return !!sessionStorage.getItem('verigo_contact_ok'); } catch (e) { return false; } };

  const requestStart = () => {
    if (contactOk()) { setUser(window.TK_SOC2.getUser()); setStage('scope'); window.scrollTo({ top: 0 }); }
    else { setGate(true); }
  };
  const onGateSubmit = (form) => {
    window.TK_SOC2.storeLead({ ...form, source: 'evaluation' });
    try { sessionStorage.setItem('verigo_contact_ok', '1'); } catch (e) {}
    setUser(window.TK_SOC2.getUser());
    setGate(false);
    setStage('scope');
    window.scrollTo({ top: 0 });
  };
  const onScopeSubmit = (form) => {
    const criteria = Array.isArray(form.criteria) ? form.criteria : [];
    window.TK_SOC2.storeLead({ ...form, criteria: ['Security'].concat(criteria).join(', '), source: 'evaluation-scope' });
    setUser(window.TK_SOC2.getUser());
    setScopeData({ form, criteria });
    setSeed({ answers: {}, step: 0 });
    saveProg({ stage: 'quiz', scope: form, criteria, answers: {}, step: 0, ts: Date.now() });
    setStage('quiz');
    window.scrollTo({ top: 0 });
  };
  const onQuizProgress = (answers, step) => { persist({ stage: 'quiz', answers, step }); };
  const onComplete = (res) => { setResults(res); persist({ stage: 'results', results: res }); setStage('results'); window.scrollTo({ top: 0 }); };
  const retake = () => { setResults(null); setSeed({ answers: {}, step: 0 }); persist({ stage: 'quiz', answers: {}, step: 0, results: null }); setStage('quiz'); window.scrollTo({ top: 0 }); };

  const doResume = () => {
    const p = resume; if (!p) return;
    if (p.scope) setScopeData({ form: p.scope, criteria: Array.isArray(p.criteria) ? p.criteria : [] });
    setSeed({ answers: p.answers || {}, step: p.step || 0 });
    if (p.results) setResults(p.results);
    setResume(null);
    setStage(p.stage === 'results' ? 'results' : 'quiz');
    window.scrollTo({ top: 0 });
  };
  const doStartOver = () => { clearProg(); setResume(null); setResults(null); setScopeData(null); setSeed(null); setStage('intro'); requestStart(); };

  const scopeCriteria = scopeData ? scopeData.criteria : [];

  return (
    <div>
      {stage === 'intro' && <SEvalIntro onStart={requestStart} onNav={onNav} resume={resume} onResume={doResume} onStartOver={doStartOver} />}
      {stage === 'scope' && <SScopeForm onSubmit={onScopeSubmit} onBack={() => { setStage('intro'); window.scrollTo({ top: 0 }); }} saved={resume && resume.scope ? { ...resume.scope, criteria: resume.criteria } : null} />}
      {stage === 'quiz' && <window.EvalQuizSOC2
        criteria={scopeCriteria}
        initialAnswers={seed ? seed.answers : {}}
        initialStep={seed ? seed.step : 0}
        onProgress={onQuizProgress}
        onComplete={onComplete}
        onExit={() => { setStage('intro'); window.scrollTo({ top: 0 }); }} />}
      {stage === 'results' && results && <window.EvalResultsSOC2 results={results} user={user} onNav={onNav} onRetake={retake} />}

      {gate && (
        <window.LeadCaptureModal
          icon="gauge"
          eyebrow="SOC 2 readiness evaluation"
          heading="Start your evaluation"
          intro="Tell us who you are so we can send your results and tailor your quote. Next, we’ll capture a little about your organization and scope."
          cta="Continue"
          note="Free and confidential. We'll only use your details to share your results and follow up."
          onClose={() => setGate(false)}
          onSubmit={onGateSubmit} />
      )}
    </div>
  );
};

Object.assign(window, { EvaluationSOC2Page });
