// toolkit-cmmc-data.jsx — CMMC 2.0 (NIST SP 800-171) toolkit contents + PDF engine + lead capture
// Exposes window.TK_CMMC (data, generatePDF, lead helpers)

/* ── POLICY LIBRARY (18) ─────────────────────────────────── */
const C_POLICIES = [
  ['Information Security Policy', 'Top-level security mandate, objectives, and management commitment.'],
  ['Access Control Policy', 'Rules for granting, limiting, and revoking access to FCI and CUI.'],
  ['Identification & Authentication Policy', 'Unique identity and multifactor authentication requirements.'],
  ['Awareness & Training Policy', 'Security awareness, role-based, and insider-threat training.'],
  ['Audit & Accountability Policy', 'Logging, retention, review, and protection of audit records.'],
  ['Configuration Management Policy', 'Baseline configurations, least functionality, and change control.'],
  ['Incident Response Policy', 'Detecting, reporting, and responding to security incidents.'],
  ['Maintenance Policy', 'Controlled system maintenance and maintenance-tool handling.'],
  ['Media Protection Policy', 'Protecting, marking, transporting, and sanitizing CUI media.'],
  ['Personnel Security Policy', 'Screening and protecting CUI across personnel actions.'],
  ['Physical Protection Policy', 'Limiting and monitoring physical access to systems and CUI.'],
  ['Risk Assessment Policy', 'Assessing risk and managing technical vulnerabilities.'],
  ['Security Assessment Policy', 'Assessing controls, SSP maintenance, and POA&M management.'],
  ['System & Communications Protection Policy', 'Boundary protection and cryptographic protection of CUI.'],
  ['System & Information Integrity Policy', 'Flaw remediation, malicious-code protection, and monitoring.'],
  ['CUI Handling & Marking Policy', 'Identifying, marking, and handling Controlled Unclassified Information.'],
  ['Acceptable Use Policy', 'Expected behaviour for users of systems, data, and assets.'],
  ['Supply Chain & External Provider Policy', 'Security requirements for ESPs, cloud, and subcontractors.'],
];

/* ── PROCEDURE SET (16) ──────────────────────────────────── */
const C_PROCEDURES = [
  ['System Security Plan (SSP) Procedure', 'Building and maintaining the SSP that documents the environment.'],
  ['POA&M Management Procedure', 'Logging, tracking, and closing plans of action and milestones.'],
  ['Access Provisioning & Deprovisioning Procedure', 'Granting and removing access on the joiner-mover-leaver path.'],
  ['User Access Review Procedure', 'Periodic recertification of access rights.'],
  ['Audit Log Review Procedure', 'Collecting, reviewing, and correlating audit records.'],
  ['Configuration Baseline & Change Procedure', 'Establishing baselines and controlling changes.'],
  ['Incident Response Procedure', 'Triage, containment, eradication, recovery, and DoD reporting.'],
  ['Media Sanitization & Disposal Procedure', 'Sanitizing or destroying media before reuse or disposal.'],
  ['Vulnerability Scanning & Remediation Procedure', 'Scanning, prioritising, and remediating findings.'],
  ['Risk Assessment Procedure', 'Step-by-step risk identification, analysis, and treatment.'],
  ['Security Control Assessment Procedure', 'Assessing control implementation against 800-171.'],
  ['Backup & Restore Procedure', 'Performing and verifying backups and restores of CUI.'],
  ['Security Awareness & Training Procedure', 'Delivering and tracking awareness training.'],
  ['Account Management Procedure', 'Creating, modifying, disabling, and reviewing accounts.'],
  ['FIPS-Validated Cryptography Procedure', 'Selecting and managing FIPS-validated cryptographic modules.'],
  ['Maintenance Logging Procedure', 'Authorizing, supervising, and logging system maintenance.'],
];

