/**
 * Per-standard wording of the audit report (Form 04-2a for ISO 9001, Form 04-2b for ISO 14001, ...).
 *
 * Everything that differs between the Word forms of two standards but is NOT a clause row lives here:
 * finding-category definitions, objective / criteria text, audit-brief lines, the Stage 2 section titles
 * (section 10 "quality" vs "environmental" performance verification, section 12 customer vs interested-party
 * feedback), the interview line, the default "auditor's overall conclusion" and the attachment tick list.
 *
 * The profile is chosen from the standard NAME stored on the report (crm_json.standard_name), so approved
 * snapshots keep rendering with the wording they were approved with. A standard without a profile gets the
 * generic one (neutral "management system" wording). To add a standard: add one entry to PROFILES.
 */
import type { StageType } from './entities/audit-report.entity';
import { ATTACHMENTS, BRIEF_AREAS, BRIEF_COMMON, FINDING_CATEGORIES, ISO9001_TEXT, PREVIOUS_NC_DEFAULT } from './report.constants';

export interface StandardLabels {
  /** Section 10 bar, e.g. "Management system effectiveness — quality performance verification" */
  perf_title: string;
  perf_intro: string;
  /** First column header of the section 10 tables */
  perf_col: string;
  interview_roles: string[];
  interview_text: string;
  /** Section 11 bar (default "Risk management"; ISO 45001: "Hazard identification & risk management") */
  risk_title?: string;
  /** Section 11 intro */
  risk_intro: string;
  /** Section 12 bar */
  feedback_title: string;
  /** Section 13 intro */
  statutory_intro: string;
  /** Section 15 intro */
  effectiveness_intro: string;
}

export interface AttachmentItem {
  key: string;
  text: string;
  /** true = printed as a sub-heading row (no tick box), e.g. "MANDATORY DOCUMENTED INFORMATION VERIFIED" */
  heading?: boolean;
}

/** Colours (hex without #) and cover layout of a form. Form 04-2a is blue, Form 04-2b is green. */
export interface ReportTheme {
  /** section bars, table header rows, label cells */
  primary: string;
  /** text printed on those fills (white on the blue / green forms, dark on the light-blue IMS form) */
  primary_text: string;
  /** "Clause 6. Planning" group headings */
  group_heading: string;
  /** "QUALITY REGISTRAR SYSTEM" in the document control box, photo captions */
  brand: string;
  /** standard name + Doc. No. text in the document control box */
  docbox_text: string;
  /** "<standard> AUDIT REPORT" title on the first body page */
  page_title: string;
  /** filled tick box (HTML) */
  checkbox: string;
  /** background of the digital-evidence photo cells */
  evidence_fill: string;
  cover: {
    /** 'ims' = the three-column Integrated Management System cover (crest, FINAL AUDIT REPORT, company, three standards, bottom band) */
    kind?: 'ims';
    /** large crest printed at the top of the cover (IMS); file in templates/ */
    crest?: string;
    /** picture in templates/ */
    file: string;
    /** text printed over the picture above the company name, e.g. "FINAL AUDIT REPORT" (null = already in the picture) */
    label: string | null;
    label_color: string;
    company_color: string;
    std_color: string;
    /** when set, the standard name is printed two-tone: the first word in std_color, the rest in std_color2 (ISO 45001 cover) */
    std_color2?: string;
    sub_color: string;
    /** print the standard title ("ENVIRONMENTAL MANAGEMENT SYSTEM") under the standard (or under each IMS column) — false when the picture already carries it or it is not wanted */
    show_sub: boolean;
    rn_color: string;
    /** fixed positions in mm from the top of the page; null = the original flowing layout of the 9001 cover */
    top_mm: { label: number; company: number; std: number; rn: number } | null;
  };
}

export interface AuditTypeBox { text: string; on: boolean }

/** One column of the IMS cover: standard name + system name in that standard's colour */
export interface CoverColumn { main: string; sub: string; color: string }

export interface StandardProfile {
  key: 'iso9001' | 'iso14001' | 'iso45001' | 'ims' | 'generic';
  theme: ReportTheme;
  /**
   * standards.id whose clause_library rows and report_templates rows this form uses when the report is the COMBINED
   * report of an audit (standard_id 0). null = the combined report concatenates each standard's own list, as before.
   */
  library_standard_id: number | null;
  /** Report title / document-box name built from the covered standards. null = "<standard> AUDIT REPORT" as before. */
  title: ((names: string[], stage: StageType) => { title: string; line2: string; docbox: string }) | null;
  /** Columns of the IMS cover for a standard name; null = the ordinary cover. */
  cover_column: ((name: string, title: string) => CoverColumn) | null;
  /** Columns printed when the report covers one "umbrella" standard (standards.id 1) instead of a combined list. */
  cover_columns_default: CoverColumn[];
  /** Tick line under the report title. null = the shared "Stage 1 / Stage 2 / Surveillance / Recertification" boxes. */
  audit_type_boxes: ((stage: StageType, extras: Record<string, any>) => AuditTypeBox[]) | null;
  /** Italic line under the report title. null = the wording built into the templates. */
  form_subtitle: { stage1: string; full: string } | null;
  /** Fixed rows of the "Category of Audit Findings" table (Stage 2 form). null = one row per clause that has a finding (9001, 14001, IMS). */
  finding_components: { label: string; clauses: string[] }[] | null;
  /** Short name of the system: QMS / EMS / management system */
  system_short: string;
  /** Long name: Quality Management System / Environmental Management System */
  system_long: string;
  categories: { category: string; classification: string; definition: string }[];
  attachments: AttachmentItem[];
  labels: StandardLabels;
  /** Fixed objective / criteria text from the Word form. null = build a generic sentence from the standard name. */
  text: { stage1: { objective: string; criteria: string }; full: { objective: string; criteria: string } } | null;
  /** The two fill-in lines of "Audit brief and facts" (work instructions, site conditions) */
  brief_lines: string[];
  /** Extra paragraphs appended to the Stage 2 audit brief (ISO 9001 form only) */
  brief_areas: string[];
  /** Default "Auditor's overall conclusion" for Stage 2 / Surveillance / Recert. */
  effectiveness: (standardName: string) => string;
}

