// resource-pdf-generators.jsx — Full-blown branded PDF templates for all 6 free downloads
// Exposes window.RC_PDF.generate(item)

(function() {

const PURPLE=[91,46,145], ORANGE=[232,98,42], INK=[30,30,46], GREY=[120,120,134], LIGHT=[245,245,247], MID=[200,200,215];

/* ── SHARED HELPERS ──────────────────────────────────────── */
function makeDoc() {
  const doc = new window.jspdf.jsPDF({ unit:'pt', format:'a4' });
  const W = doc.internal.pageSize.getWidth();
  const H = doc.internal.pageSize.getHeight();
  const M = 50;
  let y = 0;
  let pageNum = 0;

  const newPage = () => {
    doc.addPage();
    pageNum++;
    header(doc, W, H, M, _title, _subtitle);
    y = 96;
  };
  const ensureSpace = (h) => { if (y + h > H - 60) newPage(); };

  let _title = '', _subtitle = '';
  const setMeta = (t, s) => { _title = t; _subtitle = s; };

  function header(doc, W, H, M, t, s) {
    doc.setFillColor(...PURPLE); doc.rect(0,0,W,62,'F');
    doc.setFillColor(...ORANGE); doc.rect(W-M-10,22,10,10,'F');
    doc.setTextColor(255,255,255); doc.setFont('helvetica','bold'); doc.setFontSize(13);
    doc.text('VERIGO GLOBAL',M,28);
    doc.setFont('helvetica','normal'); doc.setFontSize(8); doc.setTextColor(200,190,220);
    doc.text('Compliance by Design',M,42);
    if (t) { doc.setTextColor(255,255,255); doc.setFontSize(8); doc.text(t, W-M-10, 28, {align:'right'}); }
    if (s) { doc.setTextColor(200,190,220); doc.setFontSize(7.5); doc.text(s, W-M-10, 40, {align:'right'}); }
  }

  const startPage = (t, s) => {
    setMeta(t, s);
    header(doc, W, H, M, t, s);
    pageNum = 1;
    y = 96;
  };

  const footer = (doc, W, H, M, ref) => {
    const total = doc.internal.getNumberOfPages();
    for (let i=1;i<=total;i++) {
      doc.setPage(i);
      doc.setDrawColor(...MID); doc.setLineWidth(0.5); doc.line(M,H-36,W-M,H-36);
      doc.setFont('helvetica','normal'); doc.setFontSize(7.5); doc.setTextColor(160,160,175);
      doc.text('© 2026 Verigo Global · Free resource · verigoglobal.com' + (ref?' · '+ref:''), M, H-22);
      doc.text(i+' / '+total, W-M, H-22, {align:'right'});
    }
  };

  const sectionHead = (txt) => {
    ensureSpace(28);
    doc.setFont('helvetica','bold'); doc.setFontSize(11); doc.setTextColor(...PURPLE);
    doc.text(txt, M, y); y+=5;
    doc.setDrawColor(...PURPLE); doc.setLineWidth(0.8); doc.line(M,y,W-M,y); y+=14;
  };
  const subHead = (txt) => {
    ensureSpace(18);
    doc.setFont('helvetica','bold'); doc.setFontSize(10); doc.setTextColor(...INK);
    doc.text(txt, M, y); y+=13;
  };
  const body = (txt, indent=0) => {
    const lines = doc.splitTextToSize(txt, W-2*M-indent);
    ensureSpace(lines.length*13+4);
    doc.setFont('helvetica','normal'); doc.setFontSize(9.5); doc.setTextColor(...INK);
    lines.forEach(ln=>{ doc.text(ln, M+indent, y); y+=13; }); y+=2;
  };
  const note = (txt) => {
    const lines = doc.splitTextToSize(txt, W-2*M);
    ensureSpace(lines.length*12+4);
    doc.setFont('helvetica','italic'); doc.setFontSize(9); doc.setTextColor(...GREY);
    lines.forEach(ln=>{ doc.text(ln, M, y); y+=12; }); y+=2;
  };
  const colHead = (cols) => { // [{label,x,w}]
    doc.setFillColor(...LIGHT); doc.rect(M, y-10, W-2*M, 14, 'F');
    doc.setFont('helvetica','bold'); doc.setFontSize(8.5); doc.setTextColor(...GREY);
    cols.forEach(c=>doc.text(c.label, c.x+4, y));
    y+=10; doc.setDrawColor(...MID); doc.setLineWidth(0.3); doc.line(M,y,W-M,y); y+=4;
  };
  const row = (cells, cols, shade=false) => {
    const maxH = Math.max(...cells.map((c,i)=>doc.splitTextToSize(c,cols[i].w-8).length))*11+8;
    ensureSpace(maxH+2);
    if (shade) { doc.setFillColor(248,248,252); doc.rect(M,y-8,W-2*M,maxH+2,'F'); }
    doc.setFont('helvetica','normal'); doc.setFontSize(8.5); doc.setTextColor(...INK);
    cells.forEach((c,i)=>{ const ls=doc.splitTextToSize(c,cols[i].w-8); ls.forEach((l,j)=>doc.text(l,cols[i].x+4,y+j*11)); });
    doc.setDrawColor(230,230,240); doc.setLineWidth(0.3); doc.line(M,y+maxH-2,W-M,y+maxH-2);
    y+=maxH;
  };
  const check = (label, sub='', val='☐') => {
    ensureSpace(sub?30:18);
    doc.setFont('helvetica','normal'); doc.setFontSize(11); doc.setTextColor(...ORANGE); doc.text(val,M,y);
    doc.setFont('helvetica','normal'); doc.setFontSize(9.5); doc.setTextColor(...INK);
    doc.splitTextToSize(label,W-2*M-22).forEach((l,i)=>doc.text(l,M+22,y+i*13));
    y+=doc.splitTextToSize(label,W-2*M-22).length*13;
    if (sub) { doc.setFont('helvetica','italic'); doc.setFontSize(8.5); doc.setTextColor(...GREY); doc.splitTextToSize(sub,W-2*M-26).forEach(l=>{ doc.text(l,M+26,y); y+=12; }); }
    y+=4;
  };
  const space = (h=12) => { y+=h; };
  const divider = () => { ensureSpace(8); doc.setDrawColor(...LIGHT); doc.setLineWidth(0.8); doc.line(M,y,W-M,y); y+=12; };
  const badge = (label,x,yw,color=ORANGE) => { doc.setFillColor(...color); doc.rect(x,yw-8,doc.getTextWidth(label)+12,12,'F'); doc.setTextColor(255,255,255); doc.setFont('helvetica','bold'); doc.setFontSize(8); doc.text(label,x+6,yw); };

  return { doc, W, H, M, startPage, newPage, ensureSpace, sectionHead, subHead, body, note, colHead, row, check, space, divider, badge, footer, setMeta, getY:()=>y, setY:(v)=>{y=v;} };
}

/* ──────────────────────────────────────────────────────────── */
/* 1. SOC 2 READINESS CHECKLIST                               */
/* ──────────────────────────────────────────────────────────── */
function genSOC2Checklist(user) {
  const d = makeDoc();
  d.startPage('SOC 2 Readiness Checklist', 'AICPA · Trust Services Criteria 2017 (updated 2022)');
  const { doc, W, H, M, sectionHead, subHead, body, note, check, space, divider, footer, newPage, ensureSpace } = d;

  // Title block
  doc.setFont('helvetica','bold'); doc.setFontSize(24); doc.setTextColor(...INK);
  doc.text('SOC 2 Readiness Checklist', M, d.getY()); d.setY(d.getY()+10);
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,d.getY(),M+60,d.getY()); d.setY(d.getY()+18);
  doc.setFont('helvetica','normal'); doc.setFontSize(10); doc.setTextColor(...GREY);
  doc.text('Use this checklist before your SOC 2 Type I or Type II examination to identify control gaps.', M, d.getY()); d.setY(d.getY()+22);
  if (user && user.company) { doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE); doc.text('Prepared for: '+user.company, M, d.getY()); d.setY(d.getY()+8); }
  doc.setFont('helvetica','normal'); doc.setFontSize(9); doc.setTextColor(...GREY);
  doc.text('Date: '+new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'})+' · © 2026 Verigo Global', M, d.getY()); d.setY(d.getY()+20);
  divider();

  // Instructions
  sectionHead('How to use this checklist');
  body('For each control statement below, mark the status as: ☑ Fully implemented · ☒ Partially implemented · ☐ Not implemented. Anything marked ☒ or ☐ is a gap that should be remediated before your examination window opens. The checklist covers all five Trust Services Criteria; check only the categories in scope for your examination (Security is mandatory for all SOC 2 examinations).');
  space();

  // CC1–CC3
  sectionHead('CC1 · Control Environment');
  check('Management has formally defined and communicated integrity and ethical values, including a code of conduct acknowledged by all staff.','Evidence: Code of conduct, acknowledgment log, onboarding records.');
  check('The board or equivalent oversight body provides meaningful oversight of cybersecurity risk management.','Evidence: Board meeting minutes, CISO reporting structure, governance charter.');
  check('Security roles, reporting lines, and authorities are formally defined and communicated across the organization.','Evidence: RACI matrix, org chart, job descriptions with security responsibilities.');
  check('Personnel are recruited, developed, and evaluated with security responsibilities in mind.','Evidence: Job postings, performance review criteria, training completion records.');
  check('Individuals are held accountable for their control responsibilities through formal processes.','Evidence: Disciplinary procedure, performance management policy.');
  space();
  sectionHead('CC2 · Communication & Information');
  check('Quality, relevant information is available to support the functioning of internal controls.','Evidence: Risk register, control documentation, policy repository.');
  check('Security objectives, responsibilities, and risk appetite are communicated internally to relevant staff.','Evidence: Security awareness materials, all-hands communications, policy sign-offs.');
  check('Material cybersecurity information is communicated to external parties as appropriate.','Evidence: Customer privacy notices, vendor security requirements, breach notification procedures.');
  space();
  sectionHead('CC3 · Risk Assessment');
  check('Risk assessment objectives are specified with sufficient clarity to identify and assess information security risk.','Evidence: Risk assessment methodology document, scope definition.');
  check('Information security risks are identified and analyzed at defined intervals and upon significant change.','Evidence: Current risk register with threat, vulnerability, likelihood, and impact entries.');
  check('The potential for fraud is considered in the risk assessment process.','Evidence: Risk assessment records noting fraud scenarios, segregation of duties analysis.');
  check('Changes to the environment, technology, and business model are assessed for risk impact before implementation.','Evidence: Change management records with risk assessment fields.');
  space();
  newPage();
  sectionHead('CC4 · Monitoring Activities');
  check('Controls are monitored through a combination of ongoing activities and periodic evaluations.','Evidence: Monitoring schedule, automated alerting rules, quarterly review meeting minutes.');
  check('Deficiencies identified through monitoring are communicated to responsible parties and remediated.','Evidence: Deficiency log, corrective action records, management reporting.');
  space();
  sectionHead('CC5 · Control Activities');
  check('Control activities are selected and developed to mitigate risks to acceptable levels.','Evidence: Control matrix linking risks to controls, control testing results.');
  check('General technology controls are selected and developed to support the achievement of control objectives.','Evidence: Technology control inventory, IT GRC documentation, configuration baselines.');
  check('Control activities are deployed through policies and procedures that clearly specify what is required.','Evidence: Policy repository with effective dates, version history, and owner sign-offs.');
  space();
  sectionHead('CC6 · Logical & Physical Access Controls');
  check('Logical access security is implemented through identity management, MFA, and least-privilege entitlements.','Evidence: IdP configuration export, MFA enrolment report, entitlement review records.');
  check('New user access is registered and authorized before being granted.','Evidence: Access request tickets, approval records, provisioning logs.');
  check('Access rights are reviewed and recertified on a defined cadence (at least quarterly for privileged accounts).','Evidence: Access review reports, recertification attestations, revocation records.');
  check('Physical access to facilities and data centers is restricted and monitored.','Evidence: Badge access logs, visitor register, physical security assessments.');
  check('Boundary protection prevents unauthorized access from external networks.','Evidence: Firewall rulesets, network segmentation diagrams, penetration test results.');
  space();
  sectionHead('CC7 · System Operations');
  check('Vulnerabilities and configuration changes are detected through continuous scanning and monitoring.','Evidence: Vulnerability scan reports (dated), SIEM alerting rules, configuration management records.');
  check('Security events are monitored and evaluated for potential incidents.','Evidence: SIEM dashboards, alert triage logs, security operations runbooks.');
  check('Incidents are identified, declared, escalated, and documented through a formal process.','Evidence: Incident log, incident response procedure, post-incident review reports.');
  check('Systems recover from incidents through documented recovery procedures.','Evidence: Tested recovery runbooks, disaster recovery test results, RTO/RPO documentation.');
  space();
  newPage();
  sectionHead('CC8 · Change Management');
  check('Infrastructure, data, and software changes are authorized, designed, developed, tested, and approved before release.','Evidence: Change management records with CAB approvals, test results, and deployment confirmation.');
  space();
  sectionHead('CC9 · Risk Mitigation');
  check('Identified risks are addressed through mitigation, acceptance, transfer, or avoidance — with residual risk accepted at an appropriate authority.','Evidence: Risk treatment register with decisions, owners, and accepted residual risk.');
  check('Vendor and subservice organization risk is assessed and managed throughout the relationship.','Evidence: Vendor risk assessment records, third-party security reviews, contract security addenda.');
  divider();

  // Optional criteria
  sectionHead('Availability (A1) — Optional: include if in scope');
  check('System capacity is monitored and managed to meet availability commitments.','Evidence: Capacity monitoring dashboards, uptime SLAs, capacity planning records.');
  check('Backups are performed, encrypted, and restoration is tested at least annually.','Evidence: Backup schedules, encryption configs, restoration test reports.');
  check('Recovery plans are documented and tested to meet defined RTO and RPO targets.','Evidence: DR plan, BCP, test results with RTO/RPO outcomes.');
  space();
  sectionHead('Confidentiality (C1) — Optional: include if in scope');
  check('Information designated as confidential is identified and maintained throughout its lifecycle.','Evidence: Data classification policy, confidential data inventory, handling procedures.');
  check('Confidential information is disposed of securely using approved destruction methods.','Evidence: Media sanitization records, destruction certificates, disposal policy.');
  space();
  sectionHead('Processing Integrity (PI1) — Optional: include if in scope');
  check('System inputs are validated for completeness and accuracy before processing.','Evidence: Input validation controls, error logs, data quality reports.');
  check('Processing is monitored to ensure it is complete, valid, accurate, and timely.','Evidence: Processing job logs, reconciliation reports, exception handling records.');
  space();
  sectionHead('Privacy (P1–P8) — Optional: include if in scope');
  check('A current privacy notice is published describing how personal information is collected, used, and disclosed.','Evidence: Published privacy notice with version date, change log.');
  check('Consent is obtained before collecting personal information where required.','Evidence: Consent capture mechanism, consent records, opt-out procedures.');
  check('Personal information is used only for the purposes described in the privacy notice.','Evidence: Data flow diagrams, purpose limitation controls, data access logs.');
  check('Personal information is retained only as long as necessary and disposed of securely.','Evidence: Retention schedule, deletion logs, disposal certificates.');
  divider();

  sectionHead('Scoring & next steps');
  body('Count your responses: ☑ Fully implemented, ☒ Partially implemented, ☐ Not implemented. Calculate a readiness score: (☑ count) ÷ (total in scope) × 100. Scores below 70% indicate material risk before an examination window. Each ☒ or ☐ item should be logged in your evidence remediation tracker with an owner and target date.');
  space(8);
  body('For a practitioner-led gap analysis and a toolkit that closes every gap identified here, contact Verigo Global at verigoglobal.com.');

  footer(doc, W, H, M, 'Verigo-SOC2-Readiness-Checklist');
  doc.save('Verigo-SOC2-Readiness-Checklist.pdf');
}

/* ──────────────────────────────────────────────────────────── */
/* 2. CMMC 2.0 SELF-ASSESSMENT SCORECARD                       */
/* ──────────────────────────────────────────────────────────── */
function genCMMCScorecard(user) {
  const d = makeDoc();
  d.startPage('CMMC 2.0 Level 2 Self-Assessment Scorecard', 'NIST SP 800-171 Rev 2 · 110 practices');
  const { doc, W, H, M, sectionHead, subHead, body, note, colHead, row, space, divider, footer, newPage, ensureSpace } = d;

  doc.setFont('helvetica','bold'); doc.setFontSize(22); doc.setTextColor(...INK);
  doc.text('CMMC 2.0 Level 2', M, d.getY()); d.setY(d.getY()+2);
  doc.setFont('helvetica','bold'); doc.setFontSize(16); doc.setTextColor(...PURPLE);
  doc.text('Self-Assessment Scorecard', M, d.getY()+12); d.setY(d.getY()+22);
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,d.getY(),M+60,d.getY()); d.setY(d.getY()+18);
  if (user && user.company) { doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE); doc.text('Prepared for: '+user.company,M,d.getY()); d.setY(d.getY()+8); }
  doc.setFont('helvetica','normal'); doc.setFontSize(9); doc.setTextColor(...GREY);
  doc.text('Date: '+new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'}),M,d.getY()); d.setY(d.getY()+20);
  divider();

  sectionHead('Instructions');
  body('Score each NIST SP 800-171 practice as: MET (1.0) · PARTIALLY MET (0.5) · NOT MET (0.0). The DoD uses a 110-point scoring system where each practice is worth 1 point (with some practices having higher weighted negative impact). Complete the "Notes / Evidence location" column for every practice — this becomes your SSP evidence cross-reference. Any NOT MET practice must appear in your Plan of Action & Milestones (POA&M) with a remediation date.');
  space(4);

  // Domain tables
  const DOMAINS = [
    { code:'AC', name:'Access Control', pts:22, practices:[
      ['3.1.1','Limit system access to authorized users, processes acting on behalf of authorized users, and devices.'],
      ['3.1.2','Limit system access to types of transactions and functions that authorized users are permitted to execute.'],
      ['3.1.3','Control the flow of CUI in accordance with approved authorizations.'],
      ['3.1.4','Separate the duties of individuals to reduce the risk of malevolent activity.'],
      ['3.1.5','Employ the principle of least privilege, including for specific security functions and privileged accounts.'],
      ['3.1.6','Use non-privileged accounts when accessing non-security functions.'],
      ['3.1.7','Prevent non-privileged users from executing privileged functions and capture the execution in audit logs.'],
      ['3.1.8','Limit unsuccessful logon attempts.'],
      ['3.1.12','Monitor and control remote access sessions.'],
      ['3.1.13','Employ cryptographic mechanisms to protect the confidentiality of remote access sessions.'],
      ['3.1.16','Authorize wireless access prior to allowing connections to the system.'],
      ['3.1.17','Protect wireless access using authentication and encryption.'],
      ['3.1.18','Control connection of mobile devices.'],
      ['3.1.19','Encrypt CUI on mobile devices and mobile computing platforms.'],
      ['3.1.20','Verify and control/limit connections to external systems.'],
      ['3.1.21','Limit use of portable storage devices on external systems.'],
      ['3.1.22','Control CUI posted or processed on publicly accessible systems.'],
    ]},
    { code:'AT', name:'Awareness & Training', pts:3, practices:[
      ['3.2.1','Ensure that organizational personnel are aware of the security risks associated with their activities.'],
      ['3.2.2','Ensure personnel are trained to carry out their assigned information security responsibilities.'],
      ['3.2.3','Provide security awareness training on recognizing and reporting potential threats, including social engineering.'],
    ]},
    { code:'AU', name:'Audit & Accountability', pts:9, practices:[
      ['3.3.1','Create and retain system audit logs and records to enable the monitoring, analysis, investigation, and reporting of unlawful or unauthorized activity.'],
      ['3.3.2','Ensure that the actions of individual system users can be traced to those users.'],
      ['3.3.5','Correlate audit record review, analysis, and reporting processes for investigation and response.'],
      ['3.3.7','Provide a system capability that compares and synchronizes internal system clocks.'],
      ['3.3.8','Protect audit information and tools from unauthorized access, modification, and deletion.'],
    ]},
    { code:'CM', name:'Configuration Management', pts:9, practices:[
      ['3.4.1','Establish and maintain baseline configurations and inventories of organizational systems.'],
      ['3.4.2','Establish and enforce security configuration settings for information technology products.'],
      ['3.4.3','Track, review, approve, and log changes to organizational systems.'],
      ['3.4.5','Define, document, approve, and enforce physical and logical access restrictions associated with changes.'],
      ['3.4.6','Employ the principle of least functionality by configuring systems to provide only essential capabilities.'],
      ['3.4.7','Restrict, disable, or prevent the use of nonessential programs, functions, ports, protocols, and services.'],
      ['3.4.8','Apply deny-by-exception / permit-by-exception policy to prevent use of unauthorized software.'],
      ['3.4.9','Control and monitor user-installed software.'],
    ]},
    { code:'IA', name:'Identification & Authentication', pts:11, practices:[
      ['3.5.1','Identify system users, processes acting on behalf of users, and devices.'],
      ['3.5.2','Authenticate (or verify) the identities of users, processes, or devices before allowing access.'],
      ['3.5.3','Use multifactor authentication for local and network access to privileged accounts and network access to non-privileged accounts.'],
      ['3.5.7','Enforce a minimum password complexity and change of characters when new passwords are created.'],
      ['3.5.8','Prohibit password reuse for a specified number of generations.'],
      ['3.5.10','Store and transmit only cryptographically-protected passwords.'],
      ['3.5.11','Obscure feedback of authentication information.'],
    ]},
    { code:'IR', name:'Incident Response', pts:3, practices:[
      ['3.6.1','Establish an operational incident-handling capability for organizational systems including preparation, detection, analysis, containment, recovery, and user response activities.'],
      ['3.6.2','Track, document, and report incidents to designated officials and/or authorities.'],
      ['3.6.3','Test the organizational incident response capability.'],
    ]},
    { code:'MA', name:'Maintenance', pts:6, practices:[
      ['3.7.1','Perform maintenance on organizational systems.'],
      ['3.7.2','Provide controls on the tools, techniques, mechanisms, and personnel for maintenance.'],
      ['3.7.5','Require MFA to establish nonlocal maintenance sessions via external network connections.'],
      ['3.7.6','Supervise the maintenance activities of maintenance personnel without required access authorization.'],
    ]},
    { code:'MP', name:'Media Protection', pts:9, practices:[
      ['3.8.1','Protect (i.e., physically control and securely store) system media containing CUI, both paper and digital.'],
      ['3.8.2','Limit access to CUI on system media to authorized users.'],
      ['3.8.3','Sanitize or destroy system media before disposal or reuse.'],
      ['3.8.5','Control access to media containing CUI during transport outside of controlled areas.'],
      ['3.8.6','Implement cryptographic mechanisms to protect the confidentiality of CUI during transport.'],
      ['3.8.7','Control the use of removable media on system components.'],
      ['3.8.9','Protect the confidentiality of backup CUI at storage locations.'],
    ]},
    { code:'PS', name:'Personnel Security', pts:2, practices:[
      ['3.9.1','Screen individuals prior to authorizing access to organizational systems containing CUI.'],
      ['3.9.2','Ensure that CUI is protected during and after personnel actions such as terminations and transfers.'],
    ]},
    { code:'PE', name:'Physical Protection', pts:6, practices:[
      ['3.10.1','Limit physical access to organizational systems to authorized individuals.'],
      ['3.10.2','Protect and monitor the physical facility and support infrastructure for organizational systems.'],
      ['3.10.3','Escort visitors and monitor visitor activity.'],
      ['3.10.4','Maintain audit logs of physical access.'],
      ['3.10.5','Control and manage physical access devices.'],
      ['3.10.6','Enforce safeguarding measures for CUI at alternate work sites.'],
    ]},
    { code:'RA', name:'Risk Assessment', pts:3, practices:[
      ['3.11.1','Periodically assess the risk to organizational operations, assets, and individuals.'],
      ['3.11.2','Scan for vulnerabilities in organizational systems and applications periodically and when new vulnerabilities are identified.'],
      ['3.11.3','Remediate vulnerabilities in accordance with risk assessments.'],
    ]},
    { code:'CA', name:'Security Assessment', pts:4, practices:[
      ['3.12.1','Periodically assess the security controls in organizational systems to determine if the controls are effective.'],
      ['3.12.2','Develop and implement plans of action designed to correct deficiencies and reduce or eliminate vulnerabilities.'],
      ['3.12.3','Monitor security controls on an ongoing basis to ensure the continued effectiveness of the controls.'],
      ['3.12.4','Develop, document, and periodically update system security plans (SSP) that describe system boundaries, environments, and how security requirements are implemented.'],
    ]},
    { code:'SC', name:'System & Communications Protection', pts:16, practices:[
      ['3.13.1','Monitor, control, and protect communications at external boundaries and key internal boundaries of organizational systems.'],
      ['3.13.5','Implement subnetworks for publicly accessible system components that are physically or logically separated from internal networks.'],
      ['3.13.8','Implement cryptographic mechanisms to prevent unauthorized disclosure of CUI during transmission.'],
      ['3.13.10','Establish and manage cryptographic keys for required cryptography employed in organizational systems.'],
      ['3.13.11','Employ FIPS-validated cryptography when used to protect the confidentiality of CUI.'],
      ['3.13.15','Protect the authenticity of communications sessions.'],
      ['3.13.16','Protect the confidentiality of CUI at rest.'],
    ]},
    { code:'SI', name:'System & Information Integrity', pts:7, practices:[
      ['3.14.1','Identify, report, and correct information and information system flaws in a timely manner.'],
      ['3.14.2','Provide protection from malicious code at appropriate locations within organizational systems.'],
      ['3.14.4','Update malicious code protection mechanisms when new releases are available.'],
      ['3.14.5','Perform periodic scans of organizational systems and real-time scans of files from external sources.'],
      ['3.14.6','Monitor organizational systems, including inbound and outbound communications traffic, to detect attacks and indicators of potential attacks.'],
      ['3.14.7','Identify unauthorized use of organizational systems.'],
    ]},
  ];

  const cols = [
    {label:'Practice',x:M,w:48},
    {label:'Requirement statement (abbreviated)',x:M+48,w:260},
    {label:'Status',x:M+308,w:60},
    {label:'Score',x:M+368,w:40},
    {label:'Notes / Evidence location',x:M+408,w:120},
  ];

  DOMAINS.forEach((dom, di) => {
    newPage();
    sectionHead(dom.code + ' · ' + dom.name + '  (' + dom.pts + ' pts)');
    colHead(cols);
    dom.practices.forEach((p,pi)=>row([p[0], p[1], '', '', ''], cols, pi%2===1));
    // Domain score box
    d.setY(d.getY()+6);
    doc.setFillColor(...LIGHT); doc.rect(M,d.getY()-8,W-2*M,22,'F');
    doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE);
    doc.text(`${dom.code} domain score: _____ / ${dom.practices.length}   |   Practices not met (POA&M required): _____`, M+8, d.getY()+6);
    d.setY(d.getY()+20);
  });

  // Summary page
  newPage();
  sectionHead('Summary Scoring Sheet');
  colHead([{label:'Domain',x:M,w:180},{label:'Practices',x:M+180,w:70},{label:'Met',x:M+250,w:50},{label:'Partial',x:M+300,w:55},{label:'Not Met',x:M+355,w:55},{label:'Score',x:M+410,w:60}]);
  DOMAINS.forEach((dom,i)=>row([dom.code+' · '+dom.name, String(dom.practices.length),'','','','___ / '+dom.practices.length], [{x:M,w:180},{x:M+180,w:70},{x:M+250,w:50},{x:M+300,w:55},{x:M+355,w:55},{x:M+410,w:60}], i%2===1));
  d.setY(d.getY()+10);
  doc.setFillColor(...PURPLE); doc.rect(M,d.getY()-8,W-2*M,24,'F');
  doc.setFont('helvetica','bold'); doc.setFontSize(11); doc.setTextColor(255,255,255);
  doc.text('TOTAL SCORE: _____ / 110    |    ASSESSMENT DATE: ____________________', M+10, d.getY()+8); d.setY(d.getY()+30);
  sectionHead('Interpretation');
  body('110 / 110 = All practices met · Assessment-ready. 100–109 = Minor gaps; complete POA&M before assessment. 85–99 = Moderate gaps; significant remediation needed. Below 85 = Material risk; do not schedule a C3PAO assessment until score improves. Any practice scored 0 that involves CUI protection may result in assessment failure regardless of total score.');
  space(8);
  sectionHead('POA&M Summary');
  colHead([{label:'Practice ID',x:M,w:70},{label:'Description',x:M+70,w:200},{label:'Remediation plan',x:M+270,w:140},{label:'Owner',x:M+410,w:70},{label:'Target date',x:M+480,w:70}]);
  for (let i=0;i<10;i++) row(['','','','',''], [{x:M,w:70},{x:M+70,w:200},{x:M+270,w:140},{x:M+410,w:70},{x:M+480,w:70}], i%2===1);

  footer(doc, W, H, M, 'Verigo-CMMC-Level2-Scorecard');
  doc.save('Verigo-CMMC-Level2-Self-Assessment-Scorecard.pdf');
}