/* ── 14 DOMAINS · 110 NIST SP 800-171 PRACTICES ──────────── */
const CMMC_DOMAINS = [
  { code: 'AC', domain: 'Access Control', icon: 'lock', l1: 4, l2: 22, items: [
    ['3.1.1', 'Limit system access to authorized users, processes, and devices'], ['3.1.2', 'Limit access to permitted transactions and functions'], ['3.1.3', 'Control the flow of CUI'], ['3.1.4', 'Separate the duties of individuals'], ['3.1.5', 'Employ least privilege'], ['3.1.6', 'Use non-privileged accounts for nonsecurity functions'], ['3.1.7', 'Prevent non-privileged users from executing privileged functions'], ['3.1.8', 'Limit unsuccessful logon attempts'], ['3.1.9', 'Provide privacy and security notices'], ['3.1.10', 'Use session lock with pattern-hiding displays'], ['3.1.11', 'Terminate sessions after inactivity'], ['3.1.12', 'Monitor and control remote access sessions'], ['3.1.13', 'Protect remote access with cryptography'], ['3.1.14', 'Route remote access via managed access control points'], ['3.1.15', 'Authorize remote execution of privileged commands'], ['3.1.16', 'Authorize wireless access prior to connection'], ['3.1.17', 'Protect wireless access with authentication and encryption'], ['3.1.18', 'Control connection of mobile devices'], ['3.1.19', 'Encrypt CUI on mobile devices'], ['3.1.20', 'Verify and control connections to external systems'], ['3.1.21', 'Limit use of portable storage on external systems'], ['3.1.22', 'Control CUI on publicly accessible systems'],
  ] },
  { code: 'AT', domain: 'Awareness & Training', icon: 'users', l1: 0, l2: 3, items: [
    ['3.2.1', 'Provide security awareness to managers and users'], ['3.2.2', 'Train personnel for assigned security duties'], ['3.2.3', 'Provide insider-threat awareness training'],
  ] },
  { code: 'AU', domain: 'Audit & Accountability', icon: 'clipboard', l1: 0, l2: 9, items: [
    ['3.3.1', 'Create and retain system audit logs'], ['3.3.2', 'Ensure actions are traceable to users'], ['3.3.3', 'Review and update logged events'], ['3.3.4', 'Alert on audit logging process failures'], ['3.3.5', 'Correlate audit review, analysis, and reporting'], ['3.3.6', 'Provide audit reduction and report generation'], ['3.3.7', 'Synchronize system clocks for timestamps'], ['3.3.8', 'Protect audit information and tools'], ['3.3.9', 'Limit management of audit logging to privileged users'],
  ] },
  { code: 'CM', domain: 'Configuration Management', icon: 'cpu', l1: 0, l2: 9, items: [
    ['3.4.1', 'Establish and maintain baseline configurations'], ['3.4.2', 'Enforce security configuration settings'], ['3.4.3', 'Track, review, and approve/disapprove changes'], ['3.4.4', 'Analyze the security impact of changes'], ['3.4.5', 'Define access restrictions for changes'], ['3.4.6', 'Employ least functionality'], ['3.4.7', 'Restrict nonessential programs, ports, and services'], ['3.4.8', 'Apply deny-by-exception / permit-by-exception'], ['3.4.9', 'Control user-installed software'],
  ] },
  { code: 'IA', domain: 'Identification & Authentication', icon: 'shield', l1: 2, l2: 11, items: [
    ['3.5.1', 'Identify users, processes, and devices'], ['3.5.2', 'Authenticate users, processes, and devices'], ['3.5.3', 'Use multifactor authentication'], ['3.5.4', 'Employ replay-resistant authentication'], ['3.5.5', 'Prevent reuse of identifiers'], ['3.5.6', 'Disable identifiers after inactivity'], ['3.5.7', 'Enforce minimum password complexity'], ['3.5.8', 'Prohibit password reuse for set generations'], ['3.5.9', 'Allow temporary passwords with immediate change'], ['3.5.10', 'Store and transmit only protected passwords'], ['3.5.11', 'Obscure authentication feedback'],
  ] },
  { code: 'IR', domain: 'Incident Response', icon: 'zap', l1: 0, l2: 3, items: [
    ['3.6.1', 'Establish an incident-handling capability'], ['3.6.2', 'Track, document, and report incidents'], ['3.6.3', 'Test the incident response capability'],
  ] },
  { code: 'MA', domain: 'Maintenance', icon: 'refresh', l1: 0, l2: 6, items: [
    ['3.7.1', 'Perform system maintenance'], ['3.7.2', 'Control tools, mechanisms, and personnel for maintenance'], ['3.7.3', 'Sanitize equipment removed for off-site maintenance'], ['3.7.4', 'Check media used in maintenance for malicious code'], ['3.7.5', 'Require MFA for nonlocal maintenance'], ['3.7.6', 'Supervise maintenance by personnel without access'],
  ] },
  { code: 'MP', domain: 'Media Protection', icon: 'file', l1: 1, l2: 9, items: [
    ['3.8.1', 'Protect system media containing CUI'], ['3.8.2', 'Limit access to CUI on system media'], ['3.8.3', 'Sanitize or destroy media before disposal or reuse'], ['3.8.4', 'Mark media with CUI markings and distribution limits'], ['3.8.5', 'Control access to media during transport'], ['3.8.6', 'Use cryptographic protection of CUI on transported media'], ['3.8.7', 'Control the use of removable media'], ['3.8.8', 'Prohibit portable storage with no identifiable owner'], ['3.8.9', 'Protect backup CUI at storage locations'],
  ] },
  { code: 'PS', domain: 'Personnel Security', icon: 'briefcase', l1: 0, l2: 2, items: [
    ['3.9.1', 'Screen individuals prior to authorizing access'], ['3.9.2', 'Protect CUI during and after personnel actions'],
  ] },
  { code: 'PE', domain: 'Physical Protection', icon: 'building', l1: 4, l2: 6, items: [
    ['3.10.1', 'Limit physical access to systems and equipment'], ['3.10.2', 'Protect and monitor the physical facility'], ['3.10.3', 'Escort visitors and monitor activity'], ['3.10.4', 'Maintain audit logs of physical access'], ['3.10.5', 'Control and manage physical access devices'], ['3.10.6', 'Enforce safeguarding at alternate work sites'],
  ] },
  { code: 'RA', domain: 'Risk Assessment', icon: 'target', l1: 0, l2: 3, items: [
    ['3.11.1', 'Periodically assess risk to operations and CUI'], ['3.11.2', 'Scan for vulnerabilities periodically'], ['3.11.3', 'Remediate vulnerabilities per risk assessments'],
  ] },
  { code: 'CA', domain: 'Security Assessment', icon: 'search', l1: 0, l2: 4, items: [
    ['3.12.1', 'Periodically assess security controls'], ['3.12.2', 'Develop and implement plans of action (POA&M)'], ['3.12.3', 'Monitor security controls on an ongoing basis'], ['3.12.4', 'Develop and update the System Security Plan (SSP)'],
  ] },
  { code: 'SC', domain: 'System & Communications Protection', icon: 'network', l1: 2, l2: 16, items: [
    ['3.13.1', 'Monitor and protect communications at boundaries'], ['3.13.2', 'Employ security-promoting architectural designs'], ['3.13.3', 'Separate user and management functionality'], ['3.13.4', 'Prevent unauthorized transfer via shared resources'], ['3.13.5', 'Implement subnetworks for publicly accessible components'], ['3.13.6', 'Deny network traffic by default, allow by exception'], ['3.13.7', 'Prevent split tunneling for remote devices'], ['3.13.8', 'Use cryptography to protect CUI in transit'], ['3.13.9', 'Terminate network connections after sessions'], ['3.13.10', 'Establish and manage cryptographic keys'], ['3.13.11', 'Employ FIPS-validated cryptography'], ['3.13.12', 'Prohibit remote activation of collaborative devices'], ['3.13.13', 'Control and monitor mobile code'], ['3.13.14', 'Control and monitor VoIP'], ['3.13.15', 'Protect authenticity of communications sessions'], ['3.13.16', 'Protect confidentiality of CUI at rest'],
  ] },
  { code: 'SI', domain: 'System & Information Integrity', icon: 'activity', l1: 4, l2: 7, items: [
    ['3.14.1', 'Identify, report, and correct flaws in a timely manner'], ['3.14.2', 'Provide protection from malicious code'], ['3.14.3', 'Monitor security alerts and advisories'], ['3.14.4', 'Update malicious-code protection mechanisms'], ['3.14.5', 'Perform periodic and real-time scans'], ['3.14.6', 'Monitor systems including inbound/outbound traffic'], ['3.14.7', 'Identify unauthorized use of systems'],
  ] },
];