const CATEGORY_TAIL = [
  { category: 'Category 2', classification: 'Minor Non-Conformity', definition: 'A nonconformity which does not affect the capability of the management system to achieve its intended results, but reflects a single lapse or partial breakdown in the implementation of a documented process or requirement. Corrective action is mandatory.' },
  { category: 'Category 3', classification: 'Observation', definition: "Requirements and expectations are generally met, with minor inadequacies or omissions noted; in the auditor's opinion, preventive action would improve the effectiveness of the implemented management system. Corrective action is not mandatory." },
  { category: 'Category 4', classification: 'Satisfactory / Conformity', definition: 'The requirement is fully met and effectively implemented.' },
  { category: 'Category 5', classification: 'Positive Point', definition: 'A point worth noting as good practice or a particular strength, which the organization is encouraged to continue and build upon.' },
];

/** Form 04-2a (ISO 9001): the blue design, exactly as before */
const THEME_BLUE: ReportTheme = {
  primary: '4C94D8', primary_text: 'FFFFFF', group_heading: '331430', brand: '0A2A5E', docbox_text: '000000', page_title: '000000', checkbox: '0A2A5E', evidence_fill: 'F3F7FC',
  cover: { file: 'cover.jpg', label: null, label_color: '0A2A5E', company_color: '0A2A5E', std_color: '1A62B8', sub_color: '0A2A5E', show_sub: true, rn_color: '0A2A5E', top_mm: null },
};

/** Form 04-2b (ISO 14001): the green design of the sample Word files (fills 3A7C22, clause headings 1F3864, title 007700) */
const THEME_GREEN: ReportTheme = {
  primary: '3A7C22', primary_text: 'FFFFFF', group_heading: '1F3864', brand: '3A7C22', docbox_text: '331430', page_title: '3A7C22', checkbox: '3A7C22', evidence_fill: 'F2F8EE',
  cover: {
    file: 'cover-14001.jpg', label: 'FINAL AUDIT REPORT', label_color: '181717', company_color: '181717', std_color: '007700', sub_color: '181717',
    show_sub: false, // the picture already says ENVIRONMENTAL MANAGEMENT SYSTEM
    rn_color: '555555',
    top_mm: { label: 69, company: 88, std: 118, rn: 133 },
  },
};

/** Form 04-2a (ISO 45001): the orange design of the sample Word files (fills FF9966, clause headings 1F3864, title BF4E14) */
const THEME_ORANGE: ReportTheme = {
  primary: 'FF9966', primary_text: 'FFFFFF', group_heading: '1F3864', brand: 'BF4E14', docbox_text: '331430', page_title: 'BF4E14', checkbox: 'BF4E14', evidence_fill: 'FFF4EE',
  cover: {
    file: 'cover-45001.jpg', label: 'FINAL AUDIT REPORT', label_color: '181717', company_color: '181717', std_color: '54742A', std_color2: 'EE740C', sub_color: '181717',
    show_sub: false, // the picture already says OCCUPATIONAL HEALTH & SAFETY MANAGEMENT SYSTEM
    rn_color: '555555',
    top_mm: { label: 67, company: 88, std: 128, rn: 146 }, // label above the picture's orange line (~82 mm), company below it
  },
};

/** IMS (Form 04-2a, integrated): light-blue fills with dark text, three-column cover — from the IMS sample Word files */
const THEME_IMS: ReportTheme = {
  primary: 'C1E4F5', primary_text: '181717', group_heading: '1F3864', brand: '331430', docbox_text: '331430', page_title: '181717', checkbox: '181717', evidence_fill: 'F3F7FC',
  cover: {
    kind: 'ims', crest: 'crest-cover.png', file: 'cover-ims.jpg', label: 'FINAL AUDIT REPORT', label_color: '181717', company_color: '181717',
    // 2026-11-05: owner wanted only the standard names in the three columns (show_sub was false).
    // 2026-11-06: owner wants the columns exactly like the sample Word cover again — standard name, round icon
    // (templates/ims-icon-*.png, cut from samples/IMS_*.docx) and the system title under it.
    std_color: '181717', sub_color: '1A1915', show_sub: true,
    rn_color: '555555',
    top_mm: { label: 54, company: 66, std: 99, rn: 160 },
  },
};

// ───────────────────────── ISO 9001:2015 (Form 04-2a) — wording exactly as before ─────────────────────────
const ISO9001: StandardProfile = {
  key: 'iso9001',
  theme: THEME_BLUE,
  library_standard_id: null, title: null, cover_column: null, cover_columns_default: [],
  audit_type_boxes: null,
  form_subtitle: null,
  finding_components: null,
  system_short: 'QMS',
  system_long: 'Quality Management System',
  categories: FINDING_CATEGORIES,
  attachments: ATTACHMENTS,
  labels: {
    perf_title: 'Management system effectiveness — quality performance verification',
    perf_intro: 'Verification of the core quality performance elements of the QMS (ISO 9001:2015 Clauses 8.2–8.7, 9.1). Findings below are pre-drafted for the auditor to confirm, edit, or override, and to complete with the document reference sampled.',
    perf_col: 'Quality Management Element',
    interview_roles: ['Management Representative / Quality Manager', 'Process Owner(s)', 'Production / Service Delivery Personnel', 'Internal Auditor', 'Other: ______________'],
    interview_text: "Personnel interviewed demonstrated awareness of the organization's Quality Management System, the quality policy and relevant quality objectives, and their respective responsibilities in achieving conformity of products/services and continual improvement.",
    risk_intro: "Verification of the organization's approach to risks and opportunities relevant to the QMS (Clause 6.1), including internal and external issues, needs and expectations of interested parties, and compliance obligations.",
    feedback_title: 'Customer feedback and complaints (if any)',
    statutory_intro: 'Domestic / international requirements, product / service certification standards, insurance, international registration, and other applicable requirements.',
    effectiveness_intro: "Auditor's overall conclusion on the effectiveness of the Quality Management System, based on the audit evidence obtained. Edit as necessary.",
  },
  text: ISO9001_TEXT,
  brief_lines: [
    'Work instructions/guidance provided to employees before commencing work: ',
    'Work environment observed (ventilation, noise, lighting, housekeeping, welfare/rest facilities): ',
  ],
  brief_areas: BRIEF_AREAS,
  effectiveness: (std) => [
    `The audit confirmed that the organization has established, implemented and maintained a Quality Management System (QMS) in accordance with the requirements of ${std}. The organization has demonstrated effective implementation of processes for determining customer and product/service requirements, operational planning and control, and monitoring of customer satisfaction to support continual improvement.`,
    `**Leadership and Commitment**\nTop management has demonstrated commitment by providing the necessary resources, establishing quality objectives, promoting customer focus and risk-based thinking, and supporting the effective operation of the QMS. Based on the audit evidence obtained, the QMS is considered effective and capable of achieving its intended outcomes.`,
    `**Performance Evaluation:**`,
    `**Internal Audit:**\nThe organization has established a procedure for conducting internal audits at planned intervals, as defined in the internal audit procedure. The procedure covers audit planning, selection of competent auditors, scheduling, execution, reporting, and implementation of corrective actions. The evaluation of audit results is an input to the management review process.`,
    `**Management Review:**\nThe management review process is conducted to assess and ensure the continuing suitability, adequacy, effectiveness, and alignment of the QMS with the strategic direction and operational objectives of the organization. Management reviews are required at planned intervals, at least once annually.`,
    `**Customer Satisfaction:**\n• Customer satisfaction is monitored through the customer feedback and complaints register.\n• Customer feedback and complaints are recorded, monitored, and reviewed to evaluate customer satisfaction.\n• Monitoring of customer satisfaction is carried out at planned intervals, with results analysed and retained as documented information.`,
    `**Observations / Nonconformity Detail:**\nThe nonconformities and observations recorded for this audit are listed in the clause checklist and in the summary of audit.`,
    `**Overall Conclusion:**\nThe organization is recommended for certification, subject to the satisfactory implementation of corrective actions and closure of any identified nonconformities.`,
  ].join('\n\n'),
};