/* ──────────────────────────────────────────────────────────── */
/* 3. ISO 27001:2022 GAP ANALYSIS TEMPLATE                     */
/* ──────────────────────────────────────────────────────────── */
function genISO27001Gap(user) {
  const d = makeDoc();
  d.startPage('ISO 27001:2022 Gap Analysis', 'ISO/IEC 27001:2022 · Annex A controls');
  const { doc, W, H, M, sectionHead, body, colHead, row, space, divider, footer, newPage } = d;

  doc.setFont('helvetica','bold'); doc.setFontSize(22); doc.setTextColor(...INK);
  doc.text('ISO 27001:2022', M, d.getY()); d.setY(d.getY()+2);
  doc.setFont('helvetica','bold'); doc.setFontSize(16); doc.setTextColor(...PURPLE);
  doc.text('Annex A Gap Analysis Template', M, d.getY()+12); d.setY(d.getY()+26);
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,d.getY(),M+60,d.getY()); d.setY(d.getY()+18);
  if (user && user.company) { doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE); doc.text('Prepared for: '+user.company,M,d.getY()); d.setY(d.getY()+8); }
  doc.setFont('helvetica','normal'); doc.setFontSize(9); doc.setTextColor(...GREY);
  doc.text('Date: '+new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'})+' · ISO/IEC 27001:2022 · 93 Annex A controls',M,d.getY()); d.setY(d.getY()+20);
  divider();

  sectionHead('Instructions');
  body('For each control, complete four columns: (1) Applicable: Y / N / Partial — if N, document justification for the SoA. (2) Implementation status: Not started / In progress / Largely / Implemented. (3) Evidence location: file path, system, or document reference where implementation evidence lives. (4) Owner: name or role responsible for the control. Use this output to populate your Statement of Applicability (SoA) and risk treatment plan.');
  space(4);

  const themes = [
    { code:'A.5', name:'Organizational Controls', count:37, controls:[
      ['A.5.1','Policies for information security'],['A.5.2','Information security roles and responsibilities'],
      ['A.5.3','Segregation of duties'],['A.5.4','Management responsibilities'],
      ['A.5.5','Contact with authorities'],['A.5.6','Contact with special interest groups'],
      ['A.5.7','Threat intelligence ★NEW'],['A.5.8','Information security in project management'],
      ['A.5.9','Inventory of information and assets'],['A.5.10','Acceptable use of information and assets'],
      ['A.5.11','Return of assets'],['A.5.12','Classification of information'],
      ['A.5.13','Labelling of information'],['A.5.14','Information transfer'],
      ['A.5.15','Access control'],['A.5.16','Identity management'],
      ['A.5.17','Authentication information'],['A.5.18','Access rights'],
      ['A.5.19','Information security in supplier relationships'],['A.5.20','Supplier agreements'],
      ['A.5.21','ICT supply chain ★NEW'],['A.5.22','Monitoring and review of supplier services'],
      ['A.5.23','Information security for cloud services ★NEW'],['A.5.24','Incident management planning and preparation'],
      ['A.5.25','Assessment of information security events'],['A.5.26','Response to information security incidents'],
      ['A.5.27','Learning from incidents'],['A.5.28','Collection of evidence'],
      ['A.5.29','Information security during disruption'],['A.5.30','ICT readiness for business continuity ★NEW'],
      ['A.5.31','Legal, statutory, regulatory requirements'],['A.5.32','Intellectual property rights'],
      ['A.5.33','Protection of records'],['A.5.34','Privacy and protection of PII'],
      ['A.5.35','Independent review of information security'],['A.5.36','Compliance with policies'],
      ['A.5.37','Documented operating procedures'],
    ]},
    { code:'A.6', name:'People Controls', count:8, controls:[
      ['A.6.1','Screening'],['A.6.2','Terms and conditions of employment'],
      ['A.6.3','Information security awareness, education and training'],['A.6.4','Disciplinary process'],
      ['A.6.5','Responsibilities after termination or change'],['A.6.6','Confidentiality agreements'],
      ['A.6.7','Remote working'],['A.6.8','Information security event reporting'],
    ]},
    { code:'A.7', name:'Physical Controls', count:14, controls:[
      ['A.7.1','Physical security perimeters'],['A.7.2','Physical entry'],
      ['A.7.3','Securing offices, rooms and facilities'],['A.7.4','Physical security monitoring ★NEW'],
      ['A.7.5','Protecting against physical and environmental threats'],['A.7.6','Working in secure areas'],
      ['A.7.7','Clear desk and clear screen'],['A.7.8','Equipment siting and protection'],
      ['A.7.9','Security of assets off-premises'],['A.7.10','Storage media'],
      ['A.7.11','Supporting utilities'],['A.7.12','Cabling security'],
      ['A.7.13','Equipment maintenance'],['A.7.14','Secure disposal or re-use of equipment'],
    ]},
    { code:'A.8', name:'Technological Controls', count:34, controls:[
      ['A.8.1','User endpoint devices'],['A.8.2','Privileged access rights'],
      ['A.8.3','Information access restriction'],['A.8.4','Access to source code'],
      ['A.8.5','Secure authentication'],['A.8.6','Capacity management'],
      ['A.8.7','Protection against malware'],['A.8.8','Management of technical vulnerabilities'],
      ['A.8.9','Configuration management ★NEW'],['A.8.10','Information deletion ★NEW'],
      ['A.8.11','Data masking ★NEW'],['A.8.12','Data leakage prevention ★NEW'],
      ['A.8.13','Information backup'],['A.8.14','Redundancy of information processing facilities'],
      ['A.8.15','Logging'],['A.8.16','Monitoring activities ★NEW'],
      ['A.8.17','Clock synchronization'],['A.8.18','Use of privileged utility programs'],
      ['A.8.19','Installation of software on operational systems'],['A.8.20','Networks security'],
      ['A.8.21','Security of network services'],['A.8.22','Segregation of networks'],
      ['A.8.23','Web filtering ★NEW'],['A.8.24','Use of cryptography'],
      ['A.8.25','Secure development life cycle'],['A.8.26','Application security requirements'],
      ['A.8.27','Secure system architecture and engineering principles'],['A.8.28','Secure coding'],
      ['A.8.29','Security testing in development and acceptance'],['A.8.30','Outsourced development'],
      ['A.8.31','Separation of development, test and production environments'],['A.8.32','Change management'],
      ['A.8.33','Test information'],['A.8.34','Protection of information systems during audit testing'],
    ]},
  ];

  const cols4 = [{label:'Control',x:M,w:140},{label:'Applicable (Y/N)',x:M+140,w:80},{label:'Status',x:M+220,w:100},{label:'Evidence location',x:M+320,w:120},{label:'Owner',x:M+440,w:80}];
  themes.forEach(th => {
    newPage();
    sectionHead(th.code+' · '+th.name+' ('+th.count+' controls)');
    colHead(cols4);
    th.controls.forEach((c,i)=>row([c[0]+' '+c[1],'','','',''], cols4, i%2===1));
    d.setY(d.getY()+8);
    doc.setFillColor(...LIGHT); doc.rect(M,d.getY()-8,W-2*M,20,'F');
    doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE);
    doc.text(th.code+' — Applicable: ___/'+th.count+'   Not applicable: ___   Implemented: ___   In progress: ___   Not started: ___', M+8, d.getY()+4); d.setY(d.getY()+18);
  });

  newPage();
  sectionHead('Gap Analysis Summary');
  colHead([{label:'Theme',x:M,w:180},{label:'Total',x:M+180,w:45},{label:'Applicable',x:M+225,w:60},{label:'Implemented',x:M+285,w:75},{label:'In progress',x:M+360,w:70},{label:'Not started',x:M+430,w:70},{label:'% complete',x:M+500,w:70}]);
  themes.forEach((t,i)=>row([t.code+' · '+t.name,String(t.count),'','','','',''], [{x:M,w:180},{x:M+180,w:45},{x:M+225,w:60},{x:M+285,w:75},{x:M+360,w:70},{x:M+430,w:70},{x:M+500,w:70}], i%2===1));
  d.setY(d.getY()+8);
  doc.setFillColor(...PURPLE); doc.rect(M,d.getY()-8,W-2*M,24,'F');
  doc.setFont('helvetica','bold'); doc.setFontSize(10); doc.setTextColor(255,255,255);
  doc.text('TOTAL: 93 controls   Applicable: ___   Implemented: ___   % complete: ___', M+10, d.getY()+8); d.setY(d.getY()+30);
  body('★NEW marks the 11 controls added in the ISO 27001:2022 revision. All 11 must be assessed for applicability. Controls marked N (not applicable) must include a documented justification in the Statement of Applicability (SoA) and be supported by a risk treatment decision.');

  footer(doc, W, H, M, 'Verigo-ISO27001-2022-Gap-Analysis');
  doc.save('Verigo-ISO27001-2022-Gap-Analysis-Template.pdf');
}