/* ── THREE CERTIFICATION LEVELS ──────────────────────────── */
const CMMC_LEVELS = [
  { id: 1, name: 'Level 1 — Foundational', practices: 17, scope: 'Federal Contract Information (FCI)', assess: 'Annual self-assessment', blurb: '17 basic safeguarding practices drawn from FAR 52.204-21.' },
  { id: 2, name: 'Level 2 — Advanced', practices: 110, scope: 'Controlled Unclassified Information (CUI)', assess: 'Triennial C3PAO assessment', blurb: 'All 110 NIST SP 800-171 controls across 14 domains.', popular: true },
  { id: 3, name: 'Level 3 — Expert', practices: '110+', scope: 'High-priority CUI programs', assess: 'Government-led assessment', blurb: 'Level 2 plus a subset of enhanced NIST SP 800-172 controls.' },
];

/* ── ASSET METADATA ──────────────────────────────────────── */
const C_ASSETS = {
  policies: { icon: 'doc', label: 'Policy Library', count: 18, unit: 'policies',
    file: 'Verigo-CMMC-Policy-Library.pdf', pdfTitle: 'CMMC 2.0 Policy Library',
    blurb: 'The complete, 800-171-aligned policy set — 18 approval-ready policies covering all 14 CMMC domains plus CUI handling and supply chain.',
    intro: 'This index lists the 18 policies in the Verigo Global CMMC 2.0 Policy Library. Each policy ships as an editable, organization-tailored document with purpose, scope, policy statements, roles and responsibilities, and a review cadence — ready to adopt as the documentation backbone of a CMMC-ready environment.' },
  procedures: { icon: 'file', label: 'Procedure Set', count: 16, unit: 'procedures',
    file: 'Verigo-CMMC-Procedure-Set.pdf', pdfTitle: 'CMMC 2.0 Procedure Set',
    blurb: '16 operational procedures — including SSP and POA&M management — that turn policy into repeatable, assessable practice.',
    intro: 'This index lists the 16 procedures in the Verigo Global CMMC 2.0 Procedure Set. Each documents the step-by-step workflow, roles, inputs, outputs, and records — the operating machinery that produces assessment evidence and keeps the SSP and POA&M current.' },
  controls: { icon: 'layers', label: 'Practice Control Templates', count: 110, unit: 'practices',
    file: 'Verigo-CMMC-Practice-Templates.pdf', pdfTitle: 'CMMC 2.0 Practice Control Templates',
    blurb: 'All 110 NIST SP 800-171 practices across the 14 domains, each as an implementation template with objective, guidance, evidence, and owner fields.',
    intro: 'This index lists all 110 NIST SP 800-171 practices that underpin CMMC 2.0 Level 2, organized under the 14 domains. Each practice ships as an implementation template capturing the objective, implementation guidance, assessment objectives, evidence expectations, owner, and status (met / not met / POA&M).' },
  standard: { icon: 'layers', label: 'Standard Toolkit Package', count: 144, unit: 'documents',
    file: 'Verigo-CMMC-Standard-Package.pdf', pdfTitle: 'CMMC 2.0 Standard Toolkit Package',
    blurb: 'The complete Standard package index — every policy, procedure, and practice template in one branded document.',
    intro: 'This index summarizes the complete Verigo Global CMMC 2.0 Standard Toolkit Package — 18 policies, 16 procedures, and all 110 NIST SP 800-171 practice templates, plus SSP and POA&M templates. Each artefact ships as an editable, organization-tailored document, ready to adopt as the documentation backbone of a CMMC assessment.' },
};

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

