// toolkit-nist-data.jsx — NIST Cybersecurity Framework v2.0 toolkit contents + PDF engine + lead capture
// Exposes window.TK_NIST

/* ── POLICY LIBRARY (14) ─────────────────────────────────── */
const N_POLICIES = [
  ['Cybersecurity Policy', 'Top-level cybersecurity mandate, objectives, and management commitment.'],
  ['Organizational Risk Management Policy', 'How cybersecurity risk is identified, assessed, and treated.'],
  ['Supply Chain Risk Management Policy', 'Cybersecurity requirements for suppliers, vendors, and partners.'],
  ['Asset Management Policy', 'Inventory, classification, and lifecycle management of assets.'],
  ['Vulnerability Management Policy', 'Identifying, prioritizing, and remediating technical vulnerabilities.'],
  ['Identity & Access Management Policy', 'Authentication, access control, and identity lifecycle.'],
  ['Data Security Policy', 'Protecting data in transit, at rest, and throughout its lifecycle.'],
  ['Platform & Infrastructure Security Policy', 'Securing technology components and infrastructure.'],
  ['Security Awareness & Training Policy', 'Role-based training and organizational cybersecurity culture.'],
  ['Continuous Monitoring Policy', 'Ongoing detection of cybersecurity events and anomalies.'],
  ['Incident Response Policy', 'Detecting, analyzing, containing, and recovering from incidents.'],
  ['Business Continuity & Recovery Policy', 'Maintaining and restoring operations after disruption.'],
  ['Cybersecurity Roles & Responsibilities Policy', 'Authorities, accountabilities, and reporting structures.'],
  ['Third-Party & Partner Security Policy', 'Security requirements in external relationships.'],
];

/* ── PROCEDURE SET (12) ──────────────────────────────────── */
const N_PROCEDURES = [
  ['Risk Assessment Procedure', 'Identifying, analyzing, and prioritizing cybersecurity risk.'],
  ['Asset Inventory & Classification Procedure', 'Maintaining a current inventory of assets and their criticality.'],
  ['Vulnerability Scanning & Remediation Procedure', 'Scanning, prioritizing, and remediating findings.'],
  ['Access Provisioning & Review Procedure', 'Granting and periodically reviewing user and system access.'],
  ['Incident Response Procedure', 'Triage, containment, eradication, recovery, and reporting.'],
  ['Business Continuity & Recovery Testing Procedure', 'Testing and maintaining recovery plans.'],
  ['Security Monitoring & Alerting Procedure', 'Collecting events, generating alerts, and reviewing findings.'],
  ['Data Classification & Handling Procedure', 'Classifying and handling data by sensitivity.'],
  ['Supply Chain Risk Assessment Procedure', 'Evaluating cybersecurity risk in supplier relationships.'],
  ['Security Awareness Training Procedure', 'Delivering and tracking role-based training.'],
  ['Change Management Procedure', 'Controlling changes to systems and infrastructure.'],
  ['Threat Intelligence Review Procedure', 'Gathering, analyzing, and acting on threat intelligence.'],
];

