// evaluation-iso42001-engine.jsx — Verigo Global: ISO 42001 readiness evaluation engine
// Questions, scoring, quiz + results components, and a results-PDF generator.
// Exposes window.EVAL42
const { V: G2V, MAXW: G2MW, FONT: G2FT } = window;

/* ── QUESTION BANK — 5 themes × statements ───────────────── */
const QUESTIONS42 = [
  { theme: 'Policy & Organization', icon: 'briefcase', controls: 8,
    docs: ['AI Management Policy', 'AI Roles & Responsibilities Policy'],
    q: [
      'An approved, top-level AI Management Policy is in place and reviewed at least annually.',
      'AI governance roles and responsibilities are formally defined and assigned.',
      'Staff know how and where to report AI-related concerns or incidents.',
    ] },
  { theme: 'Impact Assessment', icon: 'target', controls: 3,
    docs: ['AI System Impact Assessment Policy', 'AI System Impact Assessment Procedure'],
    q: [
      'A documented impact assessment process runs before any AI system reaches production.',
      'Impact assessments consider effects on individuals, groups, and society, not just technical risk.',
    ] },
  { theme: 'AI System Life Cycle', icon: 'layers', controls: 10,
    docs: ['AI System Lifecycle Policy', 'Model Validation & Verification Procedure'],
    q: [
      'AI systems follow a defined life cycle from requirements through deployment and retirement.',
      'Models are verified and validated for accuracy and robustness before release.',
      'AI system operation is monitored and events are logged for review.',
    ] },
  { theme: 'Data & Transparency', icon: 'doc', controls: 9,
    docs: ['Data Governance Policy for AI', 'Data Quality & Provenance Procedure'],
    q: [
      'Data used to train and operate AI systems has documented quality and provenance controls.',
      'Interested parties receive appropriate transparency about AI system use and limitations.',
      'AI incidents and malfunctions are communicated to affected parties in a defined way.',
    ] },
  { theme: 'Use & Relationships', icon: 'compass', controls: 8,
    docs: ['Responsible AI Use Policy', 'AI Supplier & Third-Party Policy'],
    q: [
      'Intended use and prohibited use cases are documented for each AI system.',
      'Responsibilities between your organization and AI suppliers or customers are clearly allocated.',
    ] },
];

const OPTIONS42 = [
  ['Not started', 0],
  ['Partial', 1],
  ['Largely', 2],
  ['Fully', 3],
];

const BANDS42 = [
  [0, 'Initial', G2V.orange, 'Foundations are largely missing — start with the core policy and risk set.'],
  [40, 'Developing', G2V.orange, 'Key pieces exist, but real gaps remain before certification is viable.'],
  [60, 'Established', G2V.purple, 'A working AIMS is in place — focus on closing the weaker themes.'],
  [80, 'Optimized', G2V.purple, 'Strong posture — fine-tune evidence and keep it continuous.'],
];
const bandFor42 = (pct) => { let b = BANDS42[0]; BANDS42.forEach((x) => { if (pct >= x[0]) b = x; }); return b; };

function computeResults42(answers) {
  const themes = QUESTIONS42.map((t, ti) => {
    const max = t.q.length * 3;
    let sum = 0;
    t.q.forEach((_, qi) => { sum += (answers[ti + '-' + qi] || 0); });
    const pct = Math.round((sum / max) * 100);
    return { theme: t.theme, icon: t.icon, docs: t.docs, controls: t.controls, pct, gaps: Math.round((1 - pct / 100) * t.controls) };
  });
  const totSum = themes.reduce((a, t) => a + (t.pct), 0);
  const overall = Math.round(totSum / themes.length);
  const gaps = themes.reduce((a, t) => a + t.gaps, 0);
  return { themes, overall, gaps, band: bandFor42(overall) };
}

