// toolkit-cmmi-data.jsx — CMMI v2.0 toolkit contents + PDF engine + lead capture
// Exposes window.TK_CMMI

/* ── POLICY LIBRARY (14) ─────────────────────────────────── */
const CM_POLICIES = [
  ['Process Management Policy', "Governing the organization's commitment to defined, repeatable processes."],
  ['Estimating & Planning Policy', 'Requirements for project estimating, work breakdown, and baseline planning.'],
  ['Requirements Management Policy', 'Managing and tracing requirements throughout the project lifecycle.'],
  ['Configuration Management Policy', 'Controlling work product integrity, versioning, and change control.'],
  ['Measurement & Analysis Policy', 'Collecting, storing, and using measurement data for decision-making.'],
  ['Process Quality Assurance Policy', 'Ensuring processes and work products conform to plans and standards.'],
  ['Supplier Agreement Management Policy', 'Establishing and monitoring agreements with suppliers.'],
  ['Verification & Validation Policy', 'Ensuring products meet requirements and intended use.'],
  ['Technical Solution Policy', 'Designing and implementing solutions that satisfy requirements.'],
  ['Project Monitoring & Control Policy', 'Tracking project status against the plan and taking corrective action.'],
  ['Peer Review Policy', 'Conducting structured reviews of work products to find defects early.'],
  ['Decision Analysis & Resolution Policy', 'Using formal evaluation criteria for significant decisions.'],
  ['Risk & Opportunity Management Policy', 'Identifying, analyzing, and mitigating risks and realizing opportunities.'],
  ['Causal Analysis & Resolution Policy', 'Identifying and resolving causes of defects and problems.'],
];

/* ── PROCEDURE SET (12) ──────────────────────────────────── */
const CM_PROCEDURES = [
  ['Project Estimating Procedure', 'Estimating project size, effort, and cost from requirements.'],
  ['Project Planning Procedure', 'Building the project plan from estimates, milestones, and resources.'],
  ['Monitor & Control Procedure', 'Tracking actuals vs. plan and initiating corrective action.'],
  ['Requirements Development & Management Procedure', 'Eliciting, analyzing, and managing requirements.'],
  ['Configuration Management Procedure', 'Baselining, versioning, and auditing configuration items.'],
  ['Quality Assurance Review Procedure', 'Planning, conducting, and recording QA reviews.'],
  ['Measurement Data Collection Procedure', 'Collecting and analyzing project and process metrics.'],
  ['Supplier Evaluation & Agreement Procedure', 'Evaluating, selecting, and monitoring suppliers.'],
  ['Peer Review Procedure', 'Preparing, conducting, and recording peer review findings.'],
  ['Risk & Opportunity Management Procedure', 'Identifying, analyzing, and responding to risks and opportunities.'],
  ['Causal Analysis & Resolution Procedure', 'Analyzing root causes and implementing corrective actions.'],
  ['Process Improvement Proposal Procedure', 'Proposing, evaluating, and implementing process improvements.'],
];

