// EvaluationCMMC.jsx — Verigo Global: CMMC 2.0 online readiness evaluation (level-driven, gated, resumable)
const { V: EV, MAXW: EMW, FONT: EFT } = window;

/* ── PROGRESS PERSISTENCE (localStorage) ─────────────────── */
const PROG_KEY = 'verigo_cmmc_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 cPreviewThemes = [
  ['lock', 'AC · Access Control', 58],
  ['shield', 'IA · Identification', 64],
  ['network', 'SC · Comms Protection', 52],
  ['activity', 'SI · System Integrity', 70],
];

/* ── RESUME BANNER ───────────────────────────────────────── */
const CResumeBanner = ({ 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' }) : '';
  const lvl = prog.level ? 'Level ' + prog.level : '';
  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 + ' · ' : ''}{lvl ? lvl + ' · ' : ''}{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 CScorePreview = () => (
  <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 · L2</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% 61%, ${EV.g100} 61% 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 }}>61</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 }}>41 of 110 practices need work before assessment.</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {cPreviewThemes.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 CEvalIntro = ({ onStart, onNav, resume, onResume, onStartOver }) => {
  const steps = [
    ['target', 'Pick your level & scope', 'Choose Level 1, 2, or 3 and tell us about your environment — your level decides exactly which practices the evaluation asks about.'],
    ['gauge', 'Instant scoring', 'Get a weighted maturity score with a domain-by-domain breakdown showing where you stand against 800-171.'],
    ['flag', 'Mapped action plan', 'Every gap links straight to the toolkit document, policy, or practice that closes it — so you know the next move.'],
  ];
  return (
    <div>
      {resume && <CResumeBanner 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:cmmc')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#7A7A8A', fontSize: 13, fontWeight: 600, padding: 0, fontFamily: EFT }}>CMMC 2.0 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> Level-aware · ~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 CMMC 2.0.
              </h1>
              <p style={{ fontSize: 19, color: EV.g600, lineHeight: 1.6, margin: '0 0 28px', maxWidth: 560 }}>
                Measure your current state against the NIST SP 800-171 practices for the CMMC level you’re targeting. Pick your level in scope and the evaluation asks only the practices that apply — then maps every gap to the toolkit documents that close it.
              </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>
            <CScorePreview />
          </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_CMMC = {
  industry: ['Defense / aerospace', 'IT / managed services', 'Manufacturing', 'Software / SaaS', 'Professional services', 'Logistics', 'Other'],
  employees: ['1–50', '51–200', '201–1,000', '1,000+'],
  region: ['United States', 'Other'],
  locations: ['1 site', '2–5 sites', '6–20 sites', '20+ sites'],
  target: ['Within 3 months', 'Within 6 months', '6–12 months', '12+ months', 'Just exploring'],
};
// CMMC levels — the choice here decides which domains/questions the evaluation asks.
const LEVEL_OPTIONS = [
  [1, 'Level 1 — Foundational', '17 practices', 'Federal Contract Information (FCI) · annual self-assessment'],
  [2, 'Level 2 — Advanced', '110 practices', 'Controlled Unclassified Information (CUI) · C3PAO assessment'],
  [3, 'Level 3 — Expert', '110+ practices', 'High-priority CUI · adds enhanced 800-172 controls'],
];
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 CScopeForm = ({ onSubmit, onBack, saved }) => {
  const u = (() => { try { return window.TK_CMMC.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_CMMC.industry[0], employees: sv.employees || u.employees || SCOPE_FIELDS_CMMC.employees[0],
    region: sv.region || u.region || SCOPE_FIELDS_CMMC.region[0], locations: sv.locations || u.locations || SCOPE_FIELDS_CMMC.locations[0],
    systems: sv.systems || u.systems || '', certs: sv.certs || u.certs || '', target: sv.target || u.target || SCOPE_FIELDS_CMMC.target[1],
  });
  const [level, setLevel] = React.useState(() => (saved && saved.level) ? Number(saved.level) : 2);
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  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_CMMC[k].map((o) => <option key={o}>{o}</option>)}</select></div>;
  const lvlMeta = LEVEL_OPTIONS.find((o) => o[0] === level);

  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 }}>Pick your target CMMC level and a few details. Your level sets which practices we assess; the rest lets us tailor your results and quote.</p>
        </div>
      </section>

      <window.Section bg="#fff" pad="40px 0 84px">
        <form onSubmit={(e) => { e.preventDefault(); onSubmit({ ...f, level }); }} style={{ maxWidth: 860, margin: '0 auto' }}>
          {/* TARGET LEVEL — drives the evaluation */}
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: EV.g400, marginBottom: 14 }}>Target CMMC level</div>
          <div style={{ background: '#fff', border: `1px solid ${EV.g200}`, padding: '24px', marginBottom: 28 }}>
            <p style={{ fontSize: 12.5, color: EV.g500, lineHeight: 1.55, margin: '0 0 16px' }}>This is the key choice — the evaluation asks only the NIST SP 800-171 practices that apply to the level you select.</p>
            <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
              {LEVEL_OPTIONS.map(([id, name, count, desc]) => {
                const on = level === id;
                return (
                  <button type="button" key={id} onClick={() => setLevel(id)} aria-pressed={on}
                    style={{ display: 'flex', flexDirection: 'column', gap: 8, textAlign: 'left', cursor: 'pointer', fontFamily: EFT, background: on ? EV.purpleSubtle : '#fff', border: `1.5px solid ${on ? EV.purple : EV.g200}`, borderRadius: 8, padding: '18px 16px', transition: 'all 150ms' }}>
                    <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                      <span style={{ width: 20, height: 20, borderRadius: '50%', border: `1.5px solid ${on ? EV.purple : EV.g300}`, background: on ? EV.purple : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        {on && <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#fff' }}></span>}
                      </span>
                      <span style={{ fontSize: 11, fontWeight: 700, color: on ? EV.purple : EV.g400, fontFamily: "'JetBrains Mono', monospace" }}>{count}</span>
                    </span>
                    <span style={{ fontSize: 14.5, fontWeight: 800, color: EV.black, letterSpacing: '-0.01em', lineHeight: 1.2 }}>{name}</span>
                    <span style={{ fontSize: 12, color: EV.g500, lineHeight: 1.45 }}>{desc}</span>
                  </button>
                );
              })}
            </div>
            {lvlMeta && <p style={{ fontSize: 12.5, color: EV.g500, margin: '14px 0 0' }}>Selected: <strong style={{ color: EV.purple }}>{lvlMeta[1]}</strong> · the evaluation will cover the {lvlMeta[2]} that apply at this level.</p>}
          </div>

          <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 Defense Systems' })}
              {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: 16 }}>
            <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 timeline')}
            </div>
            <div><label style={evLabel}>Systems & services in scope (CUI enclave)</label><textarea style={{ ...evInput, minHeight: 76, resize: 'vertical' }} value={f.systems} onChange={(e) => set('systems', e.target.value)} placeholder="e.g. GCC High tenant, engineering network, on-prem file shares handling CUI…" /></div>
            {text('certs', 'Existing certifications (optional)', { placeholder: 'e.g. ISO 27001, NIST 800-171 self-assessment, none yet' })}
          </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 }}>Level-aware questions · about 12 minutes · saved automatically</p>
        </form>
      </window.Section>
    </div>
  );
};

