// toolkit-iso27001-data.jsx — ISO 27001:2022 toolkit contents + PDF engine + lead capture
// Exposes window.TK_ISO (data, generatePDF, lead helpers)

/* ── POLICY LIBRARY (24) ─────────────────────────────────── */
const POLICIES = [
  ['Information Security Policy', 'Top-level ISMS mandate, objectives, and management commitment.'],
  ['Access Control Policy', 'Rules for granting, reviewing, and revoking system access.'],
  ['Acceptable Use Policy', 'Expected behaviour for users of information and assets.'],
  ['Asset Management Policy', 'Identification, ownership, and handling of information assets.'],
  ['Risk Management Policy', 'How information security risk is assessed and treated.'],
  ['Cryptography Policy', 'Use of encryption and cryptographic key management.'],
  ['Physical & Environmental Security Policy', 'Protection of facilities, equipment, and secure areas.'],
  ['Operations Security Policy', 'Secure day-to-day operation of systems and services.'],
  ['Network Security Policy', 'Segmentation, controls, and monitoring of networks.'],
  ['Supplier & Third-Party Security Policy', 'Security requirements for vendors and the supply chain.'],
  ['Information Classification & Handling Policy', 'Labelling and handling rules by sensitivity level.'],
  ['Human Resources Security Policy', 'Security across the employment lifecycle.'],
  ['Mobile Device & Remote Working Policy', 'Securing endpoints and work outside the office.'],
  ['Backup Policy', 'Backup scope, frequency, and restoration testing.'],
  ['Logging & Monitoring Policy', 'Event logging, retention, and review obligations.'],
  ['Vulnerability & Patch Management Policy', 'Identifying and remediating technical weaknesses.'],
  ['Secure Development Policy', 'Security requirements across the development lifecycle.'],
  ['Incident Management Policy', 'Detecting, reporting, and responding to incidents.'],
  ['Business Continuity Policy', 'Maintaining operations and ICT readiness during disruption.'],
  ['Data Protection & Privacy Policy', 'Lawful handling and protection of personal data.'],
  ['Change Management Policy', 'Controlled changes to systems and services.'],
  ['Anti-Malware Policy', 'Protection against malicious software.'],
  ['Clear Desk & Clear Screen Policy', 'Protecting information in the workplace.'],
  ['Compliance Policy', 'Meeting legal, regulatory, and contractual obligations.'],
];

/* ── PROCEDURE SET (20) ──────────────────────────────────── */
const PROCEDURES = [
  ['Risk Assessment & Treatment Procedure', 'Step-by-step risk identification, analysis, and treatment.'],
  ['Statement of Applicability Procedure', 'Building and maintaining the SoA against Annex A.'],
  ['Internal Audit Procedure', 'Planning and conducting ISMS internal audits.'],
  ['Management Review Procedure', 'Running periodic management reviews of the ISMS.'],
  ['Corrective Action & Nonconformity Procedure', 'Logging, tracking, and closing nonconformities.'],
  ['Document & Record Control Procedure', 'Versioning, approval, and retention of documents.'],
  ['Access Provisioning & Deprovisioning Procedure', 'Granting and removing user access on the joiner-mover-leaver path.'],
  ['User Access Review Procedure', 'Periodic recertification of access rights.'],
  ['Incident Response Procedure', 'Triage, containment, eradication, and recovery steps.'],
  ['Backup & Restore Procedure', 'Performing and verifying backups and restores.'],
  ['Change Management Procedure', 'Requesting, approving, and deploying changes.'],
  ['Vulnerability Management Procedure', 'Scanning, prioritising, and remediating findings.'],
  ['Patch Management Procedure', 'Testing and applying security patches.'],
  ['Secure Development & Code Review Procedure', 'Embedding security across the SDLC.'],
  ['Supplier Assessment & Onboarding Procedure', 'Evaluating and onboarding vendors securely.'],
  ['Business Continuity & DR Testing Procedure', 'Exercising continuity and recovery plans.'],
  ['Asset Inventory & Lifecycle Procedure', 'Maintaining the asset register end to end.'],
  ['Security Awareness & Training Procedure', 'Delivering and tracking awareness training.'],
  ['Cryptographic Key Management Procedure', 'Generating, storing, rotating, and retiring keys.'],
  ['Data Retention & Secure Disposal Procedure', 'Retaining and destroying information securely.'],
];

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