// ───────────────────────── ISO 14001:2026 (Form 04-2b) — from the two Word files in samples/ ─────────────────────────
const ISO14001_MANDATORY_DOCS: AttachmentItem[] = [
  { key: 'h_mandatory', heading: true, text: 'MANDATORY DOCUMENTED INFORMATION VERIFIED — ISO 14001:2026' },
  { key: 'm1', text: 'EMS Scope Statement (Clause 4.3)' },
  { key: 'm2', text: 'Environmental Policy (Clause 5.2)' },
  { key: 'm3', text: 'Environmental Aspects & Impacts Register, incl. significance criteria (Clause 6.1.2)' },
  { key: 'm4', text: 'Compliance Obligations / Legal Register (Clause 6.1.3)' },
  { key: 'm5', text: 'Environmental Objectives & Planning to Achieve Them (Clause 6.2.1/6.2.2)' },
  { key: 'm6', text: 'Evidence of Competence — training records/certificates (Clause 7.2)' },
  { key: 'm7', text: 'Evidence of Internal/External Communications (Clause 7.4)' },
  { key: 'm8', text: 'EMS Documented Information — manual/procedures determined necessary (Clause 7.5.1)' },
  { key: 'm9', text: 'Operational Control Procedure(s) (Clause 8.1)' },
  { key: 'm10', text: 'Emergency Preparedness & Response Procedure and Test Records (Clause 8.2)' },
  { key: 'm11', text: 'Monitoring, Measurement, Analysis & Evaluation Results (Clause 9.1.1)' },
  { key: 'm12', text: 'Evidence of Evaluation of Compliance Obligations (Clause 9.1.2)' },
  { key: 'm13', text: 'Internal Audit Programme and Audit Reports (Clause 9.2)' },
  { key: 'm14', text: 'Management Review Records — inputs and outputs (Clause 9.3)' },
  { key: 'm15', text: 'Nonconformity & Corrective Action Records (Clause 10.2)' },
];