const C_TIERS = [
  { id: 'starter', name: 'Starter', price: 1495, tagline: 'The complete document toolkit, ready to deploy.',
    forWho: 'Contractors driving their own CMMC readiness.',
    features: ['All 18 policies, 16 procedures & 110 practice templates', 'Editable source files (Word & Excel)', 'SSP & POA&M templates', 'Self-assessment & evidence 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 CUI scope.',
    features: ['Everything in Starter', 'Documents tailored to your scope & level', 'CUI scoping & enclave 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 support, all the way to assessment.',
    forWho: 'Defense suppliers targeting a Level 2 C3PAO assessment.',
    features: ['Everything in Professional', 'Hands-on implementation support', 'SSP & POA&M development', 'C3PAO pre-assessment & mock audit', 'Assessment coordination & evidence packaging', 'Unlimited tailoring & review cycles', 'Dedicated delivery team'] },
];

const C_ADDONS = [
  { id: 'ssp', name: 'SSP & POA&M development', desc: 'We build your System Security Plan and Plan of Action & Milestones from your environment.', price: 3200 },
  { id: 'impl', name: 'Hands-on implementation support', desc: 'A practitioner embeds with your team to operationalize every practice.', price: 6500 },
  { id: 'c3pao', name: 'C3PAO pre-assessment', desc: 'A mock Level 2 assessment with an exceptions log before the certified assessor arrives.', price: 4200 },
  { id: 'scoping', name: 'CUI scoping & enclave workshop', desc: 'Define the assessment boundary and design a CUI enclave to shrink scope.', price: 2200 },
  { id: 'mapping', name: 'Cross-framework mapping', desc: 'Map practices to ISO 27001, SOC 2 & NIST CSF so evidence is reused, not rebuilt.', price: 2400 },
  { id: 'level', name: 'Additional level / enclave', desc: 'Extend the program to another level or operating enclave.', price: 1800 },
];

/* ── LEAD CAPTURE (localStorage) ─────────────────────────── */
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: 'CMMC 2.0', 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: 'CMMC 2.0',
    metadata: lead,
  });
}