/* ── PAGE ────────────────────────────────────────────────── */
const EvaluationCMMCPage = ({ 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, level }
  const [resume, setResume] = React.useState(null);
  const [seed, setSeed] = React.useState(null);

  React.useEffect(() => {
    try { setUser(window.TK_CMMC.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_CMMC.getUser()); setStage('scope'); window.scrollTo({ top: 0 }); }
    else { setGate(true); }
  };
  const onGateSubmit = (form) => {
    window.TK_CMMC.storeLead({ ...form, source: 'evaluation' });
    try { sessionStorage.setItem('verigo_contact_ok', '1'); } catch (e) {}
    setUser(window.TK_CMMC.getUser());
    setGate(false);
    setStage('scope');
    window.scrollTo({ top: 0 });
  };
  const onScopeSubmit = (form) => {
    const level = Number(form.level) || 2;
    window.TK_CMMC.storeLead({ ...form, level: 'Level ' + level, source: 'evaluation-scope' });
    setUser(window.TK_CMMC.getUser());
    setScopeData({ form, level });
    setSeed({ answers: {}, step: 0 });
    saveProg({ stage: 'quiz', scope: form, level, 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, level: Number(p.level) || 2 });
    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 level = scopeData ? scopeData.level : 2;

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

      {gate && (
        <window.LeadCaptureModal
          icon="gauge"
          eyebrow="CMMC 2.0 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 your target level, 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, { EvaluationCMMCPage });
