// toolkit-hitrust-data.jsx — HITRUST CSF toolkit contents + PDF engine + lead capture
// Exposes window.TK_HITRUST (data, generatePDF, lead helpers)

/* ── POLICY LIBRARY (20) ─────────────────────────────────── */
const H_POLICIES = [
  ['Information Security Management Program Policy', 'Top-level ISMP mandate, objectives, and management commitment.'],
  ['Access Control Policy', 'Rules for granting, reviewing, and revoking system access.'],
  ['Human Resources Security Policy', 'Security across the employment lifecycle.'],
  ['Risk Management Policy', 'How information risk is assessed, treated, and evaluated.'],
  ['Information Security Policy', 'The overarching security policy document and review cadence.'],
  ['Organization of Information Security Policy', 'Roles, responsibilities, and external-party coordination.'],
  ['Compliance Policy', 'Meeting legal, regulatory, and contractual obligations including HIPAA.'],
  ['Asset Management Policy', 'Inventory, ownership, classification, and handling of assets.'],
  ['Physical & Environmental Security Policy', 'Protection of facilities, equipment, and secure areas.'],
  ['Communications & Operations Management Policy', 'Secure day-to-day operation of systems and networks.'],
  ['Malware Protection Policy', 'Protection against malicious and mobile code.'],
  ['Backup Policy', 'Backup scope, frequency, encryption, and restoration testing.'],
  ['Network Security Policy', 'Segmentation, controls, and monitoring of networks.'],
  ['Secure Development Policy', 'Security requirements across the development lifecycle.'],
  ['Cryptography & Key Management Policy', 'Use of encryption and cryptographic key management.'],
  ['Vulnerability & Patch Management Policy', 'Identifying and remediating technical vulnerabilities.'],
  ['Incident Management Policy', 'Detecting, reporting, and responding to security incidents.'],
  ['Business Continuity Policy', 'Maintaining and recovering operations during disruption.'],
  ['Privacy Policy', 'Lawful collection, use, retention, and disclosure of covered information.'],
  ['Third-Party & Supplier Security Policy', 'Security requirements for vendors and business associates.'],
];

/* ── PROCEDURE SET (16) ──────────────────────────────────── */
const H_PROCEDURES = [
  ['Risk Assessment Procedure', 'Step-by-step risk identification, analysis, and treatment.'],
  ['Access Provisioning & Deprovisioning Procedure', 'Granting and removing access on the joiner-mover-leaver path.'],
  ['User Access Review Procedure', 'Periodic recertification of access rights.'],
  ['Change Management Procedure', 'Requesting, approving, and deploying changes.'],
  ['Incident Response Procedure', 'Triage, containment, eradication, and recovery steps.'],
  ['Backup & Restore Procedure', 'Performing and verifying backups and restores.'],
  ['Business Continuity & DR Testing Procedure', 'Exercising continuity and recovery plans.'],
  ['Audit Logging & Monitoring Procedure', 'Collecting, protecting, and reviewing audit logs.'],
  ['Vulnerability & Patch Management Procedure', 'Scanning, prioritising, and remediating findings.'],
  ['Malware Protection Procedure', 'Deploying and updating anti-malware controls.'],
  ['Media Handling & Disposal Procedure', 'Handling, transporting, and securely disposing of media.'],
  ['Security Awareness & Training Procedure', 'Delivering and tracking awareness training.'],
  ['Data Classification & Handling Procedure', 'Labelling and handling information by sensitivity.'],
  ['Cryptographic Key Management Procedure', 'Generating, storing, rotating, and retiring keys.'],
  ['Privacy Rights & Consent Procedure', 'Handling consent, access, and disclosure requests.'],
  ['Third-Party Risk Assessment Procedure', 'Evaluating and onboarding vendors and business associates.'],
];