/* ── 4 CMMI CATEGORIES · 20 PRACTICE AREAS ───────────────── */
const CMMI_CATS = [
  { cat: 'Doing', icon: 'activity', pas: [
    { code: 'EST', name: 'Estimating', ml2: true, items: [
      ['EST 1.1', 'Establish estimates of work product size and attributes'], ['EST 1.2', 'Establish estimates of effort, cost, and schedule'], ['EST 2.1', 'Reconcile work with available resources'], ['EST 2.2', 'Maintain estimates throughout the project lifecycle'],
    ] },
    { code: 'PLAN', name: 'Planning', ml2: true, items: [
      ['PLAN 1.1', 'Establish the project plan'], ['PLAN 1.2', 'Obtain commitment to the plan'], ['PLAN 2.1', 'Maintain the plan'], ['PLAN 2.2', 'Reconcile work and resource levels'],
    ] },
    { code: 'MC', name: 'Monitor and Control', ml2: true, items: [
      ['MC 1.1', 'Monitor the project against the plan'], ['MC 1.2', 'Manage corrective actions to closure'], ['MC 2.1', 'Manage performance against the plan'], ['MC 2.2', 'Analyze and resolve issues'],
    ] },
    { code: 'SAM', name: 'Supplier Agreement Management', ml2: true, items: [
      ['SAM 1.1', 'Establish supplier agreements'], ['SAM 1.2', 'Monitor supplier agreements'], ['SAM 2.1', 'Evaluate supplier work products and services'],
    ] },
    { code: 'RDM', name: 'Requirements Development and Management', ml2: true, items: [
      ['RDM 1.1', 'Elicit and develop requirements'], ['RDM 1.2', 'Maintain bidirectional traceability of requirements'], ['RDM 2.1', 'Manage requirements throughout the project'], ['RDM 2.2', 'Ensure alignment among requirements and work products'],
    ] },
    { code: 'PQA', name: 'Process Quality Assurance', ml2: true, items: [
      ['PQA 1.1', 'Objectively evaluate adherence of performed processes'], ['PQA 1.2', 'Objectively evaluate work products'], ['PQA 2.1', 'Communicate and resolve noncompliance issues'],
    ] },
    { code: 'VV', name: 'Verification and Validation', ml2: false, items: [
      ['VV 1.1', 'Select work products for verification'], ['VV 1.2', 'Perform peer reviews'], ['VV 2.1', 'Perform verification'], ['VV 2.2', 'Perform validation'],
    ] },
    { code: 'TS', name: 'Technical Solution', ml2: false, items: [
      ['TS 1.1', 'Select technical solutions'], ['TS 1.2', 'Design the product or product component'], ['TS 2.1', 'Implement the design'], ['TS 2.2', 'Ensure the product is ready for integration'],
    ] },
    { code: 'PI', name: 'Product Integration', ml2: false, items: [
      ['PI 1.1', 'Prepare for product integration'], ['PI 1.2', 'Ensure interface compatibility'], ['PI 2.1', 'Assemble product components and deliver the product'],
    ] },
    { code: 'PR', name: 'Peer Reviews', ml2: false, items: [
      ['PR 1.1', 'Prepare for peer reviews'], ['PR 1.2', 'Conduct peer reviews'], ['PR 2.1', 'Analyze peer review data'],
    ] },
  ] },
  { cat: 'Managing', icon: 'briefcase', pas: [
    { code: 'CM', name: 'Configuration Management', ml2: true, items: [
      ['CM 1.1', 'Establish configuration baselines'], ['CM 1.2', 'Track and control changes to configuration items'], ['CM 2.1', 'Establish a configuration management system'], ['CM 2.2', 'Conduct configuration audits'],
    ] },
    { code: 'MA', name: 'Measurement and Analysis', ml2: true, items: [
      ['MA 1.1', 'Establish measurement objectives'], ['MA 1.2', 'Specify measures and data collection procedures'], ['MA 2.1', 'Collect measurement data'], ['MA 2.2', 'Analyze and report measurement results'],
    ] },
    { code: 'GOV', name: 'Governance', ml2: true, items: [
      ['GOV 1.1', 'Ensure senior management commitment to processes'], ['GOV 1.2', 'Establish policy to guide implementation'], ['GOV 2.1', 'Establish accountability for process implementation'],
    ] },
    { code: 'II', name: 'Implementation Infrastructure', ml2: true, items: [
      ['II 1.1', 'Identify process implementation resources'], ['II 1.2', 'Provide process support and guidance'], ['II 2.1', 'Establish repositories for process assets'],
    ] },
    { code: 'PCM', name: 'Process Management', ml2: false, items: [
      ['PCM 1.1', 'Establish organizational process needs'], ['PCM 1.2', 'Establish an organizational process framework'], ['PCM 2.1', 'Ensure process compliance'], ['PCM 2.2', "Monitor the performance of the organization's processes"],
    ] },
  ] },
  { cat: 'Enabling', icon: 'users', pas: [
    { code: 'OT', name: 'Organizational Training', ml2: false, items: [
      ['OT 1.1', 'Identify skills needed for performing assigned roles'], ['OT 1.2', 'Deliver training to build needed skills'], ['OT 2.1', 'Assess training effectiveness'],
    ] },
    { code: 'DAR', name: 'Decision Analysis and Resolution', ml2: false, items: [
      ['DAR 1.1', 'Establish criteria for evaluating alternatives'], ['DAR 1.2', 'Evaluate alternative solutions using criteria'], ['DAR 2.1', 'Select solutions and record rationale'],
    ] },
    { code: 'RSK', name: 'Risk and Opportunity Management', ml2: false, items: [
      ['RSK 1.1', 'Identify and categorize risks'], ['RSK 1.2', 'Develop risk mitigation plans'], ['RSK 2.1', 'Monitor risks and implement mitigation plans'], ['RSK 2.2', 'Identify and realize opportunities'],
    ] },
  ] },
  { cat: 'Improving', icon: 'refresh', pas: [
    { code: 'PAD', name: 'Process Asset Development', ml2: false, items: [
      ['PAD 1.1', 'Establish organizational process assets'], ['PAD 1.2', 'Maintain the organizational process asset library'], ['PAD 2.1', 'Gather process improvement proposals'],
    ] },
    { code: 'MPM', name: 'Managing Performance and Measurement', ml2: false, items: [
      ['MPM 1.1', 'Establish performance baselines and models'], ['MPM 2.1', 'Manage the performance of selected processes quantitatively'], ['MPM 2.2', 'Use performance data to achieve business objectives'],
    ] },
    { code: 'CAR', name: 'Causal Analysis and Resolution', ml2: false, items: [
      ['CAR 1.1', 'Identify and analyze causes of defects'], ['CAR 1.2', 'Implement corrective actions'], ['CAR 2.1', 'Evaluate the effect of changes on process performance'],
    ] },
  ] },
];

