// EvaluationHITRUST.jsx — Verigo Global: HITRUST CSF online readiness evaluation (assessment-driven, resumable)
const { V: EV, MAXW: EMW, FONT: EFT } = window;

/* ── PROGRESS PERSISTENCE ─────────────────────────────────── */
const H_PROG_KEY = 'verigo_hitrust_eval';
const hLoadProg = () => { try { return JSON.parse(localStorage.getItem(H_PROG_KEY) || 'null'); } catch (e) { return null; } };
const hSaveProg = (p) => { try { localStorage.setItem(H_PROG_KEY, JSON.stringify(p)); } catch (e) {} };
const hClearProg = () => { try { localStorage.removeItem(H_PROG_KEY); } catch (e) {} };

const hPreviewThemes = [
  ['lock', '01 · Access Control', 58],
  ['network', '09 · Comms & Ops', 64],
  ['zap', '11 · Incident Mgmt', 72],
  ['heart', '13 · Privacy', 44],
];

/* ── RESUME BANNER ───────────────────────────────────────── */
const HResumeBanner = ({ 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 assess = prog.assessment ? prog.assessment.toUpperCase() : '';
  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 + ' · ' : ''}{assess ? assess + ' · ' : ''}{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 ───────────────────────────────────── */
const HScorePreview = () => (
  <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 · i1</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% 63%, ${EV.g100} 63% 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 }}>63</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 }}>54 of 147 references need attention.</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {hPreviewThemes.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 HEvalIntro = ({ onStart, onNav, resume, onResume, onStartOver }) => {
  const steps = [
    ['target', 'Pick your assessment type', 'Choose e1, i1, or r2 — your choice tailors the evaluation to the categories and depth that apply to that assessment.'],
    ['gauge', 'Instant scoring', 'Get a maturity score with a category-by-category breakdown showing exactly where you stand against the CSF.'],
    ['flag', 'Mapped action plan', 'Every gap links straight to the toolkit document or control reference that closes it — so you know the next move for MyCSF.'],
  ];
  return (
    <div>
      {resume && <HResumeBanner 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:hitrust')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#7A7A8A', fontSize: 13, fontWeight: 600, padding: 0, fontFamily: EFT }}>HITRUST 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> Assessment-aware · ~10 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 HITRUST.
              </h1>
              <p style={{ fontSize: 19, color: EV.g600, lineHeight: 1.6, margin: '0 0 28px', maxWidth: 560 }}>
                Measure your current state against the HITRUST CSF for the assessment type you're targeting. Pick your assessment type in scope and the evaluation asks only the categories and controls 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>
            <HScorePreview />
          </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 \u201cwhere do we even stand?\u201d 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_HITRUST = {
  industry: ['Healthcare provider', 'Health plan / payer', 'Health IT / SaaS', 'Managed services / BPO', 'Life sciences', 'Professional services', 'Other'],
  employees: ['1–50', '51–200', '201–1,000', '1,000+'],
  region: ['United States', 'United Kingdom', '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'],
};

// HITRUST assessment types — the key scope choice that drives the evaluation.
const HITRUST_ASSESS_OPTIONS = [
  ['e1', 'e1 — Essentials', '44 requirements', '1-year validity', 'Foundational cybersecurity hygiene — fastest path to a HITRUST certificate.'],
  ['i1', 'i1 — Implemented', '182 requirements', '1-year validity', 'Leading security practices and threat-adaptive controls for moderate assurance.'],
  ['r2', 'r2 — Risk-based', '200+ requirements', '2-year validity', 'Tailored, risk-based controls for the highest assurance and full certification.'],
];

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 HScopeForm = ({ onSubmit, onBack, saved }) => {
  const u = (() => { try { return window.TK_HITRUST.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_HITRUST.industry[0], employees: sv.employees || u.employees || SCOPE_FIELDS_HITRUST.employees[0],
    region: sv.region || u.region || SCOPE_FIELDS_HITRUST.region[0], locations: sv.locations || u.locations || SCOPE_FIELDS_HITRUST.locations[0],
    systems: sv.systems || u.systems || '', certs: sv.certs || u.certs || '', target: sv.target || u.target || SCOPE_FIELDS_HITRUST.target[1],
  });
  const [assessment, setAssessment] = React.useState(() => (saved && saved.assessment) ? saved.assessment : 'i1');
  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_HITRUST[k].map((o) => <option key={o}>{o}</option>)}</select></div>;
  const chosen = HITRUST_ASSESS_OPTIONS.find((o) => o[0] === assessment);

  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 HITRUST assessment type — that choice sets which categories we evaluate. Then fill in a few details to tailor your results.</p>
        </div>
      </section>

      <window.Section bg="#fff" pad="40px 0 84px">
        <form onSubmit={(e) => { e.preventDefault(); onSubmit({ ...f, assessment }); }} style={{ maxWidth: 860, margin: '0 auto' }}>
          {/* TARGET ASSESSMENT TYPE */}
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: EV.g400, marginBottom: 14 }}>Target assessment type</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 CSF categories and controls that apply to the assessment type you select.</p>
            <div className="vg-grid-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
              {HITRUST_ASSESS_OPTIONS.map(([id, name, reqs, validity, desc]) => {
                const on = assessment === id;
                return (
                  <button type="button" key={id} onClick={() => setAssessment(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: 17, fontWeight: 800, color: on ? EV.orange : EV.g400, fontFamily: "'JetBrains Mono', monospace", textTransform: 'uppercase', letterSpacing: '-0.01em' }}>{id}</span>
                    </span>
                    <span style={{ fontSize: 14.5, fontWeight: 800, color: EV.black, letterSpacing: '-0.01em', lineHeight: 1.2 }}>{name.split(' — ')[1]}</span>
                    <span style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      <span style={{ fontSize: 11, fontWeight: 700, color: EV.purple, background: EV.purpleSubtle, padding: '2px 7px', borderRadius: 4 }}>{reqs}</span>
                      <span style={{ fontSize: 11, fontWeight: 700, color: EV.g500, background: EV.g100, padding: '2px 7px', borderRadius: 4 }}>{validity}</span>
                    </span>
                    <span style={{ fontSize: 12, color: EV.g500, lineHeight: 1.45 }}>{desc}</span>
                  </button>
                );
              })}
            </div>
            {chosen && <p style={{ fontSize: 12.5, color: EV.g500, margin: '14px 0 0' }}>Selected: <strong style={{ color: EV.purple }}>{chosen[1]}</strong> · the evaluation will cover the categories in scope for this assessment type.</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 Health 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</label><textarea style={{ ...evInput, minHeight: 76, resize: 'vertical' }} value={f.systems} onChange={(e) => set('systems', e.target.value)} placeholder="e.g. EHR platform, patient portal, cloud infrastructure handling PHI/ePHI…" /></div>
            {text('certs', 'Existing certifications (optional)', { placeholder: 'e.g. HITRUST e1, SOC 2 Type II, 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 }}>Assessment-aware questions · about 10 minutes · saved automatically</p>
        </form>
      </window.Section>
    </div>
  );
};

/* ── PAGE ────────────────────────────────────────────────── */
const EvaluationHITRUSTPage = ({ onNav }) => {
  const [stage, setStage] = React.useState('intro');
  const [gate, setGate] = React.useState(false);
  const [results, setResults] = React.useState(null);
  const [user, setUser] = React.useState(null);
  const [scopeData, setScopeData] = React.useState(null);
  const [resume, setResume] = React.useState(null);
  const [seed, setSeed] = React.useState(null);

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

  const persist = (patch) => { const base = hLoadProg() || {}; hSaveProg({ ...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_HITRUST.getUser()); setStage('scope'); window.scrollTo({ top: 0 }); }
    else { setGate(true); }
  };
  const onGateSubmit = (form) => {
    window.TK_HITRUST.storeLead({ ...form, source: 'evaluation' });
    try { sessionStorage.setItem('verigo_contact_ok', '1'); } catch (e) {}
    setUser(window.TK_HITRUST.getUser());
    setGate(false);
    setStage('scope');
    window.scrollTo({ top: 0 });
  };
  const onScopeSubmit = (form) => {
    const assessment = form.assessment || 'i1';
    window.TK_HITRUST.storeLead({ ...form, source: 'evaluation-scope' });
    setUser(window.TK_HITRUST.getUser());
    setScopeData({ form, assessment });
    setSeed({ answers: {}, step: 0 });
    hSaveProg({ stage: 'quiz', scope: form, assessment, 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, assessment: p.assessment || 'i1' });
    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 = () => { hClearProg(); setResume(null); setResults(null); setScopeData(null); setSeed(null); setStage('intro'); requestStart(); };

  const assessment = scopeData ? scopeData.assessment : 'i1';

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

      {gate && (
        <window.LeadCaptureModal
          icon="gauge"
          eyebrow="HITRUST CSF 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 assessment type, 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, { EvaluationHITRUSTPage });
