// toolkit-iso42001-data.jsx — ISO 42001:2023 (AIMS) toolkit contents + PDF engine + lead capture
// Exposes window.TK_ISO42001 (data, generatePDF, lead helpers)

/* ── POLICY LIBRARY (18) ─────────────────────────────────── */
const POLICIES = [
  ['AI Management Policy', 'Top-level AIMS mandate, objectives, and management commitment to responsible AI.'],
  ['AI Risk Management Policy', 'How AI-specific risk is identified, assessed, and treated across the lifecycle.'],
  ['AI System Impact Assessment Policy', 'Assessing impacts of AI systems on individuals, groups, and society before deployment.'],
  ['Data Governance Policy for AI', 'Sourcing, quality, provenance, and lifecycle handling of data used to train and operate AI systems.'],
  ['Responsible AI Use Policy', 'Acceptable use, prohibited use cases, and human-oversight expectations for AI systems.'],
  ['AI Fairness & Bias Policy', 'Identifying, measuring, and mitigating bias across training data, models, and outcomes.'],
  ['Transparency & Explainability Policy', 'Disclosure obligations and explainability requirements for AI-driven decisions.'],
  ['Human Oversight Policy', 'Defining where and how humans review, override, or intervene in AI system decisions.'],
  ['AI Supplier & Third-Party Policy', 'Requirements for third-party models, datasets, and AI service providers.'],
  ['AI System Lifecycle Policy', 'Governance across design, development, verification, deployment, and retirement of AI systems.'],
  ['Model Monitoring & Drift Policy', 'Ongoing performance monitoring and thresholds for retraining or decommissioning.'],
  ['Incident Management Policy (AI)', 'Detecting, reporting, and responding to AI-specific incidents and near-misses.'],
  ['AI Roles & Responsibilities Policy', 'Accountability structure across the AI lifecycle, from sponsor to model owner.'],
  ['Data Protection & Privacy Policy', 'Lawful handling of personal data used in AI training, inference, and evaluation.'],
  ['Competence & Awareness Policy (AI)', 'Skills, training, and awareness requirements for staff who build or operate AI systems.'],
  ['Change Management Policy (AI Systems)', 'Controlled changes to models, prompts, pipelines, and production AI configurations.'],
  ['Third-Party & Customer Communication Policy', 'What is disclosed to customers and partners about AI system use and limitations.'],
  ['Compliance Policy (AI Regulation)', 'Meeting applicable legal, regulatory, and contractual AI obligations, including emerging AI law.'],
];

/* ── PROCEDURE SET (16) ──────────────────────────────────── */
const PROCEDURES = [
  ['AI Risk Assessment & Treatment Procedure', 'Step-by-step identification, analysis, and treatment of AI system risk.'],
  ['Statement of Applicability Procedure (Annex A)', 'Building and maintaining the SoA against the 38 Annex A controls.'],
  ['AI System Impact Assessment Procedure', 'Running a structured impact assessment before an AI system is deployed.'],
  ['Data Quality & Provenance Procedure', 'Verifying source, lineage, and quality of data used in training and inference.'],
  ['Bias Testing & Fairness Review Procedure', 'Testing models for disparate impact and documenting mitigation steps.'],
  ['Model Validation & Verification Procedure', 'Pre-deployment testing of accuracy, robustness, and safety.'],
  ['Human Oversight & Override Procedure', 'Defining escalation paths and override authority for AI-driven decisions.'],
  ['AI Incident Response Procedure', 'Triage, containment, and root-cause analysis for AI-specific incidents.'],
  ['Internal Audit Procedure (AIMS)', 'Planning and conducting AI management system internal audits.'],
  ['Management Review Procedure (AIMS)', 'Running periodic management reviews of the AI management system.'],
  ['Corrective Action & Nonconformity Procedure', 'Logging, tracking, and closing AIMS nonconformities.'],
  ['AI Supplier Assessment & Onboarding Procedure', 'Evaluating and onboarding third-party models, data, and AI vendors.'],
  ['Model Monitoring & Retraining Procedure', 'Ongoing performance tracking, drift detection, and retraining triggers.'],
  ['Document & Record Control Procedure', 'Versioning, approval, and retention of AIMS documentation.'],
  ['AI System Inventory & Classification Procedure', 'Maintaining a register of AI systems and their risk classification.'],
  ['Awareness & Training Procedure (AI)', 'Delivering and tracking role-based AI governance training.'],
];