/* ── SEGMENTED MATURITY CONTROL ──────────────────────────── */
const Segmented42 = ({ value, onChange }) => (
  <div className="vg-grid-4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
    {OPTIONS42.map(([label, val]) => {
      const on = value === val;
      return (
        <button key={val} type="button" onClick={() => onChange(val)}
          style={{ fontFamily: G2FT, fontSize: 13, fontWeight: 700, padding: '10px 6px', cursor: 'pointer', textAlign: 'center', background: on ? G2V.purple : '#fff', color: on ? '#fff' : G2V.g600, border: `1.5px solid ${on ? G2V.purple : G2V.g200}`, transition: 'all 120ms' }}>
          {label}
        </button>
      );
    })}
  </div>
);

/* ── QUIZ ────────────────────────────────────────────────── */
const EvalQuiz42 = ({ onComplete, onExit }) => {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const total = QUESTIONS42.length;
  const cur = QUESTIONS42[step];
  const set = (qi, v) => setAnswers((a) => ({ ...a, [step + '-' + qi]: v }));
  const stepDone = cur.q.every((_, qi) => answers[step + '-' + qi] !== undefined);
  const answeredCount = Object.keys(answers).length;
  const totalQ = QUESTIONS42.reduce((a, t) => a + t.q.length, 0);
  const progress = Math.round((answeredCount / totalQ) * 100);

  const next = () => { if (step < total - 1) { setStep(step + 1); window.scrollTo({ top: 0 }); } else { onComplete(computeResults42(answers)); } };
  const back = () => { if (step > 0) { setStep(step - 1); window.scrollTo({ top: 0 }); } else { onExit(); } };

  return (
    <window.Section bg={G2V.g50} pad="48px 0 96px">
      <div style={{ maxWidth: 820, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: G2V.g400 }}>Section {step + 1} of {total}</span>
          <span style={{ fontSize: 12, fontWeight: 700, color: G2V.purple, fontFamily: "'JetBrains Mono', monospace" }}>{progress}% complete</span>
        </div>
        <div style={{ height: 6, background: G2V.g200, marginBottom: 28, overflow: 'hidden' }}>
          <div style={{ width: progress + '%', height: '100%', background: G2V.purple, transition: 'width 200ms' }}></div>
        </div>

        <div style={{ background: '#fff', border: `1px solid ${G2V.g200}`, padding: '32px 36px 36px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
            <div style={{ width: 42, height: 42, background: G2V.purpleSubtle, color: G2V.purple, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <window.Icon name={cur.icon} size={22} />
            </div>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: G2V.g400 }}>Annex A theme</div>
              <h2 style={{ fontSize: 22, fontWeight: 800, color: G2V.black, margin: 0, fontFamily: G2FT, letterSpacing: '-0.02em' }}>{cur.theme}</h2>
            </div>
          </div>
          <p style={{ fontSize: 13.5, color: G2V.g500, margin: '0 0 24px', lineHeight: 1.55 }}>For each statement, choose how completely it reflects your organization today.</p>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
            {cur.q.map((text, qi) => (
              <div key={qi} style={{ borderTop: qi ? `1px solid ${G2V.g100}` : 'none', paddingTop: qi ? 22 : 0 }}>
                <div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
                  <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 12, fontWeight: 700, color: G2V.orange, flexShrink: 0, marginTop: 2 }}>{String(qi + 1).padStart(2, '0')}</span>
                  <p style={{ fontSize: 15.5, fontWeight: 600, color: G2V.g800, margin: 0, lineHeight: 1.5 }}>{text}</p>
                </div>
                <div style={{ paddingLeft: 24 }}>
                  <Segmented42 value={answers[step + '-' + qi]} onChange={(v) => set(qi, v)} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 24 }}>
          <window.Btn kind="ghost" onClick={back}>{step === 0 ? 'Exit' : 'Back'}</window.Btn>
          <window.Btn kind="primary" onClick={next} style={{ opacity: stepDone ? 1 : 0.45, pointerEvents: stepDone ? 'auto' : 'none' }}>
            {step === total - 1 ? 'See my results' : 'Next section'} <window.Icon name="arrow" size={16} color="#fff" />
          </window.Btn>
        </div>
        {!stepDone && <p style={{ textAlign: 'right', fontSize: 12.5, color: G2V.g400, marginTop: 10 }}>Answer all statements to continue.</p>}
      </div>
    </window.Section>
  );
};

/* ── RESULTS ─────────────────────────────────────────────── */
const Donut42 = ({ pct, color }) => (
  <div style={{ width: 168, height: 168, borderRadius: '50%', background: `conic-gradient(${color} 0% ${pct}%, ${G2V.g100} ${pct}% 100%)`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
    <div style={{ width: 128, height: 128, borderRadius: '50%', background: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
      <span style={{ fontSize: 48, fontWeight: 800, color: G2V.black, fontFamily: G2FT, letterSpacing: '-0.03em', lineHeight: 1 }}>{pct}</span>
      <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: G2V.g400, marginTop: 4 }}>/ 100</span>
    </div>
  </div>
);

const EvalResults42 = ({ results, user, onNav, onRetake }) => {
  const { themes, overall, gaps, band } = results;
  const [, label, bandColor, bandDesc] = band;
  const sorted = [...themes].sort((a, b) => a.pct - b.pct);
  const focus = sorted.filter((t) => t.pct < 80);
  const MODULES = window.TK_ISO42001.QUOTE_MODULES;
  const reco = new Set(['tailor']);
  if (overall < 80) reco.add('guidance');
  if (overall < 60) { reco.add('impl'); reco.add('preaudit'); }
  themes.forEach((t) => {
    if (t.pct < 60) {
      if (t.theme === 'Impact Assessment') reco.add('impact');
      if (t.theme === 'AI System Life Cycle') reco.add('preaudit');
    }
  });
  const recoIds = [...reco];
  const recoModules = MODULES.filter((m) => reco.has(m.id));
  const goBuild = () => { try { localStorage.setItem('verigo_reco_iso42001', JSON.stringify(recoIds)); } catch (e) {} onNav('checkout'); };

  return (
    <div>
      <section style={{ background: G2V.purpleDark, position: 'relative', overflow: 'hidden' }}>
        <window.GeoWatermark color={G2V.orange} style={{ top: -40, right: 40, width: 360, height: 340, opacity: 0.16 }} />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: G2MW, margin: '0 auto', padding: '56px 32px 60px' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(255,255,255,0.12)', color: '#fff', fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', padding: '6px 13px', marginBottom: 24 }}>
            <window.Icon name="gauge" size={14} color="#fff" /> Your readiness report
          </div>
          <div className="vg-detail-grid" style={{ display: 'grid', gridTemplateColumns: '168px 1fr', gap: 40, alignItems: 'center' }}>
            <Donut42 pct={overall} color="#fff" />
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginBottom: 8 }}>Overall maturity · {label}</div>
              <h1 className="vg-hero-title" style={{ fontSize: 38, fontWeight: 800, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1.1, margin: '0 0 14px', fontFamily: G2FT, maxWidth: 640 }}>
                {overall >= 80 ? 'You\u2019re close to audit-ready.' : overall >= 60 ? 'A solid base, with clear gaps to close.' : 'There\u2019s real groundwork to do first.'}
              </h1>
              <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.7)', lineHeight: 1.6, margin: 0, maxWidth: 600 }}>
                {bandDesc} We estimate <strong style={{ color: '#fff' }}>~{gaps} of 38 controls</strong> need attention before a Stage 2 audit.
                {user && user.company ? ` Prepared for ${user.company}.` : ''}
              </p>
            </div>
          </div>
        </div>
      </section>

      <window.Section bg="#fff" pad="72px 0 64px">
        <window.SectionHeader overline="By control theme" align="left"
          title="Where you stand across Annex A"
          sub="Your maturity in each of the five ISO 42001 control themes, scored from your answers." maxSub={620} />
        <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '28px 56px' }}>
          {themes.map((t, i) => {
            const c = t.pct < 60 ? G2V.orange : G2V.purple;
            return (
              <div key={i}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 15, fontWeight: 700, color: G2V.g800, fontFamily: G2FT }}>
                    <window.Icon name={t.icon} size={18} color={G2V.purple} />{t.theme}
                  </span>
                  <span style={{ fontSize: 15, fontWeight: 800, color: c, fontFamily: "'JetBrains Mono', monospace" }}>{t.pct}%</span>
                </div>
                <div style={{ height: 9, background: G2V.g100, overflow: 'hidden' }}>
                  <div style={{ width: t.pct + '%', height: '100%', background: c, transition: 'width 400ms' }}></div>
                </div>
                <div style={{ fontSize: 12.5, color: G2V.g500, marginTop: 7 }}>~{t.gaps} of {t.controls} controls need attention</div>
              </div>
            );
          })}
        </div>
      </window.Section>

      <window.Section bg={G2V.g50} pad="64px 0 72px">
        <window.SectionHeader overline="Your next steps" align="left"
          title="A plan mapped straight to the toolkit"
          sub="Start with your weakest themes. Each links to the toolkit documents that close the gap fastest." maxSub={640} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {focus.length === 0 && (
            <div style={{ background: '#fff', border: `1px solid ${G2V.g200}`, padding: '24px 28px', display: 'flex', alignItems: 'center', gap: 14 }}>
              <window.Icon name="check" size={24} color={G2V.purple} />
              <div style={{ fontSize: 15.5, fontWeight: 600, color: G2V.g800 }}>Every theme scored 80%+ — you\u2019re in strong shape. A practitioner can help validate evidence and close the final details.</div>
            </div>
          )}
          {focus.map((t, i) => (
            <div key={i} style={{ background: '#fff', border: `1px solid ${G2V.g200}`, padding: '24px 28px', display: 'grid', gridTemplateColumns: '44px 1fr auto', gap: 20, alignItems: 'center' }}>
              <div style={{ width: 44, height: 44, background: G2V.purpleSubtle, color: G2V.purple, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: "'JetBrains Mono', monospace", fontSize: 16, fontWeight: 800 }}>{i + 1}</div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                  <h3 style={{ fontSize: 17, fontWeight: 700, color: G2V.black, margin: 0, fontFamily: G2FT, letterSpacing: '-0.01em' }}>{t.theme}</h3>
                  <span style={{ fontSize: 11, fontWeight: 700, padding: '3px 9px', background: t.pct < 60 ? G2V.orangeSubtle : G2V.purpleSubtle, color: t.pct < 60 ? G2V.orange : G2V.purple, fontFamily: "'JetBrains Mono', monospace" }}>{t.pct}%</span>
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {t.docs.map((d, di) => (
                    <span key={di} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: G2V.g700, background: G2V.g50, border: `1px solid ${G2V.g200}`, padding: '6px 11px' }}>
                      <window.Icon name="doc" size={14} color={G2V.purple} />{d}
                    </span>
                  ))}
                </div>
              </div>
              <window.Btn kind="ghostBrand" onClick={() => onNav('toolkit:iso42001')} style={{ whiteSpace: 'nowrap' }}>Open toolkit <window.Icon name="arrow" size={15} color={G2V.purple} /></window.Btn>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 32 }}>
          <window.Btn kind="primary" onClick={() => window.EVAL42.generateEvalPDF(results, user)}><window.Icon name="doc" size={16} color="#fff" /> Download my results (PDF)</window.Btn>
          <window.Btn kind="ghost" onClick={onRetake}>Retake the evaluation</window.Btn>
        </div>
      </window.Section>

      <window.Section bg="#fff" pad="72px 0 64px">
        <window.SectionHeader overline="Recommended next step" align="left"
          title="Build a package that closes your gaps"
          sub="There are no fixed bundles. Based on your results we’ve pre-selected the options most likely to close your gaps fastest — add or remove anything, see your price update live, and download a custom quote." maxSub={720} />
        <div className="vg-grid-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 28 }}>
          {recoModules.map((m, i) => (
            <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start', border: `1px solid ${G2V.g200}`, padding: '18px 20px', background: '#fff' }}>
              <div style={{ width: 38, height: 38, background: G2V.purpleSubtle, color: G2V.purple, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><window.Icon name="check" size={20} color={G2V.purple} /></div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 700, color: G2V.black, fontFamily: G2FT }}>{m.name}</div>
                <div style={{ fontSize: 13, color: G2V.g500, lineHeight: 1.5, marginTop: 3 }}>{m.desc}</div>
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <window.Btn kind="primary" onClick={goBuild}>Build my custom package <window.Icon name="arrow" size={16} color="#fff" /></window.Btn>
          <span style={{ fontSize: 13, color: G2V.g500 }}>Pick your options, see the price, then download a custom quote.</span>
        </div>
      </window.Section>

      <window.Section bg={G2V.g50} pad="64px 0 0">
        <window.CTABand
          overline="Turn the score into certification"
          title="Have a practitioner walk you through your results"
          body="Your readiness report is a starting point. Our team can validate every gap, tailor the toolkit to your AI systems, and take you all the way to a certified AIMS."
          primary="Talk to a practitioner" onNav={onNav} dest="contact" />
      </window.Section>
    </div>
  );
};

/* ── RESULTS PDF ─────────────────────────────────────────── */
function generateEvalPDF42(results, user) {
  const lib = window.jspdf;
  if (!lib || !lib.jsPDF) { alert('PDF engine is still loading — please try again in a moment.'); return; }
  const { themes, overall, gaps, band } = results;
  const doc = new lib.jsPDF({ unit: 'pt', format: 'a4' });
  const W = doc.internal.pageSize.getWidth();
  const H = doc.internal.pageSize.getHeight();
  const M = 50;
  const PURPLE = [91, 46, 145], ORANGE = [232, 98, 42], INK = [30, 30, 46], GREY = [120, 120, 134];
  let y = 100;

  doc.setFillColor(...PURPLE); doc.rect(0, 0, W, 70, 'F');
  doc.setFillColor(...ORANGE); doc.rect(W - M - 11, 28, 11, 11, 'F');
  doc.setTextColor(255, 255, 255); doc.setFont('helvetica', 'bold'); doc.setFontSize(15);
  doc.text('VERIGO GLOBAL', M, 33);
  doc.setFont('helvetica', 'normal'); doc.setFontSize(8.5); doc.setTextColor(214, 204, 232);
  doc.text('Compliance by Design', M, 49);
  doc.setTextColor(255, 255, 255); doc.setFontSize(8.5);
  doc.text('ISO/IEC 42001:2023', W - M - 20, 35, { align: 'right' });

  doc.setTextColor(...INK); doc.setFont('helvetica', 'bold'); doc.setFontSize(21);
  doc.text('ISO 42001 Readiness Report', M, y); y += 12;
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M, y, M + 54, y); y += 24;

  doc.setFont('helvetica', 'bold'); doc.setFontSize(40); doc.setTextColor(...PURPLE);
  doc.text(String(overall), M, y + 14);
  doc.setFontSize(11); doc.setTextColor(...GREY); doc.setFont('helvetica', 'normal');
  doc.text('/ 100', M + 58, y + 14);
  doc.setFont('helvetica', 'bold'); doc.setFontSize(13); doc.setTextColor(...INK);
  doc.text('Overall maturity: ' + band[1], M + 130, y - 2);
  doc.setFont('helvetica', 'normal'); doc.setFontSize(10); doc.setTextColor(...GREY);
  doc.splitTextToSize('~' + gaps + ' of 38 controls need attention before a Stage 2 audit. ' + band[3], W - M - (M + 130)).forEach((ln, i) => doc.text(ln, M + 130, y + 14 + i * 13));
  y += 56;
  if (user && (user.company || user.name)) {
    doc.setDrawColor(224, 224, 232); doc.setLineWidth(0.5); doc.line(M, y, W - M, y); y += 16;
    doc.setFontSize(9); doc.setTextColor(...PURPLE); doc.setFont('helvetica', 'bold');
    doc.text('Prepared for ' + (user.company || user.name), M, y);
    doc.setFont('helvetica', 'normal'); doc.setTextColor(...GREY);
    doc.text(new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }), W - M, y, { align: 'right' });
    y += 22;
  }

  doc.setFont('helvetica', 'bold'); doc.setFontSize(12.5); doc.setTextColor(...PURPLE);
  doc.text('Maturity by control theme', M, y); y += 6;
  doc.setDrawColor(...PURPLE); doc.setLineWidth(0.8); doc.line(M, y, W - M, y); y += 20;
  const barX = M + 200, barW = W - M - barX;
  themes.forEach((t) => {
    doc.setFont('helvetica', 'bold'); doc.setFontSize(10.5); doc.setTextColor(...INK);
    doc.text(t.theme, M, y + 3);
    doc.setFillColor(237, 237, 245); doc.rect(barX, y - 7, barW, 10, 'F');
    const col = t.pct < 60 ? ORANGE : PURPLE;
    doc.setFillColor(...col); doc.rect(barX, y - 7, barW * (t.pct / 100), 10, 'F');
    doc.setFont('helvetica', 'bold'); doc.setFontSize(10); doc.setTextColor(...col);
    doc.text(t.pct + '%', W - M, y + 3, { align: 'right' });
    y += 26;
  });
  y += 6;

  const focus = [...themes].sort((a, b) => a.pct - b.pct).filter((t) => t.pct < 80);
  if (focus.length) {
    doc.setFont('helvetica', 'bold'); doc.setFontSize(12.5); doc.setTextColor(...PURPLE);
    doc.text('Recommended next steps', M, y); y += 6;
    doc.setDrawColor(...PURPLE); doc.setLineWidth(0.8); doc.line(M, y, W - M, y); y += 18;
    focus.forEach((t, i) => {
      if (y > H - 90) { doc.addPage(); y = 60; }
      doc.setFont('helvetica', 'bold'); doc.setFontSize(10.5); doc.setTextColor(...INK);
      doc.text((i + 1) + '. ' + t.theme + ' (' + t.pct + '%)', M, y); y += 14;
      doc.setFont('helvetica', 'normal'); doc.setFontSize(9.5); doc.setTextColor(...GREY);
      doc.splitTextToSize('Toolkit documents: ' + t.docs.join(', '), W - 2 * M - 14).forEach((ln) => { doc.text(ln, M + 14, y); y += 12; });
      y += 8;
    });
  }

  const total = doc.internal.getNumberOfPages();
  for (let i = 1; i <= total; i++) {
    doc.setPage(i);
    doc.setDrawColor(224, 224, 232); doc.setLineWidth(0.5); doc.line(M, H - 38, W - M, H - 38);
    doc.setFont('helvetica', 'normal'); doc.setFontSize(8); doc.setTextColor(150, 150, 160);
    doc.text('© 2026 Verigo Global · Readiness self-assessment — indicative, not a formal audit', M, H - 24);
    doc.text(i + ' / ' + total, W - M, H - 24, { align: 'right' });
  }
  doc.save('Verigo-ISO42001-Readiness-Report.pdf');
}

window.EVAL42 = { QUESTIONS: QUESTIONS42, OPTIONS: OPTIONS42, BANDS: BANDS42, computeResults: computeResults42, EvalQuiz: EvalQuiz42, EvalResults: EvalResults42, generateEvalPDF: generateEvalPDF42 };
Object.assign(window, { EvalQuiz42, EvalResults42 });