const ISO14001: StandardProfile = {
  key: 'iso14001',
  theme: THEME_GREEN,
  library_standard_id: null, title: null, cover_column: null, cover_columns_default: [],
  // Stage 1 form: one box. Stage 2 form: Stage 2 (Initial) / Surveillance 1 / Surveillance 2 / Recertification.
  // The CRM does not say which surveillance it is, so extras.surveillance_no (1 or 2, set by the auditor) decides; default 1.
  audit_type_boxes: (stage, extras) => stage === 'stage1'
    ? [{ text: 'Initial Certification — Stage 1', on: true }]
    : [
        { text: 'Stage 2 (Initial)', on: stage === 'stage2' },
        { text: 'Surveillance 1', on: stage === 'surveillance' && Number(extras?.surveillance_no ?? 1) !== 2 },
        { text: 'Surveillance 2', on: stage === 'surveillance' && Number(extras?.surveillance_no ?? 1) === 2 },
        { text: 'Recertification', on: stage === 'recert' },
      ],
  form_subtitle: {
    stage1: 'Document Review & Organizational Readiness Checklist and Report',
    full: 'Stage 2 (Initial) / Surveillance 1 / Surveillance 2 / Recertification — Checklist and Report',
  },
  finding_components: null, // 2026-11-05: dynamic like ISO 9001 — one row per clause that has a finding
  system_short: 'EMS',
  system_long: 'Environmental Management System',
  categories: [
    { category: 'Category 1', classification: 'Major Non-Conformity', definition: "A nonconformity which affects the capability of the management system to achieve its intended results, raises significant doubt on the effectiveness of the EMS, could result in harm to the organization's ability to consistently meet its compliance obligations or manage its significant environmental aspects, or reflects the recurrence/persistence of an unresolved Minor Non-Conformity. Corrective action is mandatory." },
    ...CATEGORY_TAIL,
  ],
  attachments: [...ATTACHMENTS, ...ISO14001_MANDATORY_DOCS],
  labels: {
    perf_title: 'Management system effectiveness — environmental performance verification',
    perf_intro: 'Verification of core environmental performance elements of the EMS (ISO 14001:2026 Clauses 6.1.2, 6.1.3, 6.2, 8.1, 8.2, 9.1). Findings below are pre-drafted for the auditor to confirm, edit, or override, and to complete with the document reference sampled.',
    perf_col: 'Environmental Management Element',
    interview_roles: ['Management Representative / EMS Manager', 'Process Owner(s)', 'Operations / Site Personnel', 'Internal Auditor', 'Other: ______________'],
    interview_text: "Personnel interviewed demonstrated awareness of the organization's Environmental Management System, the environmental policy, significant environmental aspects and relevant environmental objectives, and their respective responsibilities in meeting compliance obligations and supporting continual improvement.",
    risk_intro: "Verification of the organization's approach to risks and opportunities relevant to the EMS (Clause 6.1), including internal and external issues, needs and expectations of interested parties, and compliance obligations.",
    feedback_title: 'Interested party feedback, complaints & environmental incidents (if any)',
    statutory_intro: 'Domestic / international environmental legal requirements, permits/licenses, environmental certification standards, insurance, international registration, and other applicable requirements.',
    effectiveness_intro: "Auditor's overall conclusion on the effectiveness of the Environmental Management System, based on the audit evidence obtained. Edit as necessary.",
  },
  text: {
    stage1: {
      objective: "To determine the readiness of the organization's Environmental Management System (EMS) for Stage 2 Certification by evaluating documented information, understanding the organization's context (including relevant environmental conditions), scope, environmental policy, compliance obligations, environmental aspects and impacts (considering a life cycle perspective), environmental objectives and planning processes, and the establishment of the management system in accordance with ISO 14001:2026.",
      criteria: "Organization context (including internal/external issues and environmental conditions such as climate change, pollution, natural resource availability and biodiversity), needs and expectations of interested parties, scope of the EMS, environmental policy, actions to address risks and opportunities, environmental aspects and impacts determined with a life cycle perspective, compliance obligations, environmental objectives and planning to achieve them, planning of changes, operational planning and control (including externally provided processes, products and services), emergency preparedness and response, monitoring and measurement processes, competence and awareness, documented information, and the organization's readiness for Stage 2 Certification Audit in accordance with ISO 14001:2026.",
    },
    full: {
      objective: "To verify the effective implementation, maintenance, and effectiveness of the Environmental Management System (EMS) in accordance with ISO 14001:2026, evaluate conformity with the standard requirements, verify meeting of applicable compliance obligations (statutory, regulatory and other requirements), assess the achievement of environmental objectives and planned results, confirm the organization's environmental aspects and impacts continue to be effectively managed considering a life cycle perspective, and confirm continual improvement of the EMS to support certification.",
      criteria: 'Organization context (incl. relevant environmental conditions) and interested parties, EMS scope and associated processes, environmental policy, environmental aspects and impacts (determined with a life cycle perspective), compliance obligations, actions to address risks and opportunities, environmental objectives and action plans, planning of changes, operational planning and control (incl. externally provided processes/products/services and life cycle considerations in design/development and procurement), emergency preparedness and response, competence and awareness, communication, monitoring, measurement, analysis and evaluation of environmental performance, evaluation of compliance obligations, performance evaluation, internal audit, management review, nonconformity and corrective actions, continual improvement, documented information (manual, procedures, records, and related documents), and verification of the effective implementation and effectiveness of the EMS in accordance with ISO 14001:2026.',
    },
  },
  brief_lines: [
    'Environmental controls/work instructions provided to employees prior to commencing work with environmental significance (e.g. chemical handling, waste segregation, spill response): ',
    'Site conditions observed relevant to environmental aspects (waste storage/segregation, chemical/hazardous materials storage, spill containment, emission or discharge points, energy/water metering, housekeeping relevant to environmental controls): ',
  ],
  brief_areas: [],
  effectiveness: (std) => [
    `The audit confirmed that the organization has established, implemented, and maintained an Environmental Management System (EMS) in accordance with the requirements of ${std}. The organization has demonstrated effective implementation of processes for determining and meeting compliance obligations, managing environmental aspects and impacts, operational planning and control, and monitoring of environmental performance to support continual improvement.`,
    `**Leadership and Commitment**\nTop management has demonstrated commitment by providing the necessary resources, establishing environmental objectives, promoting a life cycle perspective and risk-based thinking, and supporting the effective operation of the EMS. Based on the audit evidence obtained, the Environmental Management System is considered effective and capable of achieving its intended outcomes. Subject to the satisfactory closure of any identified nonconformities, the organization is recommended for certification to ${std}.`,
    `**Performance Evaluation**\nThe internal audit programme and management review process were verified and found to be effectively planned, conducted, and maintained, providing top management with reliable information on the suitability, adequacy, and continual improvement of the EMS. Monitoring of environmental performance and evaluation of compliance obligations (Clause 9.1.2) was confirmed to be carried out at planned intervals, with results analysed and retained as documented information.`,
    `**Observations / Nonconformity Detail:**\nThe nonconformities and observations recorded for this audit are listed in the clause checklist and in the summary of audit.`,
  ].join('\n\n'),
};

// ───────────────────────── ISO 14001:2015 (Form 04-2b, standards.id 5) — added 2026-11-10 ─────────────────────────
// Same green form and design as 14001:2026 (key stays 'iso14001' so cover/theme/boxes are identical). Only the wording
// differs, copied from samples/ISO14001_2015_Stage1_Audit_Report.docx and ISO14001_2015_Stage2_Surveillance_Recert_Report.docx.
// Clause library: seed/iso14001-2015.seed.ts (set key iso14001_2015), migration 009.
const ISO14001_2015_MANDATORY_DOCS: AttachmentItem[] = [
  { key: 'h_mandatory', heading: true, text: 'MANDATORY DOCUMENTED INFORMATION VERIFIED — ISO 14001:2015' },
  { key: 'm1', text: 'EMS Scope Statement (Clause 4.3)' },
  { key: 'm2', text: 'Environmental Policy (Clause 5.2)' },
  { key: 'm3', text: 'Risks & Opportunities and the processes needed in 6.1.1 to 6.1.4 (Clause 6.1.1)' },
  { key: 'm4', text: 'Environmental Aspects & Impacts, Significance Criteria and Significant Aspects (Clause 6.1.2)' },
  { key: 'm5', text: 'Compliance Obligations / Legal Register (Clause 6.1.3)' },
  { key: 'm6', text: 'Environmental Objectives (Clause 6.2.1) & Planning to Achieve Them (Clause 6.2.2)' },
  { key: 'm7', text: 'Evidence of Competence — training records/certificates (Clause 7.2)' },
  { key: 'm8', text: 'Evidence of Communications (Clause 7.4.1)' },
  { key: 'm9', text: 'EMS Documented Information — manual/procedures determined necessary (Clause 7.5.1)' },
  { key: 'm10', text: 'Operational Control Procedure(s) (Clause 8.1)' },
  { key: 'm11', text: 'Emergency Preparedness & Response Procedure and Test Records (Clause 8.2)' },
  { key: 'm12', text: 'Monitoring, Measurement, Analysis & Evaluation Results (Clause 9.1.1)' },
  { key: 'm13', text: 'Evidence of Evaluation of Compliance Obligations (Clause 9.1.2)' },
  { key: 'm14', text: 'Internal Audit Programme and Audit Results (Clause 9.2.2)' },
  { key: 'm15', text: 'Management Review Records — inputs and outputs (Clause 9.3)' },
  { key: 'm16', text: 'Nonconformity & Corrective Action Records — nature of nonconformities, actions taken and results (Clause 10.2)' },
];