/* ──────────────────────────────────────────────────────────── */
/* 4. CROSS-FRAMEWORK CONTROL MAPPING GUIDE                    */
/* ──────────────────────────────────────────────────────────── */
function genCrossFramework(user) {
  const d = makeDoc();
  d.startPage('Cross-Framework Control Mapping', 'ISO 27001 · SOC 2 · CMMC 2.0 · NIST CSF');
  const { doc, W, H, M, sectionHead, subHead, body, note, colHead, row, space, divider, footer, newPage } = d;

  doc.setFont('helvetica','bold'); doc.setFontSize(22); doc.setTextColor(...INK);
  doc.text('Cross-Framework Control', M, d.getY()); d.setY(d.getY()+2);
  doc.setFont('helvetica','bold'); doc.setFontSize(16); doc.setTextColor(...PURPLE);
  doc.text('Mapping Guide', M, d.getY()+12); d.setY(d.getY()+26);
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,d.getY(),M+60,d.getY()); d.setY(d.getY()+18);
  doc.setFont('helvetica','normal'); doc.setFontSize(10); doc.setTextColor(...GREY);
  doc.text('ISO 27001:2022 · SOC 2 (TSC 2017 rev 2022) · CMMC 2.0/NIST SP 800-171 · NIST CSF v2.0',M,d.getY()); d.setY(d.getY()+20);
  divider();
  sectionHead('How to use this guide');
  body('Each row represents a compliance control area shared across two or more frameworks. Use the rightmost column ("Shared evidence") to build a single evidence artefact that satisfies all applicable frameworks. Implement once, reference everywhere. The final column gives the evidence type most commonly accepted by auditors and assessors for that control area.');
  space(4);

  const mappings = [
    ['Access Control & Identity','MFA, least privilege, access review','CC6.1–CC6.3','A.5.15, A.8.2, A.8.5','3.1.1, 3.1.5, 3.5.3','PR.AA-01–06, ID.AM-05','IdP config export, MFA enrolment report, quarterly access review with sign-off'],
    ['Vulnerability Management','Scanning, prioritisation, patching','CC7.1','A.8.8','3.11.2, 3.11.3','ID.RA-01, ID.RA-05','Authenticated scan report, remediation tracking log, patch management record'],
    ['Incident Response','Detection, escalation, recovery, reporting','CC7.3–CC7.5','A.5.24–A.5.27','3.6.1–3.6.3','RS.MA, RS.AN, RS.MI, RC.RP','Incident register, IR plan (tested), post-incident review report'],
    ['Change Management','Authorized, tested, deployed changes','CC8.1','A.8.32','3.4.3, 3.4.4','PR.PS-06, ID.IM-03','Change tickets with CAB approval, test results, deployment records'],
    ['Logging & Monitoring','Event collection, review, retention','CC7.2','A.8.15, A.8.16','3.3.1–3.3.5','DE.CM-01, DE.CM-09','SIEM dashboard, alert triage log, log retention policy and evidence of enforcement'],
    ['Backup & Recovery','Backup, encryption, restoration testing','A1.1–A1.3','A.8.13, A.8.14','3.7.1 (MA)','PR.DS-11, RC.RP-03–05','Backup schedule, encryption config, restoration test report with RTO/RPO outcomes'],
    ['Risk Assessment','Identification, analysis, treatment','CC3.1–CC3.4','Clauses 6.1–6.2','3.11.1','ID.RA-01–10, GV.RM-02','Current risk register, risk treatment decisions, residual risk acceptance records'],
    ['Vendor & Supply Chain Security','Third-party assessment, contract requirements','CC9.2','A.5.19–A.5.22','3.7.6, SAM domain','GV.SC-01–10','Vendor risk assessment records, contract security addenda, third-party review schedule'],
    ['Security Awareness & Training','Role-based training, tracking, refresh','CC2.2','A.6.3','3.2.1–3.2.3','PR.AT-01–02','Training completion records, curriculum, acknowledgment logs, training effectiveness survey'],
    ['Configuration Management','Baselines, hardening, least functionality','CC5.2','A.8.9','3.4.1, 3.4.2, 3.4.6','PR.PS-01, PR.PS-02','Configuration baseline documents, hardening checklists, automated compliance scan results'],
    ['Cryptography / Data in Transit','Encryption protocols, key management','CC6.7','A.8.24','3.13.8, 3.13.11','PR.DS-02','TLS certificate inventory, encryption policy, FIPS validation records, key management procedure'],
    ['Data at Rest','Storage encryption, media control','CC6.1','A.8.1, A.7.10','3.13.16, 3.8.1','PR.DS-01','Encryption config export, disk encryption policy, media inventory and handling log'],
    ['Physical Security','Perimeter, entry controls, equipment','CC6.4','A.7.1–A.7.2','3.10.1–3.10.5','PR.AA-06, PR.IR-02','Badge access logs, physical security assessment, visitor register, CCTV policy'],
    ['Business Continuity & DR','Plans, testing, RTO/RPO','A1.3','A.5.29, A.5.30','3.7.1','RC.RP-01–06','BCP/DRP documents, test results with RTO/RPO outcomes, management sign-off'],
    ['Privacy & Data Protection','Notices, consent, retention, disposal','P1–P8','A.5.34','—','GV.OC-03','Privacy notice, consent records, data retention schedule, secure disposal records'],
    ['Segregation of Duties','Separation of conflicting roles','CC3.3','A.5.3','3.1.4','GV.RR-02','RACI/SoD matrix, role definition documentation, access entitlement report'],
    ['Audit Trails & Accountability','User action traceability','CC7.2','A.8.15','3.3.1–3.3.2','DE.CM-03','Audit log samples, user activity records, log integrity verification'],
    ['Software Development Security','SDLC controls, testing, code review','CC8.1','A.8.25–A.8.28','3.14.1','PR.PS-06','SDLC policy, code review records, SAST/DAST scan results, penetration test report'],
  ];

  const cols = [{label:'Control area',x:M,w:120},{label:'What it covers',x:M+120,w:110},{label:'SOC 2',x:M+230,w:65},{label:'ISO 27001',x:M+295,w:70},{label:'CMMC/800-171',x:M+365,w:75},{label:'NIST CSF',x:M+440,w:75},{label:'Shared evidence artefact',x:M+515,w:135}];
  colHead(cols);
  mappings.forEach((r,i) => row(r, cols, i%2===1));

  newPage();
  sectionHead('Evidence reuse strategy');
  body('The most efficient multi-framework programs build a "single source of truth" for each shared control — one implementation record, one evidence artefact, mapped to all applicable framework references. The cross-reference table above gives you the framework references; the "Shared evidence" column gives you the artefact. Build your evidence library around these artefacts first — they deliver the highest return across the most frameworks simultaneously.');
  space(8);
  subHead('Recommended sequencing for US SaaS providers');
  body('1. SOC 2 Type I → establishes control design and begins building evidence routines (3–6 months). 2. ISO 27001 certification → most controls already exist from SOC 2; gap work concentrates on management system clauses and the 11 new Annex A controls (~3–6 additional months). 3. CMMC 2.0 Level 2 → NIST 800-171 overlaps heavily with SOC 2 CC6–CC9 and ISO 27001 Annex A; focus on CUI enclave scoping and SSP/POA&M documentation (~4–9 months additional).');
  space(6);
  subHead('Recommended sequencing for defense contractors');
  body('1. CMMC 2.0 Level 2 (deadline-driven) → implement all 110 NIST 800-171 practices, complete SSP and POA&M, prepare for C3PAO assessment. 2. NIST CSF v2.0 Profile → document current and target profiles using the control environment already built for CMMC. 3. ISO 27001 or SOC 2 → the CMMC control environment provides a strong starting point for either framework with targeted gap work on management system documentation.');
  space(8);
  sectionHead('How to build your unified evidence library');
  body('Step 1: Create a master control matrix with rows = implemented controls and columns = framework references. Step 2: For each implemented control, identify all frameworks it satisfies using the mapping table above. Step 3: For each control, designate a single evidence artefact and its location (file path, GRC system, document URL). Step 4: Assign a control owner responsible for both the operational execution and the evidence record. Step 5: Set a cadence for each evidence artefact (daily, weekly, quarterly, annually) aligned to the most demanding framework\'s evidence requirements.');

  footer(doc, W, H, M, 'Verigo-Cross-Framework-Mapping');
  doc.save('Verigo-Cross-Framework-Control-Mapping-Guide.pdf');
}