/* ── ANNEX A:2023 CONTROLS (38) ──────────────────────────── */
const ANNEX = [
  { theme: 'A.2 Policies for AI', icon: 'briefcase', items: [
    ['A.2.2', 'AI policy'], ['A.2.3', 'Alignment with other organizational policies'], ['A.2.4', 'Review of the AI policy'],
  ] },
  { theme: 'A.3 Internal Organization', icon: 'users', items: [
    ['A.3.2', 'AI roles and responsibilities'], ['A.3.3', 'Reporting of concerns'],
  ] },
  { theme: 'A.4 Resources for AI Systems', icon: 'cpu', items: [
    ['A.4.2', 'Resource documentation'], ['A.4.3', 'Data resources'], ['A.4.4', 'Tooling resources'], ['A.4.5', 'System and computing resources'], ['A.4.6', 'Human resources'],
  ] },
  { theme: 'A.5 Impact Assessment', icon: 'target', items: [
    ['A.5.2', 'AI system impact assessment process'], ['A.5.3', 'Documentation of AI system impact assessments'], ['A.5.4', 'Assessing societal impacts of AI systems'],
  ] },
  { theme: 'A.6 AI System Life Cycle', icon: 'layers', items: [
    ['A.6.1.2', 'AI system life cycle management'], ['A.6.1.3', 'Objectives for responsible development'], ['A.6.1.4', 'Documentation of AI system design and development'], ['A.6.2.2', 'AI system requirements analysis'], ['A.6.2.3', 'Documentation of AI system design and development'], ['A.6.2.4', 'AI system verification and validation'], ['A.6.2.5', 'Deployment of AI systems'], ['A.6.2.6', 'AI system operation and monitoring'], ['A.6.2.7', 'AI system technical documentation'], ['A.6.2.8', 'AI system event logging'],
  ] },
  { theme: 'A.7 Data for AI Systems', icon: 'doc', items: [
    ['A.7.2', 'Data for development and enhancement of AI systems'], ['A.7.3', 'Acquisition of data'], ['A.7.4', 'Quality of data for AI systems'], ['A.7.5', 'Data provenance'], ['A.7.6', 'Data preparation'],
  ] },
  { theme: 'A.8 Information for Interested Parties', icon: 'file', items: [
    ['A.8.2', 'Transparency and provision of information to interested parties'], ['A.8.3', 'Communicating incidents and malfunctions'], ['A.8.4', 'Information for interested parties'], ['A.8.5', 'Communication of policies and objectives'],
  ] },
  { theme: 'A.9 Use of AI Systems', icon: 'compass', items: [
    ['A.9.2', 'Processes for responsible use of AI systems'], ['A.9.3', 'Objectives for responsible use of AI systems'], ['A.9.4', 'Intended use of the AI system'],
  ] },
  { theme: 'A.10 Third-Party & Customer Relationships', icon: 'network', items: [
    ['A.10.2', 'Allocating responsibilities between AI providers and customers'], ['A.10.3', 'Suppliers'], ['A.10.4', 'Customers'],
  ] },
];

/* ── ASSET METADATA ──────────────────────────────────────── */
const ASSETS = {
  policies: { icon: 'doc', label: 'Policy Library', count: 18, unit: 'policies',
    file: 'Verigo-ISO42001-Policy-Library.pdf', pdfTitle: 'ISO/IEC 42001:2023 Policy Library',
    blurb: 'The complete, framework-aligned AIMS policy set — 18 approval-ready policies covering Clauses 4–10 and every Annex A objective.',
    intro: 'This index lists the 18 policies included in the Verigo Global ISO/IEC 42001:2023 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 AI Management System.' },
  procedures: { icon: 'file', label: 'Procedure Set', count: 16, unit: 'procedures',
    file: 'Verigo-ISO42001-Procedure-Set.pdf', pdfTitle: 'ISO/IEC 42001:2023 Procedure Set',
    blurb: '16 operational procedures that turn AI governance policy into repeatable practice — so evidence is generated by the process, not assembled before the audit.',
    intro: 'This index lists the 16 procedures included in the Verigo Global ISO/IEC 42001:2023 Procedure Set. Each procedure documents the step-by-step workflow, roles, inputs, outputs, and records — the operating machinery that keeps your AIMS running and continuously audit-ready.' },
  controls: { icon: 'layers', label: 'Annex A Control Templates', count: 38, unit: 'controls',
    file: 'Verigo-ISO42001-Annex-A-Controls.pdf', pdfTitle: 'ISO/IEC 42001:2023 Annex A Control Templates',
    blurb: 'All 38 Annex A:2023 controls across the nine objectives, each as an implementation template with objective, guidance, evidence, and owner fields.',
    intro: 'This index lists all 38 Annex A controls from ISO/IEC 42001:2023, organized under nine objectives — from AI policy through third-party and customer relationships. 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: 72, unit: 'documents',
    file: 'Verigo-ISO42001-Standard-Package.pdf', pdfTitle: 'ISO/IEC 42001:2023 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/IEC 42001:2023 Standard Toolkit Package — 18 policies, 16 procedures, and all 38 Annex A:2023 control templates. Each artefact ships as an editable, organization-tailored document, ready to adopt as the documentation backbone of a certifiable AI Management System.' },
};

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