/* ── 6 CSF FUNCTIONS · CATEGORIES · SUBCATEGORIES ────────── */
const NIST_FUNCS = [
  { fn: 'GV', name: 'Govern', icon: 'briefcase', cats: [
    { cat: 'GV.OC', name: 'Organizational Context', items: [
      ['GV.OC-01','Organizational mission is understood and informs cybersecurity risk management'],['GV.OC-02','Internal and external stakeholders are understood and cybersecurity risk is considered'],['GV.OC-03','Legal, regulatory, and contractual requirements for cybersecurity are understood'],['GV.OC-04','Critical objectives, capabilities, and services are understood'],['GV.OC-05','Outcomes, capabilities, and services that external parties depend on are understood'],
    ]},
    { cat: 'GV.RM', name: 'Risk Management', items: [
      ['GV.RM-01','Risk management objectives are established and agreed to by organizational stakeholders'],['GV.RM-02','Risk appetite and risk tolerance statements are established, communicated, and maintained'],['GV.RM-03','Organizational cybersecurity risk management is informed by and integrated with risk management program'],['GV.RM-04','Strategic direction describing appropriate risk response options is established'],['GV.RM-05','Lines of communication across the organization are established for cybersecurity risks'],['GV.RM-06','A standardized method for calculating, documenting, categorizing, and prioritizing cybersecurity risks is established'],['GV.RM-07','Strategic opportunities arising from cybersecurity risk management are characterized and are incorporated into the organizational risk strategy'],
    ]},
    { cat: 'GV.RR', name: 'Roles, Responsibilities & Authorities', items: [
      ['GV.RR-01','Organizational leadership is responsible and accountable for cybersecurity risk'],['GV.RR-02','Roles, responsibilities, and authorities related to cybersecurity risk management are established, communicated, understood, and enforced'],['GV.RR-03','Adequate resources are allocated commensurate with cybersecurity risk strategy, roles, responsibilities, and policies'],['GV.RR-04','Cybersecurity is included in human resources practices'],
    ]},
    { cat: 'GV.PO', name: 'Policy', items: [
      ['GV.PO-01','Policy for managing cybersecurity risks is established, communicated, and enforced'],['GV.PO-02','Policy for managing cybersecurity risks is reviewed, updated, communicated, and enforced to reflect changes in requirements and threats'],
    ]},
    { cat: 'GV.OV', name: 'Oversight', items: [
      ['GV.OV-01','Cybersecurity risk management strategy outcomes are reviewed to inform and adjust strategy and direction'],['GV.OV-02','The cybersecurity risk management strategy is reviewed and adjusted to ensure coverage of organizational requirements'],['GV.OV-03','Organizational cybersecurity risk management performance is evaluated and reviewed for adjustments needed'],
    ]},
    { cat: 'GV.SC', name: 'Cybersecurity Supply Chain Risk Management', items: [
      ['GV.SC-01','A cybersecurity supply chain risk management program, strategy, objectives, policies, and processes are established'],['GV.SC-02','Cybersecurity roles and responsibilities for suppliers, customers, and partners are established'],['GV.SC-03','Cybersecurity supply chain risk management is integrated into cybersecurity and enterprise risk management'],['GV.SC-04','Suppliers are known and prioritized by criticality'],['GV.SC-05','Requirements to address cybersecurity risks in supply chains are established, prioritized, and integrated into contracts'],['GV.SC-06','Planning and due diligence are performed to reduce risks before entering into formal supplier or other third-party relationships'],['GV.SC-07','The risks posed by a supplier, their products and services, and other third parties are understood'],['GV.SC-08','Relevant suppliers and other third parties are included in incident planning, response, and recovery activities'],['GV.SC-09','Supply chain security practices are integrated into cybersecurity and enterprise risk management programs'],['GV.SC-10','Cybersecurity supply chain risk management plans include provisions for activities that occur after the conclusion of a partnership or support agreement'],
    ]},
  ]},
  { fn: 'ID', name: 'Identify', icon: 'search', cats: [
    { cat: 'ID.AM', name: 'Asset Management', items: [
      ['ID.AM-01','Inventories of hardware managed by the organization are maintained'],['ID.AM-02','Inventories of software, services, and systems managed by the organization are maintained'],['ID.AM-03','Representations of the organization\'s authorized network communication and internal and external network data flows are maintained'],['ID.AM-04','Inventories of services provided by suppliers are maintained'],['ID.AM-05','Assets are prioritized based on classification, criticality, resources, and impact on mission'],['ID.AM-07','Inventories of data and corresponding metadata for designated data types are maintained'],['ID.AM-08','Systems, hardware, software, services, and data are managed throughout their life cycles'],
    ]},
    { cat: 'ID.RA', name: 'Risk Assessment', items: [
      ['ID.RA-01','Vulnerabilities in assets are identified, validated, and recorded'],['ID.RA-02','Cyber threat intelligence is received from information sharing forums and sources'],['ID.RA-03','Internal and external threats to the organization are identified and recorded'],['ID.RA-04','Potential impacts and likelihoods of threats exploiting vulnerabilities are identified'],['ID.RA-05','Threats, vulnerabilities, likelihoods, and impacts are used to understand inherent risk'],['ID.RA-06','Risk responses are chosen, prioritized, planned, tracked, and communicated'],['ID.RA-07','Changes and exceptions are managed, assessed for risk impact, recorded, and tracked'],['ID.RA-08','Processes for receiving, analyzing, and responding to vulnerability disclosures are established'],['ID.RA-09','The authenticity and integrity of hardware and software are assessed prior to acquisition and use'],['ID.RA-10','Critical suppliers are assessed prior to acquisition'],
    ]},
    { cat: 'ID.IM', name: 'Improvement', items: [
      ['ID.IM-01','Improvements are identified from evaluations'],['ID.IM-02','Improvements are identified from security tests and exercises'],['ID.IM-03','Improvements are identified from execution of operational processes and procedures'],['ID.IM-04','Incident response plans and other cybersecurity plans that affect operations are established, communicated, maintained, and improved'],
    ]},
  ]},
  { fn: 'PR', name: 'Protect', icon: 'shield', cats: [
    { cat: 'PR.AA', name: 'Identity Management, Authentication & Access Control', items: [
      ['PR.AA-01','Identities and credentials for authorized users, services, and hardware are managed by the organization'],['PR.AA-02','Identities are proofed and bound to credentials based on the context of interactions'],['PR.AA-03','Users, services, and hardware are authenticated'],['PR.AA-04','Identity assertions are protected, conveyed, and verified'],['PR.AA-05','Access permissions, entitlements, and authorizations are defined in a policy, managed, enforced, and reviewed'],['PR.AA-06','Physical access to assets is managed, monitored, and enforced commensurate with risk'],
    ]},
    { cat: 'PR.AT', name: 'Awareness & Training', items: [
      ['PR.AT-01','Personnel are provided with awareness and training so that they possess the knowledge and skills to perform general tasks with cybersecurity risks in mind'],['PR.AT-02','Individuals in specialized roles are provided with awareness and training so that they possess the knowledge and skills to perform relevant tasks with cybersecurity risks in mind'],
    ]},
    { cat: 'PR.DS', name: 'Data Security', items: [
      ['PR.DS-01','The confidentiality, integrity, and availability of data-at-rest are protected'],['PR.DS-02','The confidentiality, integrity, and availability of data-in-transit are protected'],['PR.DS-10','The confidentiality, integrity, and availability of data-in-use are protected'],['PR.DS-11','Backups of data are created, protected, maintained, and tested'],
    ]},
    { cat: 'PR.PS', name: 'Platform Security', items: [
      ['PR.PS-01','Configuration management practices are established and applied'],['PR.PS-02','Software is maintained, replaced, and removed commensurate with risk'],['PR.PS-03','Hardware is maintained, replaced, and removed commensurate with risk'],['PR.PS-04','Log records are generated and made available for continuous monitoring'],['PR.PS-05','Installation and execution of unauthorized software are prevented'],['PR.PS-06','Secure software development practices are integrated, and their security is evaluated'],
    ]},
    { cat: 'PR.IR', name: 'Technology Infrastructure Resilience', items: [
      ['PR.IR-01','Networks and environments are protected from unauthorized logical access and usage'],['PR.IR-02','The organization\'s technology assets are protected from environmental threats'],['PR.IR-03','Mechanisms are implemented to achieve resilience requirements in normal and adverse situations'],['PR.IR-04','Adequate resource capacity to ensure availability is maintained'],
    ]},
  ]},
  { fn: 'DE', name: 'Detect', icon: 'activity', cats: [
    { cat: 'DE.CM', name: 'Continuous Monitoring', items: [
      ['DE.CM-01','Networks and network services are monitored to find potentially adverse events'],['DE.CM-02','The physical environment is monitored to find potentially adverse events'],['DE.CM-03','Personnel activity and technology usage are monitored to find potentially adverse events'],['DE.CM-06','External service provider activities and services are monitored to find potentially adverse events'],['DE.CM-09','Computing hardware and software, runtime environments, and their data are monitored to find potentially adverse events'],
    ]},
    { cat: 'DE.AE', name: 'Adverse Event Analysis', items: [
      ['DE.AE-02','Potentially adverse events are analyzed to better understand associated activities'],['DE.AE-03','Information is correlated from multiple sources'],['DE.AE-04','The estimated impact and scope of adverse events are understood'],['DE.AE-06','Information on adverse events is provided to authorized staff and tools'],['DE.AE-07','Cyber threat intelligence and other contextual information are integrated into the analysis'],['DE.AE-08','Incidents are declared when adverse events meet the defined incident criteria'],
    ]},
  ]},
  { fn: 'RS', name: 'Respond', icon: 'zap', cats: [
    { cat: 'RS.MA', name: 'Incident Management', items: [
      ['RS.MA-01','The incident response plan is executed in coordination with relevant third parties once an incident is declared'],['RS.MA-02','Incident reports are triaged and validated'],['RS.MA-03','Incidents are categorized and prioritized'],['RS.MA-04','Incidents are escalated or elevated as needed'],['RS.MA-05','The criteria for initiating incident recovery are applied'],
    ]},
    { cat: 'RS.AN', name: 'Incident Analysis', items: [
      ['RS.AN-03','Analysis is performed to establish what has taken place during an incident and the root cause of the incident'],['RS.AN-06','Actions performed during an investigation are recorded, and the records\' integrity and provenance are preserved'],['RS.AN-07','Cyber threat intelligence and other contextual information are integrated into the incident analysis'],['RS.AN-08','Incidents are categorized consistent with response plans'],
    ]},
    { cat: 'RS.CO', name: 'Incident Response Reporting & Communication', items: [
      ['RS.CO-02','Internal and external stakeholders are notified of incidents'],['RS.CO-03','Information is shared with designated internal and external stakeholders'],
    ]},
    { cat: 'RS.MI', name: 'Incident Mitigation', items: [
      ['RS.MI-01','Incidents are contained'],['RS.MI-02','Incidents are eradicated'],
    ]},
  ]},
  { fn: 'RC', name: 'Recover', icon: 'refresh', cats: [
    { cat: 'RC.RP', name: 'Incident Recovery Plan Execution', items: [
      ['RC.RP-01','The recovery portion of the incident response plan is executed once initiated from the incident response process'],['RC.RP-02','Recovery actions are selected, scoped, prioritized, and performed'],['RC.RP-03','The integrity of backups and other restoration assets is verified before using them for restoration'],['RC.RP-04','Critical mission functions and cybersecurity risk management are considered to establish post-incident operational norms'],['RC.RP-05','The integrity of restored assets is verified, systems and services are restored, and normal operating status is confirmed'],['RC.RP-06','The end of incident recovery is declared based on criteria, and incident-related documentation is completed'],
    ]},
    { cat: 'RC.CO', name: 'Incident Recovery Communication', items: [
      ['RC.CO-03','Recovery activities and progress in restoring operational capabilities are communicated to designated internal and external stakeholders'],['RC.CO-04','Public updates on incident recovery are shared using approved methods and messaging'],
    ]},
  ]},
];