/* ── 14 CSF CONTROL CATEGORIES · CONTROL REFERENCES ──────── */
const HITRUST_CATS = [
  { code: '00', name: 'Information Security Management Program', icon: 'compass', e1: false, items: [
    ['00.a', 'Information Security Management Program'],
  ] },
  { code: '01', name: 'Access Control', icon: 'lock', e1: true, items: [
    ['01.a', 'Access Control Policy'], ['01.b', 'User Registration'], ['01.c', 'Privilege Management'], ['01.d', 'User Password Management'], ['01.e', 'Review of User Access Rights'], ['01.f', 'Password Use'], ['01.g', 'Unattended User Equipment'], ['01.h', 'Clear Desk and Clear Screen Policy'], ['01.i', 'Policy on the Use of Network Services'], ['01.j', 'User Authentication for External Connections'], ['01.k', 'Equipment Identification in Networks'], ['01.l', 'Remote Diagnostic and Configuration Port Protection'], ['01.m', 'Segregation in Networks'], ['01.n', 'Network Connection Control'], ['01.o', 'Network Routing Control'], ['01.p', 'Secure Log-on Procedures'], ['01.q', 'User Identification and Authentication'], ['01.r', 'Password Management System'], ['01.s', 'Use of System Utilities'], ['01.t', 'Session Time-out'], ['01.u', 'Limitation of Connection Time'], ['01.v', 'Information Access Restriction'], ['01.w', 'Sensitive System Isolation'], ['01.x', 'Mobile Computing and Communications'], ['01.y', 'Teleworking'],
  ] },
  { code: '02', name: 'Human Resources Security', icon: 'users', e1: true, items: [
    ['02.a', 'Roles and Responsibilities'], ['02.b', 'Screening'], ['02.c', 'Terms and Conditions of Employment'], ['02.d', 'Management Responsibilities'], ['02.e', 'Information Security Awareness, Education, and Training'], ['02.f', 'Disciplinary Process'], ['02.g', 'Termination or Change Responsibilities'], ['02.h', 'Return of Assets'], ['02.i', 'Removal of Access Rights'],
  ] },
  { code: '03', name: 'Risk Management', icon: 'target', e1: true, items: [
    ['03.a', 'Risk Management Program'], ['03.b', 'Performing Risk Assessments'], ['03.c', 'Risk Mitigation'], ['03.d', 'Risk Evaluation'],
  ] },
  { code: '04', name: 'Security Policy', icon: 'file', e1: false, items: [
    ['04.a', 'Information Security Policy Document'], ['04.b', 'Review of the Information Security Policy'],
  ] },
  { code: '05', name: 'Organization of Information Security', icon: 'briefcase', e1: false, items: [
    ['05.a', 'Management Commitment to Information Security'], ['05.b', 'Information Security Coordination'], ['05.c', 'Allocation of Information Security Responsibilities'], ['05.d', 'Authorization Process for Information Assets and Facilities'], ['05.e', 'Confidentiality Agreements'], ['05.f', 'Contact with Authorities'], ['05.g', 'Contact with Special Interest Groups'], ['05.h', 'Independent Review of Information Security'], ['05.i', 'Identification of Risks Related to External Parties'], ['05.j', 'Addressing Security When Dealing with Customers'], ['05.k', 'Addressing Security in Third-Party Agreements'],
  ] },
  { code: '06', name: 'Compliance', icon: 'scale', e1: false, items: [
    ['06.a', 'Identification of Applicable Legislation'], ['06.b', 'Intellectual Property Rights'], ['06.c', 'Protection of Organizational Records'], ['06.d', 'Data Protection and Privacy of Covered Information'], ['06.e', 'Prevention of Misuse of Information Assets'], ['06.f', 'Regulation of Cryptographic Controls'], ['06.g', 'Compliance with Security Policies and Standards'], ['06.h', 'Technical Compliance Checking'], ['06.i', 'Information Systems Audit Controls'], ['06.j', 'Protection of Information Systems Audit Tools'],
  ] },
  { code: '07', name: 'Asset Management', icon: 'layers', e1: false, items: [
    ['07.a', 'Inventory of Assets'], ['07.b', 'Ownership of Assets'], ['07.c', 'Acceptable Use of Assets'], ['07.d', 'Classification Guidelines'], ['07.e', 'Information Labeling and Handling'],
  ] },
  { code: '08', name: 'Physical and Environmental Security', icon: 'building', e1: false, items: [
    ['08.a', 'Physical Security Perimeter'], ['08.b', 'Physical Entry Controls'], ['08.c', 'Securing Offices, Rooms, and Facilities'], ['08.d', 'Protecting Against External and Environmental Threats'], ['08.e', 'Working in Secure Areas'], ['08.f', 'Public Access, Delivery, and Loading Areas'], ['08.g', 'Equipment Siting and Protection'], ['08.h', 'Supporting Utilities'], ['08.i', 'Cabling Security'], ['08.j', 'Equipment Maintenance'], ['08.k', 'Security of Equipment Off-Premises'], ['08.l', 'Secure Disposal or Re-Use of Equipment'], ['08.m', 'Removal of Property'],
  ] },
  { code: '09', name: 'Communications and Operations Management', icon: 'network', e1: true, items: [
    ['09.a', 'Documented Operating Procedures'], ['09.b', 'Change Management'], ['09.c', 'Segregation of Duties'], ['09.d', 'Separation of Development, Test, and Operational Environments'], ['09.e', 'Service Delivery'], ['09.f', 'Monitoring and Review of Third-Party Services'], ['09.g', 'Managing Changes to Third-Party Services'], ['09.h', 'Capacity Management'], ['09.i', 'System Acceptance'], ['09.j', 'Controls Against Malicious Code'], ['09.k', 'Controls Against Mobile Code'], ['09.l', 'Back-up'], ['09.m', 'Network Controls'], ['09.n', 'Security of Network Services'], ['09.o', 'Management of Removable Media'], ['09.p', 'Disposal of Media'], ['09.q', 'Information Handling Procedures'], ['09.r', 'Security of System Documentation'], ['09.s', 'Information Exchange Policies and Procedures'], ['09.t', 'Exchange Agreements'], ['09.u', 'Physical Media in Transit'], ['09.v', 'Electronic Messaging'], ['09.w', 'Interconnected Business Information Systems'], ['09.x', 'Electronic Commerce Services'], ['09.y', 'On-line Transactions'], ['09.z', 'Publicly Available Information'], ['09.aa', 'Audit Logging'], ['09.ab', 'Monitoring System Use'], ['09.ac', 'Protection of Log Information'], ['09.ad', 'Administrator and Operator Logs'], ['09.ae', 'Fault Logging'], ['09.af', 'Clock Synchronization'],
  ] },
  { code: '10', name: 'Information Systems Acquisition, Development & Maintenance', icon: 'cpu', e1: true, items: [
    ['10.a', 'Security Requirements Analysis and Specification'], ['10.b', 'Input Data Validation'], ['10.c', 'Control of Internal Processing'], ['10.d', 'Message Integrity'], ['10.e', 'Output Data Validation'], ['10.f', 'Policy on the Use of Cryptographic Controls'], ['10.g', 'Key Management'], ['10.h', 'Control of Operational Software'], ['10.i', 'Protection of System Test Data'], ['10.j', 'Access Control to Program Source Code'], ['10.k', 'Change Control Procedures'], ['10.l', 'Outsourced Software Development'], ['10.m', 'Control of Technical Vulnerabilities'],
  ] },
  { code: '11', name: 'Information Security Incident Management', icon: 'zap', e1: true, items: [
    ['11.a', 'Reporting Information Security Events'], ['11.b', 'Reporting Security Weaknesses'], ['11.c', 'Responsibilities and Procedures'], ['11.d', 'Learning from Information Security Incidents'], ['11.e', 'Collection of Evidence'],
  ] },
  { code: '12', name: 'Business Continuity Management', icon: 'refresh', e1: false, items: [
    ['12.a', 'Including Information Security in the Business Continuity Process'], ['12.b', 'Business Continuity and Risk Assessment'], ['12.c', 'Developing and Implementing Continuity Plans'], ['12.d', 'Business Continuity Planning Framework'], ['12.e', 'Testing, Maintaining, and Re-Assessing Business Continuity Plans'],
  ] },
  { code: '13', name: 'Privacy Practices', icon: 'heart', e1: false, items: [
    ['13.a', 'Privacy Notice'], ['13.b', 'Openness and Transparency'], ['13.c', 'Accounting of Disclosures'], ['13.d', 'Choice and Consent'], ['13.e', 'Collection'], ['13.f', 'Use and Disclosure'], ['13.g', 'Retention and Disposal'], ['13.h', 'Data Quality and Integrity'], ['13.i', 'Inquiry, Complaint, and Dispute Resolution'], ['13.j', 'Information for Individuals'], ['13.k', 'Privacy Reviews and Audits'], ['13.l', 'Privacy in the Workforce'],
  ] },
];