/* ──────────────────────────────────────────────────────────── */
/* 5. NIST CSF v2.0 PROFILE TEMPLATE                           */
/* ──────────────────────────────────────────────────────────── */
function genNISTProfile(user) {
  const d = makeDoc();
  d.startPage('NIST CSF v2.0 Profile Template', 'NIST Cybersecurity Framework v2.0 · February 2024');
  const { doc, W, H, M, sectionHead, subHead, body, colHead, row, space, divider, footer, newPage } = d;

  doc.setFont('helvetica','bold'); doc.setFontSize(22); doc.setTextColor(...INK);
  doc.text('NIST CSF v2.0', M, d.getY()); d.setY(d.getY()+2);
  doc.setFont('helvetica','bold'); doc.setFontSize(16); doc.setTextColor(...PURPLE);
  doc.text('Profile Template — Current & Target', M, d.getY()+12); d.setY(d.getY()+26);
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,d.getY(),M+60,d.getY()); d.setY(d.getY()+18);
  if (user && user.company) { doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE); doc.text('Prepared for: '+user.company,M,d.getY()); d.setY(d.getY()+8); }
  doc.setFont('helvetica','normal'); doc.setFontSize(9); doc.setTextColor(...GREY);
  doc.text('Date: '+new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'}),M,d.getY()); d.setY(d.getY()+20);
  divider();

  sectionHead('Instructions');
  body('A CSF Profile is a prioritized selection of Framework outcomes tailored to your organization\'s mission, risk tolerance, and resources. A Current Profile describes the outcomes you are achieving today. A Target Profile describes the outcomes you want to achieve. The gap between the two is your implementation roadmap.');
  space(2);
  body('For each subcategory: (1) Rate your Current state: 0 = Not started · 1 = Partial · 2 = Largely · 3 = Fully. (2) Set your Target state (same scale). (3) Calculate the gap (Target − Current). (4) Set a Priority: H / M / L. (5) Note the evidence location or implementation action needed.');
  space(4);

  const fnIcon = {GV:'■',ID:'▲',PR:'●',DE:'◆',RS:'★',RC:'✦'};
  const functions = [
    { fn:'GV', name:'Govern', color:PURPLE, cats:[
      {cat:'GV.OC',name:'Organizational Context',subs:['GV.OC-01 Mission informs risk priorities','GV.OC-02 Internal & external stakeholders understood','GV.OC-03 Legal & regulatory requirements identified','GV.OC-04 Critical objectives and capabilities identified','GV.OC-05 External dependencies understood']},
      {cat:'GV.RM',name:'Risk Management',subs:['GV.RM-01 Risk management objectives established','GV.RM-02 Risk appetite & tolerance communicated','GV.RM-03 Cybersecurity risk integrated with ERM','GV.RM-04 Risk response strategy established','GV.RM-06 Standardized risk calculation method defined']},
      {cat:'GV.RR',name:'Roles & Responsibilities',subs:['GV.RR-01 Leadership accountable for cyber risk','GV.RR-02 Roles and responsibilities communicated','GV.RR-03 Adequate resources allocated','GV.RR-04 Cybersecurity in HR practices']},
      {cat:'GV.PO',name:'Policy',subs:['GV.PO-01 Policy for managing cyber risk established','GV.PO-02 Policy reviewed and kept current']},
      {cat:'GV.OV',name:'Oversight',subs:['GV.OV-01 Strategy outcomes reviewed','GV.OV-02 Risk management strategy reviewed','GV.OV-03 Performance evaluated for adjustment']},
      {cat:'GV.SC',name:'Supply Chain Risk',subs:['GV.SC-01 Supply chain risk management program','GV.SC-04 Suppliers known and prioritized','GV.SC-05 Requirements in supplier contracts','GV.SC-07 Third-party risk understood','GV.SC-08 Suppliers in incident planning']},
    ]},
    { fn:'ID', name:'Identify', color:[60,80,180], cats:[
      {cat:'ID.AM',name:'Asset Management',subs:['ID.AM-01 Hardware inventories maintained','ID.AM-02 Software inventories maintained','ID.AM-05 Assets prioritized by criticality','ID.AM-07 Data inventories maintained','ID.AM-08 Assets managed through life cycle']},
      {cat:'ID.RA',name:'Risk Assessment',subs:['ID.RA-01 Vulnerabilities identified and recorded','ID.RA-02 Threat intelligence received','ID.RA-03 Threats identified and recorded','ID.RA-05 Risk understood from threats & vulnerabilities','ID.RA-06 Risk responses chosen and tracked']},
      {cat:'ID.IM',name:'Improvement',subs:['ID.IM-01 Improvements from evaluations','ID.IM-02 Improvements from tests & exercises','ID.IM-04 Incident response plans maintained']},
    ]},
    { fn:'PR', name:'Protect', color:[50,150,80], cats:[
      {cat:'PR.AA',name:'Identity Management & Access Control',subs:['PR.AA-01 Identities and credentials managed','PR.AA-02 Identities proofed and bound','PR.AA-03 Users and devices authenticated','PR.AA-05 Permissions defined and enforced','PR.AA-06 Physical access managed']},
      {cat:'PR.AT',name:'Awareness & Training',subs:['PR.AT-01 General security awareness training','PR.AT-02 Role-specific security training']},
      {cat:'PR.DS',name:'Data Security',subs:['PR.DS-01 Data-at-rest protected','PR.DS-02 Data-in-transit protected','PR.DS-10 Data-in-use protected','PR.DS-11 Backups created and tested']},
      {cat:'PR.PS',name:'Platform Security',subs:['PR.PS-01 Configuration management applied','PR.PS-02 Software maintained','PR.PS-04 Logs generated','PR.PS-06 Secure development practices integrated']},
      {cat:'PR.IR',name:'Infrastructure Resilience',subs:['PR.IR-01 Networks protected from unauthorized access','PR.IR-03 Resilience mechanisms implemented','PR.IR-04 Adequate resource capacity maintained']},
    ]},
    { fn:'DE', name:'Detect', color:[180,100,0], cats:[
      {cat:'DE.CM',name:'Continuous Monitoring',subs:['DE.CM-01 Networks and services monitored','DE.CM-03 Personnel activity monitored','DE.CM-06 External service providers monitored','DE.CM-09 Compute assets monitored']},
      {cat:'DE.AE',name:'Adverse Event Analysis',subs:['DE.AE-02 Events analyzed for understanding','DE.AE-03 Information correlated from multiple sources','DE.AE-04 Impact and scope estimated','DE.AE-06 Findings provided to authorized staff','DE.AE-08 Incidents declared from adverse events']},
    ]},
    { fn:'RS', name:'Respond', color:[180,50,50], cats:[
      {cat:'RS.MA',name:'Incident Management',subs:['RS.MA-01 Incident response plan executed','RS.MA-02 Incidents triaged and validated','RS.MA-03 Incidents categorized and prioritized','RS.MA-05 Incident recovery criteria applied']},
      {cat:'RS.AN',name:'Incident Analysis',subs:['RS.AN-03 Root cause established','RS.AN-06 Actions recorded with integrity']},
      {cat:'RS.CO',name:'Incident Communication',subs:['RS.CO-02 Stakeholders notified','RS.CO-03 Information shared with designated parties']},
      {cat:'RS.MI',name:'Incident Mitigation',subs:['RS.MI-01 Incidents contained','RS.MI-02 Incidents eradicated']},
    ]},
    { fn:'RC', name:'Recover', color:[80,130,80], cats:[
      {cat:'RC.RP',name:'Incident Recovery Plan',subs:['RC.RP-01 Recovery plan executed','RC.RP-03 Backup integrity verified','RC.RP-04 Mission operations considered post-incident','RC.RP-05 Asset integrity verified and operations restored','RC.RP-06 Incident recovery declared']},
      {cat:'RC.CO',name:'Recovery Communication',subs:['RC.CO-03 Recovery progress communicated','RC.CO-04 Public updates shared']},
    ]},
  ];

  const cols = [{label:'Subcategory',x:M,w:198},{label:'Current (0–3)',x:M+198,w:65},{label:'Target (0–3)',x:M+263,w:65},{label:'Gap',x:M+328,w:40},{label:'Priority',x:M+368,w:45},{label:'Implementation notes / Evidence',x:M+413,w:137}];

  functions.forEach(fn => {
    newPage();
    doc.setFillColor(...fn.color); doc.rect(M-4,d.getY()-14,W-2*M+8,20,'F');
    doc.setFont('helvetica','bold'); doc.setFontSize(13); doc.setTextColor(255,255,255);
    doc.text(fn.fn+' · '+fn.name, M+4, d.getY()); d.setY(d.getY()+16);
    fn.cats.forEach(cat => {
      d.setY(d.getY()+4);
      doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE);
      doc.text(cat.cat+' · '+cat.name, M, d.getY()); d.setY(d.getY()+4);
      colHead(cols);
      cat.subs.forEach((s,i)=>row([s,'','','','',''], cols, i%2===1));
    });
    d.setY(d.getY()+8);
    doc.setFillColor(...LIGHT); doc.rect(M,d.getY()-8,W-2*M,20,'F');
    doc.setFont('helvetica','bold'); doc.setFontSize(8.5); doc.setTextColor(...PURPLE);
    doc.text(fn.fn+' — Average current score: _____   Average target score: _____   Priority gaps: _____', M+8, d.getY()+4); d.setY(d.getY()+18);
  });

  newPage();
  sectionHead('Profile Summary');
  colHead([{label:'Function',x:M,w:120},{label:'Subcategories',x:M+120,w:80},{label:'Avg current',x:M+200,w:80},{label:'Avg target',x:M+280,w:80},{label:'Gap',x:M+360,w:60},{label:'Top 3 priority actions',x:M+420,w:150}]);
  functions.forEach((fn,i)=>row([fn.fn+' · '+fn.name, String(fn.cats.reduce((a,c)=>a+c.subs.length,0)),'','','',''], [{x:M,w:120},{x:M+120,w:80},{x:M+200,w:80},{x:M+280,w:80},{x:M+360,w:60},{x:M+420,w:150}], i%2===1));
  d.setY(d.getY()+12);
  body('Score interpretation: 0 = Not started · 1 = Partial (informal or inconsistent) · 2 = Largely (consistent but not fully documented) · 3 = Fully (documented, tested, monitored, continuously improved). A gap of 2+ on any subcategory warrants immediate prioritization.');

  footer(doc, W, H, M, 'Verigo-NIST-CSF-v2-Profile-Template');
  doc.save('Verigo-NIST-CSF-v2-Profile-Template.pdf');
}