/* ── CUSTOM PACKAGE: BASE + OPTION MODULES ───────────────── */
const QUOTE_BASE = { id: 'base', name: 'CMMC 2.0 Document Toolkit', price: 1495,
  desc: 'All 18 policies, 16 procedures and 110 NIST SP 800-171 practice templates as editable source files (Word & Excel), plus the SSP and POA&M templates and self-assessment 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 practice adapted to your scope, level and existing tooling.' },
  { id: 'guidance', name: 'Practitioner guidance & check-ins', price: 1500, desc: 'A named practitioner, a kickoff workshop, and scheduled check-ins through your project.' },
  { id: 'ssp', name: 'SSP & POA&M development', price: 3200, desc: 'We build your System Security Plan and Plan of Action & Milestones from your environment.' },
  { id: 'impl', name: 'Hands-on implementation support', price: 6500, desc: 'A practitioner embeds with your team to operationalize every practice.' },
  { id: 'c3pao', name: 'C3PAO pre-assessment', price: 4200, desc: 'A mock Level 2 assessment with an exceptions log before the certified assessor arrives.' },
  { id: 'scoping', name: 'CUI scoping & enclave workshop', price: 2200, desc: 'Define the assessment boundary and design a CUI enclave to shrink scope.' },
  { id: 'mapping', name: 'Cross-framework mapping', price: 2400, desc: 'Map practices to ISO 27001, SOC 2 & NIST CSF so evidence is reused, not rebuilt.' },
  { id: 'level', name: 'Additional level / enclave', price: 1800, desc: 'Extend the program to another level or operating enclave.' },
];

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.',
  'CMMC Level 2 certification assessments are performed by an independent C3PAO; Verigo prepares and coordinates but does not issue the certificate. Level 1 is a self-assessment.',
  'Pricing assumes a single assessment scope / enclave unless an “Additional level / enclave” module is included.',
  '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.',
  'Taxes, where applicable, are not included in the figures shown.',
];