/* ── THREE ASSESSMENT TYPES ──────────────────────────────── */
const HITRUST_ASSESSMENTS = [
  { id: 'e1', name: 'e1 — Essentials, 1-year', reqs: 44, validity: '1 year', assurance: 'Foundational', blurb: '44 requirements covering essential cybersecurity hygiene — a fast entry point.' },
  { id: 'i1', name: 'i1 — Implemented, 1-year', reqs: 182, validity: '1 year', assurance: 'Moderate', blurb: '182 requirements covering leading security practices and threat-adaptive controls.', popular: true },
  { id: 'r2', name: 'r2 — Risk-based, 2-year', reqs: '200+', validity: '2 years', assurance: 'High / Certifiable', blurb: 'Tailored requirement set for the highest assurance and full HITRUST CSF certification.' },
];

/* ── ASSET METADATA ──────────────────────────────────────── */
const H_ASSETS = {
  policies: { icon: 'doc', label: 'Policy Library', count: 20, unit: 'policies',
    file: 'Verigo-HITRUST-Policy-Library.pdf', pdfTitle: 'HITRUST CSF Policy Library',
    blurb: 'The complete, CSF-aligned policy set — 20 approval-ready policies covering all 14 HITRUST control categories.',
    intro: 'This index lists the 20 policies in the Verigo Global HITRUST CSF Policy Library. Each 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 certifiable CSF program.' },
  procedures: { icon: 'file', label: 'Procedure Set', count: 16, unit: 'procedures',
    file: 'Verigo-HITRUST-Procedure-Set.pdf', pdfTitle: 'HITRUST CSF Procedure Set',
    blurb: '16 operational procedures that turn policy into repeatable practice — so evidence is generated by the process, not assembled before the assessment.',
    intro: 'This index lists the 16 procedures in the Verigo Global HITRUST CSF Procedure Set. Each documents the step-by-step workflow, roles, inputs, outputs, and records — the operating machinery that keeps your CSF program running and continuously assessment-ready.' },
  controls: { icon: 'layers', label: 'Control Reference Templates', count: 147, unit: 'references',
    file: 'Verigo-HITRUST-Control-References.pdf', pdfTitle: 'HITRUST CSF Control Reference Templates',
    blurb: 'All 147 CSF control references across the 14 categories, each as an implementation template with objective, guidance, evidence, and owner fields.',
    intro: 'This index lists the 147 HITRUST CSF control references organized under the 14 control categories. Each reference ships as an implementation template capturing the control objective, implementation guidance, the maturity levels (policy, process, implemented), evidence expectations, owner, and status — ready to map into MyCSF.' },
  standard: { icon: 'layers', label: 'Standard Toolkit Package', count: 183, unit: 'documents',
    file: 'Verigo-HITRUST-Standard-Package.pdf', pdfTitle: 'HITRUST CSF Standard Toolkit Package',
    blurb: 'The complete Standard package index — every policy, procedure, and control reference in one branded document.',
    intro: 'This index summarizes the complete Verigo Global HITRUST CSF Standard Toolkit Package — 20 policies, 16 procedures, and all 147 control reference templates across the 14 categories. Each artefact ships as an editable, organization-tailored document, ready to adopt as the documentation backbone of an e1, i1, or r2 assessment.' },
};

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