/* ── FOUR IMPLEMENTATION TIERS ───────────────────────────── */
const NIST_TIERS = [
  { id: 'tier1', name: 'Tier 1 — Partial', desc: 'Cybersecurity activities are ad hoc; risk management is not formalized.', blurb: 'Starting point — ad hoc practices, risk management not integrated.' },
  { id: 'tier2', name: 'Tier 2 — Risk Informed', desc: 'Risk management practices exist but are not org-wide or consistently applied.', blurb: 'Risk-aware but inconsistent — practices vary across the organization.' },
  { id: 'tier3', name: 'Tier 3 — Repeatable', desc: 'Formal, approved risk management practices are consistently applied org-wide.', blurb: 'Formal and consistent — risk management is org-wide policy.', popular: true },
  { id: 'tier4', name: 'Tier 4 — Adaptive', desc: 'Cybersecurity practices are continuously adapted based on lessons learned and threat intelligence.', blurb: 'Optimizing — continuous adaptation based on threats and business needs.' },
];

// Count total subcategories
const N_CTRL_COUNT = NIST_FUNCS.reduce((a, f) => a + f.cats.reduce((b, c) => b + c.items.length, 0), 0);

/* ── ASSET METADATA ──────────────────────────────────────── */
const N_ASSETS = {
  policies: { icon: 'doc', label: 'Policy Library', count: 14, unit: 'policies',
    file: 'Verigo-NIST-Policy-Library.pdf', pdfTitle: 'NIST CSF v2.0 Policy Library',
    blurb: 'The complete, CSF v2.0-aligned policy set — 14 approval-ready policies covering all six functions.',
    intro: 'This index lists the 14 policies in the Verigo Global NIST CSF v2.0 Policy Library. Each ships as an editable document covering purpose, scope, policy statements, roles and responsibilities, and review cadence — ready to adopt as the documentation backbone of your CSF program.' },
  procedures: { icon: 'file', label: 'Procedure Set', count: 12, unit: 'procedures',
    file: 'Verigo-NIST-Procedure-Set.pdf', pdfTitle: 'NIST CSF v2.0 Procedure Set',
    blurb: '12 operational procedures that turn CSF policy into repeatable, evidence-generating practice.',
    intro: 'This index lists the 12 procedures in the Verigo Global NIST CSF v2.0 Procedure Set. Each documents the step-by-step workflow, roles, inputs, outputs, and records.' },
  controls: { icon: 'layers', label: 'Subcategory Templates', count: N_CTRL_COUNT, unit: 'subcategories',
    file: 'Verigo-NIST-Subcategory-Templates.pdf', pdfTitle: 'NIST CSF v2.0 Subcategory Templates',
    blurb: `All ${N_CTRL_COUNT} CSF v2.0 subcategories across the six functions, each as an implementation template with outcome, guidance, evidence, and owner fields.`,
    intro: `This index lists the ${N_CTRL_COUNT} subcategories in the NIST CSF v2.0, organized under the six functions — Govern, Identify, Protect, Detect, Respond, and Recover. Each subcategory ships as a template capturing the outcome statement, implementation guidance, evidence expectations, current/target tier, and owner.` },
  standard: { icon: 'layers', label: 'Standard Toolkit Package', count: 14 + 12 + N_CTRL_COUNT, unit: 'documents',
    file: 'Verigo-NIST-Standard-Package.pdf', pdfTitle: 'NIST CSF v2.0 Standard Toolkit Package',
    blurb: 'The complete package — every policy, procedure, and subcategory template in one branded document.',
    intro: `This index summarizes the complete Verigo Global NIST CSF v2.0 Standard Toolkit Package — 14 policies, 12 procedures, and all ${N_CTRL_COUNT} subcategory templates across the six functions.` },
};