/* ── CUSTOM QUOTE PDF (jsPDF) ────────────────────────────── */
function generateQuotePDF(order, user) {
  const lib = window.jspdf;
  if (!lib || !lib.jsPDF) { alert('PDF engine is still loading — please try again in a moment.'); 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('CMMC 2.0 · NIST SP 800-171', 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;
  doc.setFont('helvetica', 'normal'); doc.setFontSize(9.5); doc.setTextColor(...GREY);
  const issued = new Date();
  const valid = new Date(issued.getTime() + 30 * 864e5);
  const dstr = (d) => d.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
  doc.text('Quote ' + ref, M, y);
  doc.text('Issued ' + dstr(issued) + '  ·  Valid until ' + dstr(valid), W - M, y, { align: 'right' });
  y += 22;

  doc.setDrawColor(224, 224, 232); doc.setLineWidth(0.5);
  const rows = [];
  if (u.company) rows.push(['Organization', u.company]);
  if (u.name) rows.push(['Contact', u.name + (u.role ? ' · ' + u.role : '')]);
  if (u.email) rows.push(['Email', u.email]);
  if (u.phone) rows.push(['Phone', u.phone]);
  if (u.industry) rows.push(['Industry', u.industry]);
  if (u.employees) rows.push(['Company size', u.employees]);
  if (u.region) rows.push(['Primary region', u.region]);
  if (u.level) rows.push(['Target level', u.level]);
  if (u.systems) rows.push(['In scope', u.systems]);
  if (u.certs) rows.push(['Existing certifications', u.certs]);
  if (u.target) rows.push(['Target timeline', u.target]);
  doc.setFontSize(11); doc.setFont('helvetica', 'bold'); doc.setTextColor(...PURPLE);
  doc.text('Prepared for', M, y); y += 16;
  doc.setFontSize(9.5);
  rows.forEach(([k, v]) => {
    if (y > H - 80) newPage();
    doc.setFont('helvetica', 'bold'); doc.setTextColor(...INK); doc.text(k, M, y);
    doc.setFont('helvetica', 'normal'); doc.setTextColor(...GREY);
    doc.splitTextToSize(String(v), W - M - (M + 150)).forEach((ln, i) => doc.text(ln, M + 150, y + i * 12));
    y += Math.max(14, doc.splitTextToSize(String(v), W - M - (M + 150)).length * 12);
  });
  y += 8;

  if (y > H - 140) newPage();
  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 descLines = doc.splitTextToSize(it.desc, W - M - (M + 90));
    const h = 14 + descLines.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);
    descLines.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);
  });
  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;

  if (y > H - 120) newPage();
  doc.setFont('helvetica', 'bold'); doc.setFontSize(12.5); doc.setTextColor(...PURPLE);
  doc.text('Terms & conditions', M, y); y += 6;
  doc.setDrawColor(...PURPLE); doc.setLineWidth(0.8); doc.line(M, y, W - M, y); y += 16;
  doc.setFont('helvetica', 'normal'); doc.setFontSize(9); doc.setTextColor(...GREY);
  QUOTE_TERMS.forEach((t) => {
    const lines = doc.splitTextToSize(t, W - 2 * M - 14);
    if (y + lines.length * 12 > H - 56) newPage();
    doc.setTextColor(...ORANGE); doc.setFont('helvetica', 'bold'); doc.text('•', M, y);
    doc.setTextColor(...GREY); doc.setFont('helvetica', 'normal');
    lines.forEach((ln, i) => doc.text(ln, M + 14, y + i * 12));
    y += lines.length * 12 + 6;
  });

  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 · Custom quote ' + ref + ' · Indicative — not a binding offer', M, H - 24);
    doc.text(i + ' / ' + totalPages, W - M, H - 24, { align: 'right' });
  }
  doc.save('Verigo-CMMC-Custom-Quote-' + ref + '.pdf');
  return ref;
}

/* ── PDF ENGINE (jsPDF) ──────────────────────────────────── */
function sectionsFor(assetKey) {
  const polSec = { heading: 'Security policy set (18)', items: C_POLICIES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const prcSec = { heading: 'CMMC procedure set (16)', items: C_PROCEDURES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const ctrlSecs = CMMC_DOMAINS.map(g => ({ heading: g.code + ' · ' + g.domain + ' (' + g.items.length + ')', items: g.items.map(([c, t]) => ({ code: c, title: t, desc: '' })) }));
  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 = C_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('CMMC 2.0 · NIST SP 800-171', 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 titleLines = doc.splitTextToSize(it.title, RW);
      const descLines = it.desc ? doc.splitTextToSize(it.desc, RW) : [];
      const h = titleLines.length * 12 + descLines.length * 11 + 9;
      if (y + h > H - 56) newPage();
      doc.setFont('helvetica', 'bold'); doc.setFontSize(9); doc.setTextColor(...ORANGE);
      doc.text(it.code, M, y + 1);
      doc.setFontSize(10.5); doc.setTextColor(...INK);
      titleLines.forEach((ln, i) => doc.text(ln, CX, y + i * 12));
      let yy = y + titleLines.length * 12;
      if (descLines.length) {
        doc.setFont('helvetica', 'normal'); doc.setFontSize(9); doc.setTextColor(...GREY);
        descLines.forEach((ln, i) => doc.text(ln, CX, yy + 2 + i * 11));
        yy += descLines.length * 11;
      }
      y = yy + 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 — for the named recipient', M, H - 24);
    doc.text(i + ' / ' + total, W - M, H - 24, { align: 'right' });
  }
  doc.save(meta.file);
}

window.TK_CMMC = { POLICIES: C_POLICIES, PROCEDURES: C_PROCEDURES, DOMAINS: CMMC_DOMAINS, LEVELS: CMMC_LEVELS, ASSETS: C_ASSETS, TIERS: C_TIERS, ADDONS: C_ADDONS, QUOTE_BASE, QUOTE_MODULES, QUOTE_TERMS, fmtPrice, getUser, storeLead, generatePDF, generateQuotePDF };