const ISO14001_2015: StandardProfile = {
  ...ISO14001,
  attachments: [...ATTACHMENTS, ...ISO14001_2015_MANDATORY_DOCS],
  labels: {
    ...ISO14001.labels,
    perf_intro: 'Verification of core environmental performance elements of the EMS (ISO 14001:2015 Clauses 6.1.1 to 6.1.4, 6.2, 8.1, 8.2, 9.1). Findings below are pre-drafted for the auditor to confirm, edit, or override, and to complete with the document reference sampled.',
  },
  text: {
    stage1: {
      objective: "To determine the readiness of the organization's Environmental Management System (EMS) for Stage 2 Certification by evaluating documented information, understanding the organization's context (including relevant environmental conditions), scope, environmental policy, compliance obligations, environmental aspects and impacts (considering a life cycle perspective), environmental objectives and planning processes, and the establishment of the management system in accordance with ISO 14001:2015.",
      criteria: "Organization context (including internal/external issues and environmental conditions capable of affecting or being affected by the organization), needs and expectations of interested parties, scope of the EMS, environmental policy, actions to address risks and opportunities, environmental aspects and impacts determined with a life cycle perspective, compliance obligations, environmental objectives and planning to achieve them, operational planning and control (including outsourced processes and external providers), emergency preparedness and response, monitoring and measurement processes, competence and awareness, documented information, and the organization's readiness for Stage 2 Certification Audit in accordance with ISO 14001:2015.",
    },
    full: {
      objective: "To verify the effective implementation, maintenance, and effectiveness of the Environmental Management System (EMS) in accordance with ISO 14001:2015, evaluate conformity with the standard requirements, verify meeting of applicable compliance obligations (statutory, regulatory and other requirements), assess the achievement of environmental objectives and planned results, confirm the organization's environmental aspects and impacts continue to be effectively managed considering a life cycle perspective, and confirm continual improvement of the EMS to support certification.",
      criteria: 'Organization context (incl. relevant environmental conditions) and interested parties, EMS scope and associated processes, environmental policy, environmental aspects and impacts (determined with a life cycle perspective), compliance obligations, actions to address risks and opportunities, environmental objectives and action plans, operational planning and control (incl. outsourced processes / external providers and life cycle considerations in design/development and procurement), emergency preparedness and response, competence and awareness, communication, monitoring, measurement, analysis and evaluation of environmental performance, evaluation of compliance obligations, performance evaluation, internal audit, management review, nonconformity and corrective actions, continual improvement, documented information (manual, procedures, records, and related documents), and verification of the effective implementation and effectiveness of the EMS in accordance with ISO 14001:2015.',
    },
  },
};

// ───────────────────────── any other standard: neutral wording ─────────────────────────
const GENERIC: StandardProfile = {
  key: 'generic',
  theme: THEME_BLUE,
  library_standard_id: null, title: null, cover_column: null, cover_columns_default: [],
  audit_type_boxes: null,
  form_subtitle: null,
  finding_components: null,
  system_short: 'management system',
  system_long: 'management system',
  categories: [
    { category: 'Category 1', classification: 'Major Non-Conformity', definition: "A nonconformity which affects the capability of the management system to achieve its intended results, raises significant doubt on the effectiveness of the management system, could result in harm to the organization's ability to consistently meet applicable requirements, or reflects the recurrence/persistence of an unresolved Minor Non-Conformity. Corrective action is mandatory." },
    ...CATEGORY_TAIL,
  ],
  attachments: ATTACHMENTS,
  labels: {
    perf_title: 'Management system effectiveness — performance verification',
    perf_intro: 'Verification of the core performance elements of the management system. Findings below are pre-drafted for the auditor to confirm, edit, or override, and to complete with the document reference sampled.',
    perf_col: 'Management System Element',
    interview_roles: ['Management Representative', 'Process Owner(s)', 'Operations / Service Delivery Personnel', 'Internal Auditor', 'Other: ______________'],
    interview_text: "Personnel interviewed demonstrated awareness of the organization's management system, its policy and relevant objectives, and their respective responsibilities in achieving conformity and continual improvement.",
    risk_intro: "Verification of the organization's approach to risks and opportunities relevant to the management system, including internal and external issues, needs and expectations of interested parties, and compliance obligations.",
    feedback_title: 'Customer / interested party feedback and complaints (if any)',
    statutory_intro: 'Domestic / international requirements, certification standards, insurance, international registration, and other applicable requirements.',
    effectiveness_intro: "Auditor's overall conclusion on the effectiveness of the management system, based on the audit evidence obtained. Edit as necessary.",
  },
  text: null,
  brief_lines: ISO9001.brief_lines,
  brief_areas: [],
  effectiveness: (std) => [
    `The audit confirmed that the organization has established, implemented and maintained a management system in accordance with the requirements of ${std}. The organization has demonstrated effective implementation of its processes, operational planning and control, and monitoring of performance to support continual improvement.`,
    `**Leadership and Commitment**\nTop management has demonstrated commitment by providing the necessary resources, establishing objectives, promoting risk-based thinking, and supporting the effective operation of the management system. Based on the audit evidence obtained, the management system is considered effective and capable of achieving its intended outcomes.`,
    `**Observations / Nonconformity Detail:**\nThe nonconformities and observations recorded for this audit are listed in the clause checklist and in the summary of audit.`,
    `**Overall Conclusion:**\nThe organization is recommended for certification, subject to the satisfactory implementation of corrective actions and closure of any identified nonconformities.`,
  ].join('\n\n'),
};