/* ── PURCHASE: TIERS + ADD-ONS ───────────────────────────── */
const fmtPrice = (n) => '$' + Number(n).toLocaleString('en-US');

const N_TIERS = [
  { id: 'starter', name: 'Starter', price: 1495, tagline: 'The complete document toolkit, ready to deploy.',
    forWho: 'Teams driving their own NIST CSF implementation.',
    features: [`All 14 policies, 12 procedures & ${N_CTRL_COUNT} subcategory templates`, 'Editable source files (Word & Excel)', 'Current & target profile templates', 'Implementation tier checklists', '12 months of content updates', 'Email support'] },
  { id: 'professional', name: 'Professional', price: 4950, tagline: 'The toolkit tailored to you, with practitioner guidance.', popular: true,
    forWho: 'Organizations that want the toolkit shaped to their profile.',
    features: ['Everything in Starter', 'Documents tailored to your scope & target tier', 'Current/target profile workshop', 'Online readiness self-assessment', 'Cross-framework control mapping', 'Named practitioner with scheduled check-ins', 'Priority support'] },
  { id: 'enterprise', name: 'Enterprise', price: 11900, priceNote: 'from', tagline: 'End-to-end implementation, from profile to practice.',
    forWho: 'Organizations pursuing Tier 3/4 or regulatory alignment.',
    features: ['Everything in Professional', 'Hands-on implementation support', 'Full profile gap analysis & remediation', 'Regulatory mapping (HIPAA, FISMA, PCI)', 'Continuous monitoring program design', 'Dedicated delivery team'] },
];