/* ── ASSET METADATA ──────────────────────────────────────── */
const ASSETS = {
  policies: { icon: 'doc', label: 'Policy Library', count: 24, unit: 'policies',
    file: 'Verigo-ISO27001-Policy-Library.pdf', pdfTitle: 'ISO 27001:2022 Policy Library',
    blurb: 'The complete, framework-aligned ISMS policy set — 24 approval-ready policies covering Clauses 4–10 and every Annex A theme.',
    intro: 'This index lists the 24 policies included in the Verigo Global ISO 27001:2022 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 your ISMS.' },
  procedures: { icon: 'file', label: 'Procedure Set', count: 20, unit: 'procedures',
    file: 'Verigo-ISO27001-Procedure-Set.pdf', pdfTitle: 'ISO 27001:2022 Procedure Set',
    blurb: '20 operational procedures that turn policy into repeatable practice — so evidence is generated by the process, not assembled before the audit.',
    intro: 'This index lists the 20 procedures included in the Verigo Global ISO 27001:2022 Procedure Set. Each procedure documents the step-by-step workflow, roles, inputs, outputs, and records — the operating machinery that keeps your ISMS running and continuously audit-ready.' },
  controls: { icon: 'layers', label: 'Annex A Control Templates', count: 93, unit: 'controls',
    file: 'Verigo-ISO27001-Annex-A-Controls.pdf', pdfTitle: 'ISO 27001:2022 Annex A Control Templates',
    blurb: 'All 93 Annex A:2022 controls across the four themes, each as an implementation template with objective, guidance, evidence, and owner fields.',
    intro: 'This index lists all 93 Annex A controls from ISO/IEC 27001:2022, organized under the four themes — Organizational (37), People (8), Physical (14), and Technological (34). Each control ships as an implementation template capturing the control objective, applicability, implementation guidance, evidence expectations, owner, and status.' },
  standard: { icon: 'layers', label: 'Standard Toolkit Package', count: 137, unit: 'documents',
    file: 'Verigo-ISO27001-Standard-Package.pdf', pdfTitle: 'ISO 27001:2022 Standard Toolkit Package',
    blurb: 'The complete Standard package index — every policy, procedure, and Annex A control template in one branded document.',
    intro: 'This index summarizes the complete Verigo Global ISO 27001:2022 Standard Toolkit Package — 24 policies, 20 procedures, and all 93 Annex A:2022 control templates. Each artefact ships as an editable, organization-tailored document, ready to adopt as the documentation backbone of a certifiable ISMS.' },
};

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

const TIERS = [
  { id: 'starter', name: 'Starter', price: 1495, tagline: 'The complete document toolkit, ready to deploy.',
    forWho: 'Teams driving their own ISO 27001 implementation.',
    features: ['All 24 policies, 20 procedures & 93 Annex A control templates', 'Editable source files (Word & Excel)', 'Statement of Applicability & risk assessment templates', 'Audit-readiness 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 & industry', 'Half-day kickoff & gap-review 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, all the way to certified.',
    forWho: 'Multi-entity or multi-region programs targeting certification.',
    features: ['Everything in Professional', 'Hands-on implementation support', 'Stage 1 & Stage 2 pre-audit preparation', 'Internal audit as a service', 'Multi-entity / multi-region rollout', 'Unlimited tailoring & review cycles', 'Dedicated delivery team'] },
];

const ADDONS = [
  { id: 'impl', name: 'Hands-on implementation support', desc: 'A practitioner embeds with your team to operationalize every control.', price: 6500 },
  { id: 'preaudit', name: 'Pre-audit preparation', desc: 'Stage 1 & Stage 2 readiness review with a mock audit and findings log.', price: 3800 },
  { id: 'intaudit', name: 'Internal audit as a service', desc: 'We run your ISO 27001 internal audit and document the evidence.', price: 2900 },
  { id: 'risk', name: 'Risk assessment workshop', desc: 'Facilitated risk identification, analysis, and treatment planning.', price: 1600 },
  { id: 'mapping', name: 'Cross-framework mapping', desc: 'Map controls to SOC 2, CMMC & NIST so evidence is reused, not rebuilt.', price: 2400 },
  { id: 'entity', name: 'Additional entity / region', desc: 'Extend the program scope to another legal entity or operating region.', 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: 'ISO 27001', ts: new Date().toISOString() };
    const all = JSON.parse(localStorage.getItem(LEAD_KEY) || '[]');
    all.push(rec);
    localStorage.setItem(LEAD_KEY, JSON.stringify(all));
    // Merge captured fields into the persistent user record so contact + scope carry across steps.
    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: 'ISO 27001',
    metadata: lead,
  });
}