const H_TIERS = [
  { id: 'starter', name: 'Starter', price: 1495, tagline: 'The complete document toolkit, ready to deploy.',
    forWho: 'Teams driving their own HITRUST readiness.',
    features: ['All 20 policies, 16 procedures & 147 control reference templates', 'Editable source files (Word & Excel)', 'MyCSF-ready control mapping', 'Maturity & 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 scope.',
    features: ['Everything in Starter', 'Documents tailored to your scope & assessment type', 'Scoping & factor 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 validated.',
    forWho: 'Teams targeting an r2 validated assessment & certification.',
    features: ['Everything in Professional', 'Hands-on implementation support', 'Gap assessment & remediation', 'MyCSF object setup & evidence packaging', 'External Assessor coordination', 'Unlimited tailoring & review cycles', 'Dedicated delivery team'] },
];

const H_ADDONS = [
  { id: 'impl', name: 'Hands-on implementation support', desc: 'A practitioner embeds with your team to operationalize every control.', price: 6500 },
  { id: 'gap', name: 'Gap assessment & remediation', desc: 'A scored gap assessment against your assessment type with a remediation plan.', price: 2900 },
  { id: 'assessor', name: 'External Assessor coordination', desc: 'We coordinate the HITRUST authorized External Assessor and MyCSF submission.', price: 4500 },
  { id: 'scoping', name: 'Scoping & factor workshop', desc: 'Set the organizational, system, and regulatory factors that define your scope.', price: 2200 },
  { id: 'mapping', name: 'Cross-framework mapping', desc: 'Map controls to HIPAA, ISO 27001 & NIST so evidence is reused, not rebuilt.', price: 2400 },
  { id: 'tailor', name: 'Document tailoring to your scope', desc: 'Every policy, procedure and control adapted to your scope and factors.', price: 1950 },
];

/* ── 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: 'HITRUST 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: 'HITRUST CSF',
    metadata: lead,
  });
}

/* ── CUSTOM PACKAGE: BASE + OPTION MODULES ───────────────── */
const QUOTE_BASE = { id: 'base', name: 'HITRUST CSF Document Toolkit', price: 1495,
  desc: 'All 20 policies, 16 procedures and 147 CSF control reference templates as editable source files (Word & Excel), plus MyCSF-ready control mapping, maturity scoring and evidence 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 control adapted to your scope, factors 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: 'impl', name: 'Hands-on implementation support', price: 6500, desc: 'A practitioner embeds with your team to operationalize every control.' },
  { id: 'gap', name: 'Gap assessment & remediation', price: 2900, desc: 'A scored gap assessment against your assessment type with a remediation plan.' },
  { id: 'assessor', name: 'External Assessor coordination', price: 4500, desc: 'We coordinate the HITRUST authorized External Assessor and MyCSF submission.' },
  { id: 'scoping', name: 'Scoping & factor workshop', price: 2200, desc: 'Set the organizational, system, and regulatory factors that define your scope.' },
  { id: 'mapping', name: 'Cross-framework mapping', price: 2400, desc: 'Map controls to HIPAA, ISO 27001 & NIST so evidence is reused, not rebuilt.' },
];

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.',
  'r2 validated assessments are submitted through MyCSF and validated by a HITRUST authorized External Assessor; Verigo prepares and coordinates but does not issue the certification.',
  'e1 and i1 certifications are valid for one year; r2 certification is valid for two years with an interim review.',
  '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('HITRUST CSF', 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.assessment) rows.push(['Assessment type', u.assessment]);
  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-HITRUST-Custom-Quote-' + ref + '.pdf');
  return ref;
}

/* ── PDF ENGINE (jsPDF) ──────────────────────────────────── */
function sectionsFor(assetKey) {
  const polSec = { heading: 'Security policy set (20)', items: H_POLICIES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const prcSec = { heading: 'HITRUST procedure set (16)', items: H_PROCEDURES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const ctrlSecs = HITRUST_CATS.map(g => ({ heading: g.code + ' · ' + g.name + ' (' + 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 = H_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('HITRUST CSF', 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_HITRUST = { POLICIES: H_POLICIES, PROCEDURES: H_PROCEDURES, CATS: HITRUST_CATS, ASSESSMENTS: HITRUST_ASSESSMENTS, ASSETS: H_ASSETS, TIERS: H_TIERS, ADDONS: H_ADDONS, QUOTE_BASE, QUOTE_MODULES, QUOTE_TERMS, fmtPrice, getUser, storeLead, generatePDF, generateQuotePDF };