/* ── THREE MATURITY LEVELS ───────────────────────────────── */
const CMMI_LEVELS = [
  { id: 'ml2', name: 'Maturity Level 2 — Managed', pas: 10, desc: 'Projects use documented processes, are planned and monitored, and produce consistent results.', appraisal: 'CMMI Lead Appraiser', blurb: '10 practice areas — the foundational managed baseline.', popular: false },
  { id: 'ml3', name: 'Maturity Level 3 — Defined', pas: 20, desc: "Processes are tailored from the organization's standard set and well-understood across the enterprise.", appraisal: 'CMMI Lead Appraiser', blurb: '20 practice areas — fully defined across Doing, Managing, Enabling & Improving.', popular: true },
  { id: 'ml45', name: 'Maturity Level 4/5 — Quantitative', pas: 20, desc: 'Processes are measured, controlled, and continuously improved using statistical and quantitative data.', appraisal: 'CMMI Lead Appraiser', blurb: '20 practice areas with quantitative management and optimization.', popular: false },
];

// Count total practice items
const CM_CTRL_COUNT = CMMI_CATS.reduce((a, c) => a + c.pas.reduce((b, p) => b + p.items.length, 0), 0);

/* ── ASSET METADATA ──────────────────────────────────────── */
const CM_ASSETS = {
  policies: { icon: 'doc', label: 'Policy Library', count: 14, unit: 'policies',
    file: 'Verigo-CMMI-Policy-Library.pdf', pdfTitle: 'CMMI v2.0 Policy Library',
    blurb: 'The complete, CMMI v2.0-aligned policy set — 14 approval-ready policies covering all 20 practice areas across the four categories.',
    intro: 'This index lists the 14 policies in the Verigo Global CMMI v2.0 Policy Library. Each ships as an editable document covering purpose, scope, policy statements, roles and responsibilities, and review cadence.' },
  procedures: { icon: 'file', label: 'Procedure Set', count: 12, unit: 'procedures',
    file: 'Verigo-CMMI-Procedure-Set.pdf', pdfTitle: 'CMMI v2.0 Procedure Set',
    blurb: '12 operational procedures that turn CMMI practice requirements into repeatable, appraiser-ready processes.',
    intro: 'This index lists the 12 procedures in the Verigo Global CMMI v2.0 Procedure Set. Each documents the step-by-step workflow, roles, inputs, outputs, and records — producing the objective evidence an appraisal team needs.' },
  controls: { icon: 'layers', label: 'Practice Templates', count: CM_CTRL_COUNT, unit: 'practices',
    file: 'Verigo-CMMI-Practice-Templates.pdf', pdfTitle: 'CMMI v2.0 Practice Templates',
    blurb: `All ${CM_CTRL_COUNT} practice statements across the 20 CMMI v2.0 practice areas, each as an implementation template with objective, guidance, evidence, and owner fields.`,
    intro: `This index lists the ${CM_CTRL_COUNT} practice statements across the 20 CMMI v2.0 practice areas, organized under the four categories — Doing, Managing, Enabling, and Improving. Each ships as a template capturing the practice objective, implementation guidance, evidence expectations, owner, and appraisal status.` },
  standard: { icon: 'layers', label: 'Standard Toolkit Package', count: 14 + 12 + CM_CTRL_COUNT, unit: 'documents',
    file: 'Verigo-CMMI-Standard-Package.pdf', pdfTitle: 'CMMI v2.0 Standard Toolkit Package',
    blurb: 'The complete package — every policy, procedure, and practice template in one branded document.',
    intro: `This index summarizes the complete Verigo Global CMMI v2.0 Standard Toolkit Package — 14 policies, 12 procedures, and all ${CM_CTRL_COUNT} practice templates across the 20 practice areas.` },
};

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