const N_ADDONS = [
  { id: 'impl', name: 'Hands-on implementation support', desc: 'A practitioner embeds with your team to operationalize every subcategory.', price: 6500 },
  { id: 'profile', name: 'Current/target profile workshop', desc: 'Facilitated workshop to define your current and target CSF profiles.', price: 2200 },
  { id: 'gap', name: 'Full profile gap analysis', desc: 'Scored gap analysis across all 6 functions with a remediation roadmap.', price: 2900 },
  { id: 'mapping', name: 'Cross-framework regulatory mapping', desc: 'Map CSF subcategories to HIPAA, FISMA, PCI-DSS, and ISO 27001.', price: 2400 },
  { id: 'monitor', name: 'Continuous monitoring program design', desc: 'Design a monitoring program covering DE.CM, RS and RC outcomes.', price: 3200 },
];

/* ── LEAD CAPTURE ─────────────────────────────────────────── */
const LEAD_KEY = 'verigo_toolkit_leads';
const USER_KEY = 'verigo_toolkit_user';
function getUser() { try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); } catch (e) { return null; } }
function storeLead(lead) {
  try {
    const rec = { ...lead, toolkit: 'NIST CSF', ts: new Date().toISOString() };
    const all = JSON.parse(localStorage.getItem(LEAD_KEY) || '[]');
    all.push(rec);
    localStorage.setItem(LEAD_KEY, JSON.stringify(all));
    const prev = getUser() || {};
    const merged = { ...prev };
    Object.keys(lead).forEach((k) => { if (k !== 'source' && lead[k] !== undefined && lead[k] !== '') merged[k] = lead[k]; });
    localStorage.setItem(USER_KEY, JSON.stringify(merged));
  } catch (e) { /* storage unavailable */ }
  window.submitInquiry && window.submitInquiry({
    form_type: lead.source || 'toolkit',
    name: lead.name, email: lead.email, company: lead.company, phone: lead.phone,
    framework: 'NIST CSF',
    metadata: lead,
  });
}