/* ── CUSTOM PACKAGE: BASE + OPTION MODULES ───────────────── */
const QUOTE_BASE = { id: 'base', name: 'ISO 27001 Document Toolkit', price: 1495,
  desc: 'All 24 policies, 20 procedures and 93 Annex A control templates as editable source files (Word & Excel), plus the Statement of Applicability, risk-assessment templates, and audit-readiness 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, industry 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: 'preaudit', name: 'Pre-audit preparation', price: 3800, desc: 'Stage 1 & Stage 2 readiness review with a mock audit and findings log.' },
  { id: 'intaudit', name: 'Internal audit as a service', price: 2900, desc: 'We run your ISO 27001 internal audit and document the evidence.' },
  { id: 'risk', name: 'Risk assessment workshop', price: 1600, desc: 'Facilitated risk identification, analysis and treatment planning.' },
  { id: 'mapping', name: 'Cross-framework mapping', price: 2400, desc: 'Map controls to SOC 2, CMMC & NIST so evidence is reused, not rebuilt.' },
  { id: 'entity', name: 'Additional entity / region', price: 1800, desc: 'Extend the program scope to another legal entity or operating region.' },
];

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.',
  'Pricing assumes a single legal entity and operating region unless an “Additional entity / region” 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('ISO/IEC 27001:2022', W - M - 20, 35, { align: 'right' });
    y = 100;
  };
  const newPage = () => { doc.addPage(); header(); };
  header();

  // Title + meta
  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;

  // Prepared-for + scope panel
  doc.setDrawColor(224, 224, 232); doc.setLineWidth(0.5);
  const panelTop = y;
  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.locations) rows.push(['Sites / locations', u.locations]);
  if (u.systems) rows.push(['In scope', u.systems]);
  if (u.certs) rows.push(['Existing certifications', u.certs]);
  if (u.target) rows.push(['Target certification', 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;

  // Line items
  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;

  // Terms
  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;
  });

  // Footers
  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-ISO27001-Custom-Quote-' + ref + '.pdf');
  return ref;
}

/* ── PDF ENGINE (jsPDF) ──────────────────────────────────── */
function sectionsFor(assetKey) {
  const polSec = { heading: 'Information security policy set (24)', items: POLICIES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const prcSec = { heading: 'ISMS procedure set (20)', items: PROCEDURES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const ctrlSecs = ANNEX.map(g => ({ heading: g.theme + ' controls (' + 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 = 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 + 52, 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('ISO/IEC 27001:2022', W - M - 20, 35, { align: 'right' });
    y = 100;
  };
  const newPage = () => { doc.addPage(); header(); };

  header();
  // Title block
  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;
    });
  });

  // Footers
  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_ISO = { POLICIES, PROCEDURES, ANNEX, ASSETS, TIERS, ADDONS, QUOTE_BASE, QUOTE_MODULES, QUOTE_TERMS, fmtPrice, getUser, storeLead, generatePDF, generateQuotePDF };