const CM_TIERS = [
  { id: 'starter', name: 'Starter', price: 1495, tagline: 'The complete document toolkit, ready to deploy.',
    forWho: 'Teams driving their own CMMI readiness.',
    features: [`All 14 policies, 12 procedures & ${CM_CTRL_COUNT} practice templates`, 'Editable source files (Word & Excel)', 'Appraisal-readiness evidence checklists', 'ML2 & ML3 practice coverage', '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 & target ML', 'Process adoption workshop', 'Online readiness self-assessment', '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 appraised.',
    forWho: 'Organizations targeting an ML2 or ML3 appraisal.',
    features: ['Everything in Professional', 'Hands-on process implementation', 'Appraisal preparation & evidence packaging', 'CMMI Lead Appraiser coordination', 'Practice area coaching', 'Dedicated delivery team'] },
];

const CM_ADDONS = [
  { id: 'impl', name: 'Hands-on implementation support', desc: 'A practitioner embeds with your team to institutionalize every practice area.', price: 6500 },
  { id: 'appraisal', name: 'Appraisal preparation', desc: 'Evidence packaging and mock appraisal before the Lead Appraiser arrives.', price: 3800 },
  { id: 'workshop', name: 'Process adoption workshop', desc: 'Facilitated workshop to tailor the standard process set to your project types.', price: 2200 },
  { id: 'coaching', name: 'Practice area coaching', desc: 'Targeted coaching sessions per weak practice area, with evidence review.', price: 1800 },
  { id: 'mapping', name: 'Cross-framework mapping', desc: 'Map practices to ISO 9001, NIST, and SPICE/ISO 33000 so effort is reused.', price: 2400 },
];

/* ── LEAD CAPTURE ─────────────────────────────────────────── */
const LEAD_KEY = 'verigo_toolkit_leads';
const USER_KEY = 'verigo_toolkit_user';
function getUser() { try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); } catch (e) { return null; } }
function storeLead(lead) {
  try {
    const rec = { ...lead, toolkit: 'CMMI', 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: 'CMMI',
    metadata: lead,
  });
}