/* ── CUSTOM PACKAGE: BASE + OPTION MODULES ───────────────── */
const QUOTE_BASE = { id: 'base', name: 'NIST CSF v2.0 Document Toolkit', price: 1495,
  desc: `All 14 policies, 12 procedures and ${N_CTRL_COUNT} CSF v2.0 subcategory templates as editable source files (Word & Excel), plus current/target profile templates and tier checklists. 12 months of content updates included.` };
const QUOTE_MODULES = [
  { id: 'tailor', name: 'Document tailoring to your scope', price: 1950, desc: 'Every policy, procedure and subcategory adapted to your scope, sector and target tier.' },
  { id: 'guidance', name: 'Practitioner guidance & check-ins', price: 1500, desc: 'A named practitioner, a kickoff workshop, and scheduled check-ins through your project.' },
  { id: 'impl', name: 'Hands-on implementation support', price: 6500, desc: 'A practitioner embeds with your team to operationalize every subcategory.' },
  { id: 'profile', name: 'Current/target profile workshop', price: 2200, desc: 'Facilitated workshop to define your current and target CSF profiles.' },
  { id: 'gap', name: 'Full profile gap analysis', price: 2900, desc: 'Scored gap analysis across all 6 functions with a prioritized remediation roadmap.' },
  { id: 'mapping', name: 'Cross-framework regulatory mapping', price: 2400, desc: 'Map CSF subcategories to HIPAA, FISMA, PCI-DSS, and ISO 27001.' },
  { id: 'monitor', name: 'Continuous monitoring program design', price: 3200, desc: 'Design a monitoring program covering Detect, Respond and Recover outcomes.' },
];