const TIERS = [
  { id: 'starter', name: 'Starter', price: 1595, tagline: 'The complete document toolkit, ready to deploy.',
    forWho: 'Teams driving their own ISO 42001 implementation.',
    features: ['All 18 policies, 16 procedures & 38 Annex A control templates', 'Editable source files (Word & Excel)', 'Statement of Applicability & AI risk assessment templates', 'Audit-readiness checklists', '12 months of content updates', 'Email support'] },
  { id: 'professional', name: 'Professional', price: 5250, tagline: 'The toolkit tailored to you, with practitioner guidance.', popular: true,
    forWho: 'Organizations that want the toolkit shaped to their AI use cases.',
    features: ['Everything in Starter', 'Documents tailored to your AI systems & industry', 'Half-day kickoff & gap-review workshop', 'Online readiness self-assessment', 'Cross-framework control mapping to ISO 27001', 'Named practitioner with scheduled check-ins', 'Priority support'] },
  { id: 'enterprise', name: 'Enterprise', price: 12900, priceNote: 'from', tagline: 'End-to-end implementation, all the way to certified.',
    forWho: 'Multi-model or multi-entity AI 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-model 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: 6900 },
  { id: 'preaudit', name: 'Pre-audit preparation', desc: 'Stage 1 & Stage 2 readiness review with a mock audit and findings log.', price: 3950 },
  { id: 'intaudit', name: 'Internal audit as a service', desc: 'We run your ISO 42001 internal audit and document the evidence.', price: 3100 },
  { id: 'impact', name: 'AI impact assessment workshop', desc: 'Facilitated impact assessment across your highest-risk AI systems.', price: 2200 },
  { id: 'mapping', name: 'Cross-framework mapping', desc: 'Map controls to ISO 27001, SOC 2 & NIST so evidence is reused, not rebuilt.', price: 2500 },
  { id: 'entity', name: 'Additional AI system / entity', desc: 'Extend the program scope to another AI system, model, or legal entity.', price: 1900 },
];

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

/* ── CUSTOM PACKAGE: BASE + OPTION MODULES ───────────────── */
const QUOTE_BASE = { id: 'base', name: 'ISO 42001 Document Toolkit', price: 1595,
  desc: 'All 18 policies, 16 procedures and 38 Annex A control templates as editable source files (Word & Excel), plus the Statement of Applicability, AI risk-assessment templates, and audit-readiness checklists. 12 months of content updates included.' };
const QUOTE_MODULES = [
  { id: 'tailor', name: 'Document tailoring to your AI systems', price: 2050, desc: 'Every policy, procedure and control adapted to your AI use cases, industry and existing tooling.' },
  { id: 'guidance', name: 'Practitioner guidance & check-ins', price: 1550, desc: 'A named practitioner, a kickoff workshop, and scheduled check-ins through your project.' },
  { id: 'impl', name: 'Hands-on implementation support', price: 6900, desc: 'A practitioner embeds with your team to operationalize every control.' },
  { id: 'preaudit', name: 'Pre-audit preparation', price: 3950, desc: 'Stage 1 & Stage 2 readiness review with a mock audit and findings log.' },
  { id: 'intaudit', name: 'Internal audit as a service', price: 3100, desc: 'We run your ISO 42001 internal audit and document the evidence.' },
  { id: 'impact', name: 'AI impact assessment workshop', price: 2200, desc: 'Facilitated impact assessment across your highest-risk AI systems.' },
  { id: 'mapping', name: 'Cross-framework mapping', price: 2500, desc: 'Map controls to ISO 27001, SOC 2 & NIST so evidence is reused, not rebuilt.' },
  { id: 'entity', name: 'Additional AI system / entity', price: 1900, desc: 'Extend the program scope to another AI system, model, or legal entity.' },
];

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 a defined set of in-scope AI systems unless an “Additional AI system / entity” 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 42001:2023', 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.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;

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

/* ── PDF ENGINE (jsPDF) ──────────────────────────────────── */
function sectionsFor(assetKey) {
  const polSec = { heading: 'AI management policy set (18)', items: POLICIES.map(([t, d], i) => ({ code: String(i + 1).padStart(2, '0'), title: t, desc: d })) };
  const prcSec = { heading: 'AIMS procedure set (16)', 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 + 62, 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 42001:2023', 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(8.5); 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_ISO42001 = { POLICIES, PROCEDURES, ANNEX, ASSETS, TIERS, ADDONS, QUOTE_BASE, QUOTE_MODULES, QUOTE_TERMS, fmtPrice, getUser, storeLead, generatePDF, generateQuotePDF };