/* ── CUSTOM PACKAGE: BASE + OPTION MODULES ───────────────── */
const QUOTE_BASE = { id: 'base', name: 'CMMI v2.0 Document Toolkit', price: 1495,
  desc: `All 14 policies, 12 procedures and ${CM_CTRL_COUNT} CMMI v2.0 practice templates as editable source files (Word & Excel), plus appraisal-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 practice adapted to your scope, process types and target ML.' },
  { 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 institutionalize every practice area.' },
  { id: 'appraisal', name: 'Appraisal preparation', price: 3800, desc: 'Evidence packaging and mock appraisal before the Lead Appraiser arrives.' },
  { id: 'workshop', name: 'Process adoption workshop', price: 2200, desc: 'Facilitated workshop to tailor the standard process set to your project types.' },
  { id: 'coaching', name: 'Practice area coaching', price: 1800, desc: 'Targeted coaching per weak practice area, with evidence review.' },
  { id: 'mapping', name: 'Cross-framework mapping', price: 2400, desc: 'Map practices to ISO 9001, NIST and SPICE/ISO 33000 so effort is reused.' },
];

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.',
  'CMMI appraisals are conducted by a CMMI Institute-certified Lead Appraiser; Verigo prepares and coordinates but does not perform the appraisal.',
  'Pricing assumes a single organizational unit unless specified otherwise.',
  'Document tailoring and delivery typically begin within 5 business days of a signed engagement.',
  "All deliverables are provided under mutual confidentiality; documents are licensed for the named organization's internal use.",
];

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

function generatePDF(assetKey, user) {
  const lib = window.jspdf;
  if (!lib || !lib.jsPDF) { alert('PDF engine is still loading — please try again in a moment.'); return; }
  const meta = CM_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('CMMI v2.0', W-M-20, 35, {align:'right'}); y = 100;
  };
  const newPage = () => { doc.addPage(); header(); };
  header();
  doc.setTextColor(...INK); doc.setFont('helvetica','bold'); doc.setFontSize(21); doc.text(meta.pdfTitle, M, y); y+=12;
  doc.setDrawColor(...ORANGE); doc.setLineWidth(2.5); doc.line(M,y,M+54,y); y+=22;
  doc.setFont('helvetica','normal'); doc.setFontSize(10); doc.setTextColor(...GREY);
  doc.splitTextToSize(meta.intro, W-2*M).forEach(ln => { doc.text(ln,M,y); y+=14; }); y+=6;
  if (user && (user.company||user.name)) {
    doc.setDrawColor(224,224,232); doc.setLineWidth(0.5); doc.line(M,y,W-M,y); y+=16;
    doc.setFontSize(9); doc.setTextColor(...PURPLE); doc.setFont('helvetica','bold'); doc.text('Prepared for '+(user.company||user.name),M,y);
    doc.setFont('helvetica','normal'); doc.setTextColor(...GREY); doc.text(new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'}),W-M,y,{align:'right'}); y+=20;
  }
  sectionsFor(assetKey).forEach(sec => {
    if (y>H-120) newPage(); y+=8;
    doc.setFont('helvetica','bold'); doc.setFontSize(12.5); doc.setTextColor(...PURPLE); doc.text(sec.heading,M,y); y+=6;
    doc.setDrawColor(...PURPLE); doc.setLineWidth(0.8); doc.line(M,y,W-M,y); y+=16;
    sec.items.forEach(it => {
      const tl = doc.splitTextToSize(it.title, RW); const h = tl.length*12+9;
      if (y+h>H-56) newPage();
      doc.setFont('helvetica','bold'); doc.setFontSize(9); doc.setTextColor(...ORANGE); doc.text(it.code,M,y+1);
      doc.setFontSize(10.5); doc.setTextColor(...INK); tl.forEach((ln,i) => doc.text(ln,CX,y+i*12)); y+=tl.length*12+9;
    });
  });
  const total = doc.internal.getNumberOfPages();
  for (let i=1;i<=total;i++) { doc.setPage(i); doc.setDrawColor(224,224,232); doc.setLineWidth(0.5); doc.line(M,H-38,W-M,H-38); doc.setFont('helvetica','normal'); doc.setFontSize(8); doc.setTextColor(150,150,160); doc.text('© 2026 Verigo Global · Confidential',M,H-24); doc.text(i+' / '+total,W-M,H-24,{align:'right'}); }
  doc.save(meta.file);
}

function generateQuotePDF(order, user) {
  const lib = window.jspdf; if (!lib||!lib.jsPDF) { alert('PDF engine is still loading.'); return null; }
  const u = user||{}; const ref = order.ref||('VG-'+Date.now().toString(36).toUpperCase().slice(-6));
  const lineItems = [{name:QUOTE_BASE.name,price:QUOTE_BASE.price,desc:QUOTE_BASE.desc}].concat(order.modules.map(m=>({name:m.name,price:m.price,desc:m.desc})));
  const total = lineItems.reduce((s,i)=>s+i.price,0);
  const doc = new lib.jsPDF({unit:'pt',format:'a4'}); const W=doc.internal.pageSize.getWidth(); const H=doc.internal.pageSize.getHeight(); const M=50;
  const PURPLE=[91,46,145],ORANGE=[232,98,42],INK=[30,30,46],GREY=[120,120,134];
  const fmt = n => '$'+Number(n).toLocaleString('en-US'); let y=0;
  const header = () => { doc.setFillColor(...PURPLE);doc.rect(0,0,W,70,'F');doc.setFillColor(...ORANGE);doc.rect(W-M-11,28,11,11,'F');doc.setTextColor(255,255,255);doc.setFont('helvetica','bold');doc.setFontSize(15);doc.text('VERIGO GLOBAL',M,33);doc.setFont('helvetica','normal');doc.setFontSize(8.5);doc.setTextColor(214,204,232);doc.text('Compliance by Design',M,49);doc.setTextColor(255,255,255);doc.setFontSize(8.5);doc.text('CMMI v2.0',W-M-20,35,{align:'right'});y=100; };
  const newPage = () => { doc.addPage(); header(); }; header();
  doc.setTextColor(...INK);doc.setFont('helvetica','bold');doc.setFontSize(21);doc.text('Custom Package Quote',M,y);y+=12;
  doc.setDrawColor(...ORANGE);doc.setLineWidth(2.5);doc.line(M,y,M+54,y);y+=20;
  const issued=new Date(); const valid=new Date(issued.getTime()+30*864e5); const dstr=d=>d.toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'});
  doc.setFont('helvetica','normal');doc.setFontSize(9.5);doc.setTextColor(...GREY);
  doc.text('Quote '+ref,M,y); doc.text('Issued '+dstr(issued)+'  ·  Valid until '+dstr(valid),W-M,y,{align:'right'}); y+=22;
  if (u.company||u.name) { doc.setFontSize(9);doc.setTextColor(...PURPLE);doc.setFont('helvetica','bold');doc.text('Prepared for '+(u.company||u.name),M,y);doc.setFont('helvetica','normal');doc.setTextColor(...GREY);doc.text(dstr(issued),W-M,y,{align:'right'});y+=20; }
  doc.setFont('helvetica','bold');doc.setFontSize(12.5);doc.setTextColor(...PURPLE);doc.text('Your custom package',M,y);y+=6;
  doc.setDrawColor(...PURPLE);doc.setLineWidth(0.8);doc.line(M,y,W-M,y);y+=18;
  lineItems.forEach((it,idx)=>{ const dl=doc.splitTextToSize(it.desc,W-M-(M+90)); const h=14+dl.length*11+10; if(y+h>H-70)newPage(); doc.setFont('helvetica','bold');doc.setFontSize(10.5);doc.setTextColor(...INK);doc.text((idx===0?'Base · ':'')+it.name,M,y);doc.setTextColor(...PURPLE);doc.text(fmt(it.price),W-M,y,{align:'right'});y+=14; doc.setFont('helvetica','normal');doc.setFontSize(9);doc.setTextColor(...GREY);dl.forEach(ln=>{doc.text(ln,M,y);y+=11;});y+=10; doc.setDrawColor(237,237,245);doc.setLineWidth(0.5);doc.line(M,y-4,W-M,y-4); });
  if(y>H-70)newPage(); doc.setFillColor(245,245,247);doc.rect(M,y-4,W-2*M,30,'F');doc.setFont('helvetica','bold');doc.setFontSize(11);doc.setTextColor(...INK);doc.text('Indicative total',M+12,y+15);doc.setFontSize(15);doc.setTextColor(...PURPLE);doc.text(fmt(total),W-M-12,y+16,{align:'right'});y+=44;
  const totalPages=doc.internal.getNumberOfPages(); for(let i=1;i<=totalPages;i++){doc.setPage(i);doc.setDrawColor(224,224,232);doc.setLineWidth(0.5);doc.line(M,H-38,W-M,H-38);doc.setFont('helvetica','normal');doc.setFontSize(8);doc.setTextColor(150,150,160);doc.text('© 2026 Verigo Global · Quote '+ref+' · Indicative',M,H-24);doc.text(i+' / '+totalPages,W-M,H-24,{align:'right'});}
  doc.save('Verigo-CMMI-Custom-Quote-'+ref+'.pdf'); return ref;
}

window.TK_CMMI = { POLICIES:CM_POLICIES, PROCEDURES:CM_PROCEDURES, CATS:CMMI_CATS, LEVELS:CMMI_LEVELS, ASSETS:CM_ASSETS, TIERS:CM_TIERS, ADDONS:CM_ADDONS, QUOTE_BASE, QUOTE_MODULES, QUOTE_TERMS, fmtPrice, getUser, storeLead, generatePDF, generateQuotePDF, CTRL_COUNT:CM_CTRL_COUNT };