const QUOTE_TERMS = [
  'This quote is indicative and valid for 30 days from the date of issue.',
  'No payment is due at this stage. A senior practitioner will confirm final scope and pricing within one business day.',
  'NIST CSF is a voluntary framework; there is no formal third-party certification. Verigo supports adoption, alignment, and self-assessment against the framework.',
  'Pricing assumes a single organizational scope unless specified otherwise.',
  'Document tailoring and delivery typically begin within 5 business days of a signed engagement.',
  "All deliverables are provided under mutual confidentiality; documents are licensed for the named organization's internal use.",
];

/* ── PDF ENGINE ───────────────────────────────────────────── */
function sectionsFor(assetKey) {
  const polSec = { heading: 'Policy set (14)', items: N_POLICIES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const prcSec = { heading: 'Procedure set (12)', items: N_PROCEDURES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const ctrlSecs = NIST_FUNCS.map(f => f.cats.map(c => ({ heading: c.cat + ' · ' + c.name + ' (' + c.items.length + ')', items: c.items.map(([id, t]) => ({ code: id, title: t, desc: '' })) }))).flat();
  if (assetKey === 'policies') return [polSec];
  if (assetKey === 'procedures') return [prcSec];
  if (assetKey === 'standard') return [polSec, prcSec, ...ctrlSecs];
  return ctrlSecs;
}

function generatePDF(assetKey, user) {
  const lib = window.jspdf; if (!lib || !lib.jsPDF) { alert('PDF engine is still loading — please try again in a moment.'); return; }
  const meta = N_ASSETS[assetKey];
  const doc = new lib.jsPDF({ unit: 'pt', format: 'a4' }); const W = doc.internal.pageSize.getWidth(); const H = doc.internal.pageSize.getHeight();
  const M = 50, CX = M + 56, RW = W - M - CX;
  const PURPLE = [91, 46, 145], ORANGE = [232, 98, 42], INK = [30, 30, 46], GREY = [120, 120, 134];
  let y = 0;
  const header = () => { 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('NIST CSF v2.0',W-M-20,35,{align:'right'}); y=100; };
  const newPage = () => { doc.addPage(); header(); }; header();
  doc.setTextColor(...INK); doc.setFont('helvetica','bold'); doc.setFontSize(21); doc.text(meta.pdfTitle,M,y); y+=12;
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,y,M+54,y); y+=22;
  doc.setFont('helvetica','normal'); doc.setFontSize(10); doc.setTextColor(...GREY);
  doc.splitTextToSize(meta.intro, W-2*M).forEach(ln => { doc.text(ln,M,y); y+=14; }); y+=6;
  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+=20;
  }
  sectionsFor(assetKey).forEach(sec => {
    if (y>H-120) newPage(); y+=8;
    doc.setFont('helvetica','bold'); doc.setFontSize(12.5); doc.setTextColor(...PURPLE); doc.text(sec.heading,M,y); y+=6;
    doc.setDrawColor(...PURPLE); doc.setLineWidth(0.8); doc.line(M,y,W-M,y); y+=16;
    sec.items.forEach(it => {
      const tl = doc.splitTextToSize(it.title, RW); const h = tl.length*12+9; if(y+h>H-56)newPage();
      doc.setFont('helvetica','bold'); doc.setFontSize(8.5); doc.setTextColor(...ORANGE); doc.text(it.code,M,y+1);
      doc.setFontSize(10); doc.setTextColor(...INK); tl.forEach((ln,i) => doc.text(ln,CX,y+i*12)); y+=tl.length*12+9;
    });
  });
  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 · Confidential',M,H-24);doc.text(i+' / '+total,W-M,H-24,{align:'right'});}
  doc.save(meta.file);
}