// ───────────────────────── Integrated Management System (ISO 9001 + 14001 + 45001, Form 04-2a) — from samples/IMS_*.docx ─────────────────────────
const IMS_DEFAULT_COLUMNS: CoverColumn[] = [
  { main: 'ISO 9001:2015', sub: 'QUALITY MANAGEMENT SYSTEM', color: '404F8E' },
  { main: 'ISO 14001:2015', sub: 'ENVIRONMENTAL MANAGEMENT SYSTEM', color: '3E5E2F' },
  { main: 'ISO 45001:2018', sub: 'HEALTH & SAFETY MANAGEMENT SYSTEM', color: 'D75C2D' },
];

/** "ISO 9001:2015 / ISO 14001:2026 / ISO 45001:2018" -> the three names; the umbrella standard "ISO 9001, 14001 & 45001" -> its default names */
export function standardsOf(standardName: string | null | undefined): string[] {
  const name = String(standardName ?? '').trim();
  if (name.includes(' / ')) return name.split(' / ').map((x) => x.trim()).filter(Boolean);
  if (/9001.*14001.*45001/.test(name) && !/:\d{4}/.test(name)) return IMS_DEFAULT_COLUMNS.map((c) => c.main);
  return name ? [name] : [];
}
/** Round icon shown under a standard's name in the IMS cover columns (same pictures as the sample Word cover). */
export function imsIconFor(main: string | null | undefined): string | null {
  const n = String(main ?? '');
  if (/14001/.test(n)) return 'ims-icon-14001.png';
  if (/45001/.test(n)) return 'ims-icon-45001.png';
  if (/9001/.test(n)) return 'ims-icon-9001.png';
  return null;
}
/** ["A","B","C"] -> "A, B and C" */
export const joinAnd = (list: string[]): string => (list.length <= 1 ? list.join('') : `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`);
const fillStandards = (text: string, standardName: string) => text.replace(/\{STANDARDS\}/g, joinAnd(standardsOf(standardName)));

const IMS: StandardProfile = {
  key: 'ims',
  theme: THEME_IMS,
  library_standard_id: 1, // standards.id of "ISO 9001, 14001 & 45001" — holds the IMS clause list and template rows
  title: (names, stage) => ({
    title: 'INTEGRATED MANAGEMENT SYSTEM (IMS) AUDIT REPORT',
    line2: stage === 'stage1' ? '' : names.join(' | '),
    docbox: `Integrated Management System (${names.length > 1 ? `${names.slice(0, -1).join(', ')} & ${names[names.length - 1]}` : names.join('')})`,
  }),
  cover_column: (name, title) => {
    const base = /14001/.test(name) ? IMS_DEFAULT_COLUMNS[1] : /45001/.test(name) ? IMS_DEFAULT_COLUMNS[2] : /9001/.test(name) ? IMS_DEFAULT_COLUMNS[0] : { main: name, sub: '', color: '181717' };
    return { main: name, sub: (title || base.sub).toUpperCase(), color: base.color };
  },
  cover_columns_default: IMS_DEFAULT_COLUMNS,
  audit_type_boxes: ISO14001.audit_type_boxes,
  form_subtitle: ISO14001.form_subtitle,
  finding_components: null, // 2026-11-05: dynamic like ISO 9001 — one row per clause that has a finding
  system_short: 'IMS',
  system_long: 'Integrated Management System',
  categories: [
    { category: 'Category 1', classification: 'Major Non-Conformity', definition: 'A nonconformity which affects the capability of the management system to achieve its intended results, raises significant doubt on the effectiveness of the IMS, could result in harm to human health, safety or the environment, or reflects the recurrence/persistence of an unresolved Minor Non-Conformity. Corrective action is mandatory.' },
    ...CATEGORY_TAIL,
  ],
  attachments: ATTACHMENTS,
  labels: {
    perf_title: 'Management system effectiveness — core elements verification (QMS / EMS / OH&S)',
    perf_intro: 'Verification of the core elements of the Integrated Management System across {STANDARDS}. Findings below are pre-drafted for the auditor to confirm, edit, or override, and to complete with the document reference sampled.',
    perf_col: 'IMS Element (QMS / EMS / OH&S)',
    interview_roles: ['IMS / Management Representative', 'Quality Manager', 'HSE / Safety Manager', 'Operations / Production Manager', 'Internal Auditor', 'Worker Representative', 'Other: ______________'],
    interview_text: "Personnel interviewed demonstrated awareness of the organization's Integrated Management System, its policies and objectives, the significant environmental aspects and OH&S hazards relevant to their work, and their respective responsibilities in achieving continual improvement.",
    risk_intro: "Verification of the organization's approach to risks and opportunities relevant to the IMS (Clause 6.1), including internal and external issues, needs and expectations of interested parties including workers, environmental aspects, OH&S hazards, and compliance obligations.",
    feedback_title: 'Customer feedback and complaints (if any)',
    statutory_intro: 'Domestic / international requirements, product / service certification standards, insurance, international registration, and other applicable requirements.',
    effectiveness_intro: "Auditor's overall conclusion on the effectiveness of the Integrated Management System, based on the audit evidence obtained. Edit as necessary.",
  },
  text: {
    stage1: {
      objective: "To determine the readiness of the organization's Integrated Management System (IMS) for Stage 2 Certification by evaluating documented information, understanding the organization's context, scope, processes and their interactions, risks and opportunities, environmental aspects and impacts, hazard identification and assessment of OH&S risks, applicable legal and other requirements/compliance obligations, planning processes, and the establishment of the management system in accordance with {STANDARDS}.",
      criteria: "Organization context and interested parties including workers, scope of the IMS, integrated documented information, quality, environmental and OH&S policies, QMS processes and their sequence and interaction, environmental aspects and impacts including criteria for significance, hazard identification and assessment of OH&S risks and opportunities, legal and other requirements / compliance obligations, consultation and participation of workers, quality, environmental and OH&S objectives and plans, operational planning and control including customer requirements, design and development and externally provided processes (as applicable), life cycle perspective, hierarchy of controls, management of change and procurement/contractor arrangements, emergency preparedness and response, monitoring and measurement processes including customer satisfaction and evaluation of compliance, competence and awareness, documented procedures and records, and the organization's readiness for Stage 2 Certification Audit in accordance with {STANDARDS}.",
    },
    full: {
      objective: 'To verify the effective implementation, maintenance, and effectiveness of the Integrated Management System (IMS) in accordance with {STANDARDS}; evaluate conformity with the requirements of the standards; verify compliance with applicable statutory, regulatory, legal and other requirements / compliance obligations; assess the achievement of quality, environmental and OH&S objectives and planned results; and confirm continual improvement of the IMS and its performance to support certification.',
      criteria: 'Organization context and interested parties including workers, IMS and associated processes, quality, environmental and OH&S policies, objectives and plans, risks and opportunities, environmental aspects and impacts, hazard identification and assessment of OH&S risks, legal and other requirements / compliance obligations and their evaluation, consultation and participation of workers, operational planning and control (customer requirements, design and development, externally provided processes, production and service provision, life cycle perspective, hierarchy of controls, management of change, procurement and contractors), emergency preparedness and response, competence and awareness, communication, monitoring, measurement, analysis and evaluation including customer satisfaction, internal audit, management review, incident investigation, nonconformity and corrective actions, continual improvement, documented information (manual, procedures, records and related documents), and verification of the effective implementation and effectiveness of the IMS in accordance with {STANDARDS}.',
    },
  },
  brief_lines: ISO9001.brief_lines,
  // 2026-11-04 owner request: the IMS audit brief prints the full focus-area list (same as ISO 9001), not only the intro.
  brief_areas: BRIEF_AREAS,
  effectiveness: (std) => fillStandards([
    'The audit confirmed that the organization has established, implemented, and maintained an Integrated Management System (IMS) in accordance with the requirements of {STANDARDS}. The organization has demonstrated effective control of customer requirements and product/service conformity, identification and control of significant environmental aspects considering a life cycle perspective, hazard identification and control of OH&S risks following the hierarchy of controls, and evaluation of performance to support continual improvement.',
    '**Leadership and Commitment**\nTop management has demonstrated commitment by providing the necessary resources, establishing quality, environmental and OH&S objectives, promoting consultation and participation of workers, and supporting the effective operation of the IMS. Based on the audit evidence obtained, the Integrated Management System is considered effective and capable of achieving its intended outcomes. Subject to the satisfactory closure of any identified nonconformities, the organization is recommended for certification to {STANDARDS}.',
    '**Performance Evaluation**\nThe internal audit programme and management review process were verified and found to be effectively planned, conducted, and maintained, providing top management with reliable information on the suitability, adequacy, and continual improvement of the IMS. Customer satisfaction monitoring (ISO 9001, 9.1.2) and evaluation of compliance with legal and other requirements / compliance obligations (ISO 14001 / ISO 45001, 9.1.2) were confirmed to be carried out at planned intervals, with results retained as documented information.',
    '**Observations / Nonconformity Detail:**\nThe nonconformities and observations recorded for this audit are listed in the clause checklist and in the summary of audit.',
  ].join('\n\n'), std),
};