/* ──────────────────────────────────────────────────────────── */
/* 6. HITRUST CSF QUICK-START GUIDE                            */
/* ──────────────────────────────────────────────────────────── */
function genHITRUSTGuide(user) {
  const d = makeDoc();
  d.startPage('HITRUST CSF Quick-Start Guide', 'HITRUST CSF v11 · e1, i1, r2 Assessments');
  const { doc, W, H, M, sectionHead, subHead, body, note, colHead, row, check, space, divider, footer, newPage } = d;

  doc.setFont('helvetica','bold'); doc.setFontSize(22); doc.setTextColor(...INK);
  doc.text('HITRUST CSF', M, d.getY()); d.setY(d.getY()+2);
  doc.setFont('helvetica','bold'); doc.setFontSize(16); doc.setTextColor(...PURPLE);
  doc.text('Quick-Start Guide to e1, i1, and r2', M, d.getY()+12); d.setY(d.getY()+26);
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,d.getY(),M+60,d.getY()); d.setY(d.getY()+18);
  if (user && user.company) { doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...PURPLE); doc.text('Prepared for: '+user.company,M,d.getY()); d.setY(d.getY()+8); }
  doc.setFont('helvetica','normal'); doc.setFontSize(9); doc.setTextColor(...GREY);
  doc.text('Date: '+new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'}),M,d.getY()); d.setY(d.getY()+20);
  divider();

  sectionHead('Assessment type comparison');
  colHead([{label:'',x:M,w:100},{label:'e1 — Essentials',x:M+100,w:130},{label:'i1 — Implemented',x:M+230,w:130},{label:'r2 — Risk-based',x:M+360,w:160}]);
  const cmpRows = [
    ['Requirements','44 (fixed)','182 (fixed)','200–800+ (tailored)'],
    ['Assurance level','Foundational','Moderate','High / Full certification'],
    ['Validity','1 year','1 year','2 years (+ 1-year interim)'],
    ['External Assessor','Not required (HITRUST validates)','Required','Required (+ government-led option for Level 3)'],
    ['Typical prep time','1–3 months','3–9 months','9–18 months'],
    ['Typical investment','Low','Moderate','High'],
    ['Market acceptance','Entry-level signal','Most health-sector buyers','High-value healthcare contracts'],
    ['MyCSF submission','Self-assessed','EA-validated','EA-validated + interim review'],
    ['Best for','New entrants, quick response to customer RFQ','Most healthcare IT and BPO organizations','High-value health system and federal health contracts'],
  ];
  const cmpCols=[{x:M,w:100},{x:M+100,w:130},{x:M+230,w:130},{x:M+360,w:160}];
  cmpRows.forEach((r,i)=>row(r,cmpCols,i%2===1));
  space(8);

  sectionHead('Step 1 — Select your assessment type');
  body('Ask three questions: (1) What is your customer asking for? If they specify "HITRUST certified" without a level, i1 is the safe default. (2) What is your timeline? If you have fewer than 6 months, e1 is the only realistic option. (3) What type of contracts do you hold? Federal health contracts or major health system business-associate agreements typically require r2.');
  space(4);

  sectionHead('Step 2 — Set up your MyCSF account');
  subHead('Create your organization record');
  body('Go to mycsf.net and register your organization. You will complete an organizational profile including: legal entity name, primary industry sector, number of full-time employees, geographic footprint, and regulatory environment (HIPAA, HITRUST-only, etc.).');
  space(2);
  subHead('Complete the factor questionnaire (r2 only)');
  body('The r2 requirement set is generated by a factor questionnaire covering organizational factors (size, geographic scope), system factors (data types, system count, hosting model), and regulatory factors (HIPAA, PCI-DSS, GDPR, etc.). Each factor adds or removes requirement statements. Complete this carefully — it determines your entire requirement set.');
  space(4);

  sectionHead('Step 3 — Map controls to evidence');
  body('The HITRUST CSF uses a three-level maturity model for each control reference: Policy (documented), Process (operationalized as a procedure), and Implemented (evidence demonstrates the control operates). All three levels must be satisfied for a control to be fully met.');
  space(2);
  colHead([{label:'Maturity level',x:M,w:120},{label:'What it requires',x:M+120,w:180},{label:'Common evidence artefacts',x:M+300,w:170},{label:'Responsible party',x:M+470,w:90}]);
  [
    ['Policy (Level 1)','A documented policy addressing the control requirement exists, is approved, and has been communicated.','Policy document with version, approval date, owner, and distribution record.','CISO / Policy owner'],
    ['Process (Level 2)','A documented procedure operationalizes the policy — defining step-by-step how the control is executed, by whom, and how often.','Procedure document with roles, steps, frequency, and reference to the policy it implements.','Process owner'],
    ['Implemented (Level 3)','Evidence demonstrates the control operated as designed during the assessment period. For r2, the EA samples this evidence.','System configs, access review logs, training completion records, scan results, audit trails — dated and specific to the assessment period.','Control owner / Technical team'],
  ].forEach((r,i)=>row(r,[{x:M,w:120},{x:M+120,w:180},{x:M+300,w:170},{x:M+470,w:90}],i%2===1));
  space(8);

  newPage();
  sectionHead('Step 4 — The 14 control categories');
  body('All HITRUST CSF assessments evaluate controls across the same 14 categories. e1 focuses on a subset within these categories; i1 and r2 cover all 14 in depth. Understand which categories are most material to your environment before your assessment begins.');
  space(4);
  colHead([{label:'Code',x:M,w:45},{label:'Category',x:M+45,w:180},{label:'Key focus areas',x:M+225,w:200},{label:'# refs (i1 scope)',x:M+425,w:80},{label:'e1 included',x:M+505,w:55}]);
  [
    ['00','Information Security Management Program','ISMP charter, governance, risk program oversight','1','No'],
    ['01','Access Control','User registration, MFA, privilege management, remote access, mobile','25','Yes'],
    ['02','Human Resources Security','Screening, terms of employment, awareness training, termination','9','Yes'],
    ['03','Risk Management','Risk assessment methodology, treatment, evaluation','4','Yes'],
    ['04','Security Policy','Policy document, review cadence, approval process','2','No'],
    ['05','Organization of Information Security','Roles, third-party agreements, independent review','11','No'],
    ['06','Compliance','HIPAA compliance, legal requirements, data protection, cryptography regulation','10','No'],
    ['07','Asset Management','Asset inventory, classification, labelling','5','No'],
    ['08','Physical & Environmental Security','Perimeter, entry, equipment, disposal','13','No'],
    ['09','Communications & Operations Management','Change management, malware, backup, logging, network, media','32','Yes'],
    ['10','Systems Acquisition, Development & Maintenance','Requirements, cryptography, vulnerability management, SDLC','13','Yes'],
    ['11','Information Security Incident Management','Reporting, response, evidence collection','5','Yes'],
    ['12','Business Continuity Management','BCP, DR planning and testing','5','No'],
    ['13','Privacy Practices','Notice, consent, collection, use, retention, disposal, subject rights','12','No'],
  ].forEach((r,i)=>row(r,[{x:M,w:45},{x:M+45,w:180},{x:M+225,w:200},{x:M+425,w:80},{x:M+505,w:55}],i%2===1));
  space(8);

  sectionHead('Step 5 — Prepare for the assessment');
  check('Assign a control owner for each of the 14 categories.','Each owner is responsible for gathering and maintaining evidence for their category throughout the assessment period.');
  check('Complete your self-assessment in MyCSF before the External Assessor engagement.','Review every requirement statement, confirm your Policy, Process, and Implemented maturity scores, and attach evidence links.');
  check('Conduct an internal pre-assessment using the control templates.','Identify and remediate gaps before the EA begins their validation. Corrective action taken before the EA\'s fieldwork does not count as a deficiency.');
  check('Prepare your evidence library in a shared repository organized by control category.','Label each artefact with the control reference it supports and the date it was generated. The EA will request specific artefacts via a PBC (Provided by Client) list.');
  check('Brief your control owners on the EA walkthrough process.','Owners should be available for 30–45 minute walkthroughs per category during fieldwork. They should know their controls, their evidence, and any known gaps.');
  space(8);

  sectionHead('Typical HITRUST assessment timeline');
  const tlRows = [
    ['Month 1–2','Kickoff & scoping','Select assessment type, complete MyCSF org setup, set factors (r2), assign control owners.'],
    ['Month 2–4','Gap assessment','Complete self-assessment in MyCSF, identify Policy/Process/Implemented gaps, begin remediation.'],
    ['Month 4–7','Remediation','Implement missing controls, document procedures, collect evidence, build evidence library.'],
    ['Month 7–8','Pre-assessment','Internal mock assessment, evidence review, control owner coaching, final remediation sprint.'],
    ['Month 8–10','EA fieldwork','External Assessor conducts validation — document review, walkthroughs, evidence sampling.'],
    ['Month 10–11','Exception management','Respond to EA findings, implement corrective actions, close exceptions where possible.'],
    ['Month 11–12','Certification issuance','HITRUST reviews EA submission, issues certificate (e1/i1: 1 year validity; r2: 2 year).'],
  ];
  colHead([{label:'Phase',x:M,w:100},{label:'Activity',x:M+100,w:120},{label:'Key outputs and actions',x:M+220,w:330}]);
  tlRows.forEach((r,i)=>row(r,[{x:M,w:100},{x:M+100,w:120},{x:M+220,w:330}],i%2===1));

  footer(doc, W, H, M, 'Verigo-HITRUST-CSF-Quick-Start-Guide');
  doc.save('Verigo-HITRUST-CSF-Quick-Start-Guide.pdf');
}

/* ── DISPATCHER ───────────────────────────────────────────── */
function generate(item, user) {
  if (!window.jspdf || !window.jspdf.jsPDF) { alert('PDF engine is still loading — please try again in a moment.'); return; }
  const u = user || (() => { try { return JSON.parse(localStorage.getItem('verigo_toolkit_user')||'null'); } catch(e){return null;} })() || {};
  switch (item.id) {
    case 'd1': return genSOC2Checklist(u);
    case 'd2': return genCMMCScorecard(u);
    case 'd3': return genISO27001Gap(u);
    case 'd4': return genCrossFramework(u);
    case 'd5': return genNISTProfile(u);
    case 'd6': return genHITRUSTGuide(u);
    default:   return genSOC2Checklist(u);
  }
}

window.RC_PDF = { generate };

})();