function generateQuotePDF(order, user) {
  const lib = window.jspdf; if (!lib||!lib.jsPDF){alert('PDF engine is still loading.');return null;}
  const u=user||{}; const ref=order.ref||('VG-'+Date.now().toString(36).toUpperCase().slice(-6));
  const lineItems=[{name:QUOTE_BASE.name,price:QUOTE_BASE.price,desc:QUOTE_BASE.desc}].concat(order.modules.map(m=>({name:m.name,price:m.price,desc:m.desc})));
  const total=lineItems.reduce((s,i)=>s+i.price,0);
  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]; const fmt=n=>'$'+Number(n).toLocaleString('en-US'); let y=0;
  const header=()=>{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('NIST CSF v2.0',W-M-20,35,{align:'right'});y=100;};
  const newPage=()=>{doc.addPage();header();};header();
  doc.setTextColor(...INK);doc.setFont('helvetica','bold');doc.setFontSize(21);doc.text('Custom Package Quote',M,y);y+=12;
  doc.setDrawColor(...ORANGE);doc.setLineWidth(2.5);doc.line(M,y,M+54,y);y+=20;
  const issued=new Date(); const dstr=d=>d.toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'});
  doc.setFont('helvetica','normal');doc.setFontSize(9.5);doc.setTextColor(...GREY);doc.text('Quote '+ref,M,y);doc.text('Issued '+dstr(issued),W-M,y,{align:'right'});y+=22;
  if(u.company||u.name){doc.setFontSize(9);doc.setTextColor(...PURPLE);doc.setFont('helvetica','bold');doc.text('Prepared for '+(u.company||u.name),M,y);doc.setFont('helvetica','normal');doc.setTextColor(...GREY);doc.text(dstr(issued),W-M,y,{align:'right'});y+=20;}
  doc.setFont('helvetica','bold');doc.setFontSize(12.5);doc.setTextColor(...PURPLE);doc.text('Your custom package',M,y);y+=6;
  doc.setDrawColor(...PURPLE);doc.setLineWidth(0.8);doc.line(M,y,W-M,y);y+=18;
  lineItems.forEach((it,idx)=>{const dl=doc.splitTextToSize(it.desc,W-M-(M+90));const h=14+dl.length*11+10;if(y+h>H-70)newPage();doc.setFont('helvetica','bold');doc.setFontSize(10.5);doc.setTextColor(...INK);doc.text((idx===0?'Base · ':'')+it.name,M,y);doc.setTextColor(...PURPLE);doc.text(fmt(it.price),W-M,y,{align:'right'});y+=14;doc.setFont('helvetica','normal');doc.setFontSize(9);doc.setTextColor(...GREY);dl.forEach(ln=>{doc.text(ln,M,y);y+=11;});y+=10;doc.setDrawColor(237,237,245);doc.setLineWidth(0.5);doc.line(M,y-4,W-M,y-4);});
  if(y>H-70)newPage();doc.setFillColor(245,245,247);doc.rect(M,y-4,W-2*M,30,'F');doc.setFont('helvetica','bold');doc.setFontSize(11);doc.setTextColor(...INK);doc.text('Indicative total',M+12,y+15);doc.setFontSize(15);doc.setTextColor(...PURPLE);doc.text(fmt(total),W-M-12,y+16,{align:'right'});y+=44;
  const totalPages=doc.internal.getNumberOfPages();for(let i=1;i<=totalPages;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 · Quote '+ref+' · Indicative',M,H-24);doc.text(i+' / '+totalPages,W-M,H-24,{align:'right'});}
  doc.save('Verigo-NIST-Custom-Quote-'+ref+'.pdf');return ref;
}

window.TK_NIST = { POLICIES: N_POLICIES, PROCEDURES: N_PROCEDURES, FUNCS: NIST_FUNCS, TIERS: NIST_TIERS, ASSETS: N_ASSETS, PKG_TIERS: N_TIERS, ADDONS: N_ADDONS, QUOTE_BASE, QUOTE_MODULES, QUOTE_TERMS, fmtPrice, getUser, storeLead, generatePDF, generateQuotePDF, CTRL_COUNT: N_CTRL_COUNT };