// ───────────────────────── ISO 45001:2018 (Form 04-2a) — from samples/ISO 45001_*.docx ─────────────────────────
const ISO45001: StandardProfile = {
  key: 'iso45001',
  theme: THEME_ORANGE,
  library_standard_id: null, title: null, cover_column: null, cover_columns_default: [],
  audit_type_boxes: ISO14001.audit_type_boxes,
  form_subtitle: ISO14001.form_subtitle,
  finding_components: [
    { label: 'Leadership & Commitment (5.1)', clauses: ['5.1'] },
    { label: 'OH&S Policy (5.2)', clauses: ['5.2'] },
    { label: 'Consultation & Participation of Workers (5.4)', clauses: ['5.4'] },
    { label: 'Competence (7.2)', clauses: ['7.2'] },
    { label: 'Awareness (7.3)', clauses: ['7.3'] },
    { label: 'Hazard ID & Risk Assessment / OH&S Objectives (6.1/6.2)', clauses: ['6.1', '6.2'] },
    { label: 'Operational Control & Hierarchy of Controls (8.1)', clauses: ['8.1'] },
    { label: 'Emergency Preparedness & Response (8.2)', clauses: ['8.2'] },
    { label: 'Internal Audit (9.2)', clauses: ['9.2'] },
    { label: 'Management Review (9.3)', clauses: ['9.3'] },
    { label: 'Monitoring, Measurement & Evaluation of Compliance (9.1)', clauses: ['9.1'] },
    { label: 'Incident, Nonconformity & Corrective Action (10.2)', clauses: ['10.2', '10.1', '10.3'] },
  ],
  system_short: 'OHSMS',
  system_long: 'Occupational Health & Safety Management System',
  categories: [
    { category: 'Category 1', classification: 'Major Non-Conformity', definition: 'A nonconformity which affects the capability of the management system to achieve its intended results, raises significant doubt on the effectiveness of the OHSMS, could result in harm to workers or other interested parties, or reflects the recurrence/persistence of an unresolved Minor Non-Conformity. Corrective action is mandatory.' },
    ...CATEGORY_TAIL,
  ],
  attachments: ATTACHMENTS,
  labels: {
    perf_title: 'Management system effectiveness — OH&S performance verification',
    perf_intro: 'Verification of the core OH&S performance elements of the OHSMS (ISO 45001:2018 Clauses 6.1.2, 8.1–8.2, 9.1). Findings below are pre-drafted for the auditor to confirm, edit, or override, and to complete with the document reference sampled.',
    perf_col: 'OH&S Management Element',
    interview_roles: ['Management Representative / HSE Manager', 'Process Owner(s)', 'Operations / Site Personnel', 'Internal Auditor', 'Other: ______________'],
    interview_text: "Personnel interviewed demonstrated awareness of the organization's OHSMS, the OH&S policy and relevant OH&S objectives, the hazards and risks relevant to their work, and their respective responsibilities in incident/hazard reporting and continual improvement.",
    risk_title: 'Hazard identification & risk management',
    risk_intro: "Verification of the organization's approach to hazard identification and OH&S risks and opportunities relevant to the OHSMS (Clause 6.1), including internal and external issues, needs and expectations of workers and other interested parties, and compliance obligations.",
    feedback_title: 'Incidents, near misses & ill-health (if any)',
    statutory_intro: 'Domestic / international requirements, OH&S-related permits and certifications, insurance, international registration, and other applicable requirements.',
    effectiveness_intro: "Auditor's overall conclusion on the effectiveness of the Occupational Health & Safety Management System, based on the audit evidence obtained. Edit as necessary.",
  },
  text: {
    stage1: {
      objective: "To determine the readiness of the organization's Occupational Health & Safety Management System (OHSMS) for Stage 2 Certification by evaluating documented information, understanding the organization's context, scope, OH&S policy, worker consultation and participation arrangements, hazard identification and risk assessment processes, legal and other requirements, OH&S objectives and planning processes, and the establishment of the management system in accordance with ISO 45001:2018.",
      criteria: "Organization context and interested parties, scope of the OHSMS, leadership and worker consultation/participation, OH&S policy, hazard identification and assessment of OH&S risks and opportunities, legal and other requirements, OH&S objectives and planning to achieve them, operational planning and control, emergency preparedness and response, monitoring and measurement processes, competence and awareness, documented information and records, and the organization's readiness for Stage 2 Certification Audit in accordance with ISO 45001:2018.",
    },
    full: {
      objective: 'To verify the effective implementation, maintenance, and effectiveness of the Occupational Health & Safety Management System (OHSMS) in accordance with ISO 45001:2018, evaluate conformity with the standard requirements, verify compliance with applicable legal, regulatory and other requirements, assess the achievement of OH&S objectives and planned results (including the reduction of OH&S risks and improvement of OH&S performance), and confirm continual improvement of the OHSMS to support certification.',
      criteria: 'Organization context and interested parties, OHSMS and associated processes, leadership and worker consultation/participation, OH&S policy, hazard identification, assessment of OH&S risks and opportunities, OH&S objectives and action plans, compliance with applicable legal, regulatory and other requirements, operational planning and control, elimination of hazards and reduction of OH&S risks, management of change, procurement, contractors and outsourcing, emergency preparedness and response, competence and awareness, communication, monitoring, measurement, analysis and evaluation, evaluation of compliance, performance evaluation, internal audit, management review, incident investigation, nonconformity and corrective actions, continual improvement, documented information (manual, procedures, records, and related documents), and verification of the effective implementation and effectiveness of the OHSMS in accordance with ISO 45001:2018.',
    },
  },
  brief_lines: [
    'Work instructions/guidance provided to employees prior to commencing work: ',
    'Work environment observed (hazards, PPE usage, ventilation, noise, lighting, housekeeping, welfare/rest facilities, emergency exits/firefighting equipment): ',
  ],
  brief_areas: [],
  effectiveness: (std) => [
    `The audit confirmed that the organization has established, implemented, and maintained an Occupational Health & Safety Management System (OHSMS) in accordance with the requirements of ${std}. The organization has demonstrated effective implementation of processes for hazard identification and OH&S risk assessment, operational planning and control, and monitoring of OH&S performance to support continual improvement.`,
    `**Leadership and Commitment**\nTop management has demonstrated commitment by providing the necessary resources, establishing OH&S objectives, promoting worker consultation and participation, protecting workers from reprisals, and supporting the effective operation of the OHSMS. Based on the audit evidence obtained, the Occupational Health & Safety Management System is considered effective and capable of achieving its intended outcomes. Subject to the satisfactory closure of any identified nonconformities, the organization is recommended for certification to ${std}.`,
    `**Performance Evaluation**\nThe internal audit programme and management review process were verified and found to be effectively planned, conducted, and maintained, providing top management with reliable information on the suitability, adequacy, and continual improvement of the OHSMS. Evaluation of compliance with legal and other requirements (Clause 9.1.2) was confirmed to be carried out at planned intervals, with results analysed and retained as documented information.`,
    `**Observations / Nonconformity Detail:**\nThe nonconformities and observations recorded for this audit are listed in the clause checklist and in the summary of audit.`,
  ].join('\n\n'),
};

/**
 * Order matters. IMS first: a combined report (or the umbrella standard "ISO 9001, 14001 & 45001") that covers two or
 * more of ISO 9001 / 14001 / 45001 prints the IMS form. A single-standard report keeps its own form.
 */
const PROFILES: { match: (name: string) => boolean; profile: StandardProfile }[] = [
  { match: (n) => [/9001/, /14001/, /45001/].filter((r) => r.test(n)).length >= 2, profile: IMS },
  { match: (n) => /9001/.test(n), profile: ISO9001 },
  { match: (n) => /14001\s*:\s*2015/.test(n), profile: ISO14001_2015 }, // 2026-11-10: own 2015 wording
  { match: (n) => /14001/.test(n), profile: ISO14001 },
  { match: (n) => /45001/.test(n), profile: ISO45001 },
];

export function profileFor(standardName: string | null | undefined): StandardProfile {
  const name = String(standardName ?? '');
  return PROFILES.find((p) => p.match(name))?.profile ?? GENERIC;
}

/** Labels with the {STANDARDS} placeholder filled in for this report. */
export function labelsFor(profile: StandardProfile, standardName: string): StandardLabels {
  const out: any = { ...profile.labels };
  for (const k of Object.keys(out)) if (typeof out[k] === 'string') out[k] = fillStandards(out[k], standardName);
  return out;
}

/** Default body for a free-text section when a report is created. The auditor edits it afterwards. */
export function defaultSectionBody(key: string, stage: StageType, standardName: string): string {
  const std = standardName || 'the reference standard';
  const p = profileFor(standardName);
  const which = stage === 'stage1' ? 'stage1' : 'full';
  if (key === 'objective') {
    if (p.text) return fillStandards(p.text[which].objective, standardName);
    return stage === 'stage1'
      ? `To determine the readiness of the organization's management system for Stage 2 certification audit against ${std}.`
      : `To verify the effective implementation, maintenance and effectiveness of the management system against ${std} and confirm continual improvement to support certification.`;
  }
  if (key === 'criteria') {
    if (p.text) return fillStandards(p.text[which].criteria, standardName);
    return `The requirements of ${std}, applicable statutory and regulatory requirements, and the organization's own management system documentation.`;
  }
  if (key === 'audit_brief') {
    const parts = [...BRIEF_COMMON, ...p.brief_lines];
    if (stage === 'stage1') {
      parts.push('Where required documented information, records, or other objective evidence were not available for review during Stage 1, the matter was identified and communicated to the organization for appropriate action and further verification during Stage 2, where applicable.');
    } else {
      parts.push(...p.brief_areas);
    }
    return parts.join('\n\n');
  }
  if (key === 'prev_nc') return PREVIOUS_NC_DEFAULT;
  if (key === 'effectiveness') return stage === 'stage1' ? '' : p.effectiveness(std);
  return '';
}
