/* global window */
// ============================================================================
// MELR · World Bank Implementation Status & Results (ISR) export
// ----------------------------------------------------------------------------
// Generates a World Bank Implementation Status and Results Report (ISR) as
// a .docx file. The ISR is the World Bank's standard semi-annual project
// monitoring artifact (formerly called "Implementation Completion Report"
// for the closing version). It documents the Project Development Objective
// (PDO), implementation status, results indicators, and risk ratings.
//
// Generated structure:
//   1. Cover Page (WB blue branding)
//   2. Project Development Objective (PDO) statement
//   3. Project Status Summary (implementation progress, financial
//      execution, ratings)
//   4. PDO-level Results Indicators table
//   5. Intermediate Results Indicators table (grouped by component)
//   6. Implementation Performance Ratings (6-level WB scale)
//   7. Risk Assessment (Operations Risk Assessment Framework — ORAF lite)
//   8. Lessons Learned
//
// Entry point: window.exportWorldBankIsr({...})
// Uses shared helpers via window.melrDonor.
// ============================================================================

(function () {
  if (typeof window === "undefined") return;

  const WB_BLUE = "002244";       // World Bank navy blue
  const WB_ACCENT = "0078D4";     // Accent blue

  function _shared() { return window.melrDonor; }
  function _ok() { return !!(_shared() && _shared().isReady && _shared().isReady()); }

  function buildCover({ orgName, scopeLabel, year, lang }) {
    const { Paragraph, TextRun, AlignmentType } = window.docx;
    const L = _shared().L;
    return [
      new Paragraph({ spacing: { before: 1200 }, children: [] }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: "The World Bank", bold: true, size: 56, color: WB_BLUE })],
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        spacing: { after: 200 },
        children: [new TextRun({ text: L(lang, "Groupe de la Banque mondiale", "World Bank Group", "Grupo del Banco Mundial"), italics: true, size: 22, color: _shared().COLORS.MUTED })],
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        spacing: { after: 600 },
        children: [new TextRun({ text: L(lang, "Implementation Status & Results Report (ISR)",
                                              "Implementation Status & Results Report (ISR)"), bold: true, size: 30, color: WB_BLUE })],
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        spacing: { after: 200 },
        children: [new TextRun({ text: scopeLabel || L(lang, "Projet", "Project", "Proyecto"), bold: true, size: 28 })],
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        spacing: { after: 200 },
        children: [new TextRun({ text: orgName || L(lang, "Agence de mise en œuvre", "Implementing agency", "Agencia ejecutora"), size: 24, color: _shared().COLORS.MUTED })],
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        spacing: { before: 800, after: 200 },
        children: [new TextRun({ text: L(lang, "Période de référence", "Reporting period", "Período de referencia") + " : FY" + year, size: 22 })],
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        spacing: { after: 1600 },
        children: [new TextRun({ text: L(lang, "Document généré le ", "Generated on ", "Documento generado el ") + new Date().toLocaleDateString(window.L("fr-FR", "en-US", "es-ES")), size: 20, color: _shared().COLORS.MUTED, italics: true })],
      }),
      new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: L(lang, "Généré automatiquement par MELR · REFT Africa", "Auto-generated by MELR · REFT Africa", "Generado automáticamente por MELR · REFT Africa"), size: 18, color: _shared().COLORS.MUTED })],
      }),
    ];
  }

  function buildPDO({ scopeLabel, lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, Spacer } = s;
    const out = [];
    out.push(H(1, s.L(lang, "1. Objectif de développement du projet (PDO)", "1. Project Development Objective (PDO)", "1. Objetivo de desarrollo del proyecto (PDO)"), { color: WB_BLUE }));
    out.push(P(s.L(lang,
      "Le PDO formalise l'effet de développement principal recherché par le projet. Il est mesuré par un nombre limité d'indicateurs PDO-level (3 à 5 typiquement).",
      "The PDO formalizes the main development outcome sought by the project. It is measured by a limited number of PDO-level indicators (typically 3 to 5).", "El PDO formaliza el principal efecto de desarrollo perseguido por el proyecto. Se mide mediante un número limitado de indicadores PDO-level (de 3 a 5 normalmente).")));

    const FILL = "F3F4F6";
    out.push(Tbl([
      Row([
        Cell(s.L(lang, "Énoncé du PDO", "PDO Statement", "Enunciado del PDO"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang,
          "[À renseigner] Contribuer durablement aux objectifs de développement nationaux du pays bénéficiaire dans le secteur ciblé par le projet, en cohérence avec la stratégie pays (CPF).",
          "[To be completed] Sustainably contribute to the beneficiary country's national development objectives in the target sector, in line with the Country Partnership Framework (CPF).", "[A completar] Contribuir de forma sostenible a los objetivos de desarrollo nacionales del país beneficiario en el sector específico del proyecto, en coherencia con la estrategia país (CPF)."), { width: 6360, size: 20 }),
      ]),
      Row([
        Cell(s.L(lang, "Bénéficiaires principaux", "Primary beneficiaries", "Beneficiarios principales"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang, "[À renseigner — cf. document d'évaluation du projet (PAD)]",
                        "[To be completed — see Project Appraisal Document (PAD)]", "[A completar — véase el documento de evaluación del proyecto (PAD)]"), { width: 6360, size: 20 }),
      ]),
      Row([
        Cell(s.L(lang, "Composantes", "Components", "Componentes"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang,
          "Composante 1 : … · Composante 2 : … · Composante 3 : … · Gestion de projet.",
          "Component 1: … · Component 2: … · Component 3: … · Project management.", "Componente 1: … · Componente 2: … · Componente 3: … · Gestión del proyecto."), { width: 6360, size: 20 }),
      ]),
    ], { columnWidths: [3000, 6360] }));
    out.push(Spacer());

    return out;
  }

  function buildStatusSummary({ projects, year, lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, PageBreak } = s;
    const out = [];
    out.push(PageBreak());
    out.push(H(1, s.L(lang, "2. Synthèse du statut du projet", "2. Project Status Summary", "2. Síntesis del estado del proyecto"), { color: WB_BLUE }));
    out.push(P(s.L(lang,
      "Synthèse des principaux jalons d'implémentation, exécution financière et appréciation globale.",
      "Summary of key implementation milestones, financial execution, and overall assessment.", "Síntesis de los principales hitos de implementación, ejecución financiera y valoración global.")));

    const FILL = "F3F4F6";
    out.push(Tbl([
      Row([
        Cell(s.L(lang, "Date d'approbation Conseil", "Board approval date", "Fecha de aprobación por el Consejo"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang, "À renseigner", "To be completed", "Por cumplimentar"), { width: 6360, size: 20 }),
      ]),
      Row([
        Cell(s.L(lang, "Date d'effectivité", "Effectiveness date", "Fecha de efectividad"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang, "À renseigner", "To be completed", "Por cumplimentar"), { width: 6360, size: 20 }),
      ]),
      Row([
        Cell(s.L(lang, "Date de clôture prévue", "Planned closing date", "Fecha de cierre prevista"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang, "À renseigner", "To be completed", "Por cumplimentar"), { width: 6360, size: 20 }),
      ]),
      Row([
        Cell(s.L(lang, "Montant approuvé (USD M)", "Approved amount (USD M)", "Importe aprobado (USD M)"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang, "À renseigner", "To be completed", "Por cumplimentar"), { width: 6360, size: 20 }),
      ]),
      Row([
        Cell(s.L(lang, "Décaissement à ce jour (%)", "Disbursement to date (%)", "Desembolso a la fecha (%)"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(s.L(lang, "À renseigner", "To be completed", "Por cumplimentar"), { width: 6360, size: 20 }),
      ]),
      Row([
        Cell(s.L(lang, "Nombre de projets / sites couverts", "Projects / sites covered", "Número de proyectos / sitios cubiertos"), { width: 3000, bold: true, fill: FILL, color: WB_BLUE, size: 18 }),
        Cell(String((projects || []).length), { width: 6360, size: 20 }),
      ]),
    ], { columnWidths: [3000, 6360] }));

    return out;
  }

  function _isPdoIndicator(ind) {
    return (ind.level || "").trim() === "Impact" || (ind.level || "").trim() === "Outcome";
  }

  function buildPdoIndicators({ indicators, year, lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, PageBreak } = s;
    const Y = 3;
    const out = [];
    out.push(PageBreak());
    out.push(H(1, s.L(lang, "3. Indicateurs PDO (résultats de développement)", "3. PDO-level Results Indicators", "3. Indicadores PDO (resultados de desarrollo)"), { color: WB_BLUE }));
    out.push(P(s.L(lang,
      "Indicateurs de haut niveau qui mesurent l'atteinte de l'Objectif de développement du projet. Ils sont définis dans le Cadre de résultats (Results Framework) annexé au PAD.",
      "High-level indicators measuring achievement of the Project Development Objective. Defined in the Results Framework annexed to the PAD.", "Indicadores de alto nivel que miden la consecución del Objetivo de desarrollo del proyecto. Se definen en el Marco de resultados (Results Framework) anexo al PAD.")));

    const pdoInds = (indicators || []).filter(_isPdoIndicator);
    const baseYear = parseInt(year, 10) || new Date().getFullYear();
    const yLabels = [];
    for (let i = 1; i <= Y; i++) yLabels.push("FY" + (baseYear - Y + i));

    const hdr = { bold: true, color: "FFFFFF", fill: WB_BLUE };
    const headerCells = [
      Cell(s.L(lang, "Code", "Code"),                  { ...hdr, width: 800 }),
      Cell(s.L(lang, "Indicateur PDO", "PDO Indicator", "Indicador PDO"), { ...hdr, width: 2600 }),
      Cell(s.L(lang, "Unité", "Unit", "Unidad"),                 { ...hdr, width: 600 }),
      Cell(s.L(lang, "Base", "Baseline", "Línea de base"),              { ...hdr, width: 800 }),
    ];
    yLabels.forEach((yl) => {
      headerCells.push(Cell(yl + " " + s.L(lang, "Cible", "Target", "Meta"),  { ...hdr, width: 800, align: window.docx.AlignmentType.CENTER }));
      headerCells.push(Cell(yl + " " + s.L(lang, "Réal.", "Actual", "Real."),  { ...hdr, width: 800, align: window.docx.AlignmentType.CENTER }));
      headerCells.push(Cell("%", { ...hdr, width: 520, align: window.docx.AlignmentType.CENTER }));
    });
    const rows = [Row(headerCells)];
    pdoInds.forEach((ind) => {
      const perf = s.computePerformance(ind, baseYear, Y);
      rows.push(s.iptRow(ind, perf, lang, Y));
    });
    if (pdoInds.length === 0) {
      rows.push(Row([Cell(s.L(lang, "Aucun indicateur PDO (niveau Impact/Outcome) dans le périmètre",
                                    "No PDO indicators (Impact/Outcome level) in scope", "Ningún indicador PDO (nivel Impacto/Outcome) en el ámbito"),
        { colSpan: 4 + 3 * Y, color: s.COLORS.MUTED, align: window.docx.AlignmentType.CENTER })]));
    }
    const widths = [800, 2600, 600, 800];
    for (let i = 0; i < Y; i++) widths.push(800, 800, 520);
    out.push(Tbl(rows, { columnWidths: widths, width: widths.reduce((a, b) => a + b, 0) }));

    return out;
  }

  function buildIntermediateIndicators({ indicators, year, lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, PageBreak, Spacer } = s;
    const out = [];
    out.push(PageBreak());
    out.push(H(1, s.L(lang, "4. Indicateurs de résultats intermédiaires", "4. Intermediate Results Indicators", "4. Indicadores de resultados intermedios"), { color: WB_BLUE }));
    out.push(P(s.L(lang,
      "Indicateurs Output qui mesurent les livrables des composantes du projet. Ils sont organisés par composante et utilisés pour le suivi opérationnel mensuel / trimestriel.",
      "Output indicators measuring component deliverables. Organized by component and used for monthly / quarterly operational monitoring.", "Indicadores Output que miden los productos de los componentes del proyecto. Se organizan por componente y se utilizan para el seguimiento operativo mensual / trimestral.")));

    const interInds = (indicators || []).filter((i) => !_isPdoIndicator(i));
    // Group by sector as a proxy for "component" since we don't have explicit
    // component metadata yet.
    const bySector = {};
    interInds.forEach((i) => {
      const sec = (i.sector || i.sectorCode || s.L(lang, "Sans composante", "No component", "Sin componente"));
      if (!bySector[sec]) bySector[sec] = [];
      bySector[sec].push(i);
    });

    const baseYear = parseInt(year, 10) || new Date().getFullYear();
    const yLabels = [];
    for (let i = 1; i <= 3; i++) yLabels.push("FY" + (baseYear - 3 + i));

    const hdr = { bold: true, color: "FFFFFF", fill: WB_BLUE };

    if (Object.keys(bySector).length === 0) {
      out.push(P(s.L(lang, "Aucun indicateur intermédiaire dans le périmètre.",
                          "No intermediate indicators in scope.", "Ningún indicador intermedio en el ámbito."), { run: { italics: true, color: s.COLORS.MUTED } }));
      return out;
    }

    Object.keys(bySector).forEach((sec) => {
      out.push(H(2, s.L(lang, "Composante : ", "Component: ", "Componente: ") + sec, { color: WB_BLUE }));
      const headerCells = [
        Cell(s.L(lang, "Code", "Code"),                  { ...hdr, width: 800 }),
        Cell(s.L(lang, "Indicateur", "Indicator", "Indicador"),       { ...hdr, width: 2600 }),
        Cell(s.L(lang, "Unité", "Unit", "Unidad"),                 { ...hdr, width: 600 }),
        Cell(s.L(lang, "Base", "Baseline", "Línea de base"),              { ...hdr, width: 800 }),
      ];
      yLabels.forEach((yl) => {
        headerCells.push(Cell(yl + " " + s.L(lang, "Cible", "Target", "Meta"),  { ...hdr, width: 800, align: window.docx.AlignmentType.CENTER }));
        headerCells.push(Cell(yl + " " + s.L(lang, "Réal.", "Actual", "Real."),  { ...hdr, width: 800, align: window.docx.AlignmentType.CENTER }));
        headerCells.push(Cell("%", { ...hdr, width: 520, align: window.docx.AlignmentType.CENTER }));
      });
      const rows = [Row(headerCells)];
      bySector[sec].forEach((ind) => {
        const perf = s.computePerformance(ind, baseYear, 3);
        rows.push(s.iptRow(ind, perf, lang, 3));
      });
      const widths = [800, 2600, 600, 800, 800, 800, 520, 800, 800, 520, 800, 800, 520];
      out.push(Tbl(rows, { columnWidths: widths, width: widths.reduce((a, b) => a + b, 0) }));
      out.push(Spacer(140));
    });

    return out;
  }

  function buildPerformanceRatings({ lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, PageBreak } = s;
    const out = [];
    out.push(PageBreak());
    out.push(H(1, s.L(lang, "5. Notations de performance de mise en œuvre", "5. Implementation Performance Ratings", "5. Calificaciones de desempeño de la implementación"), { color: WB_BLUE }));
    out.push(P(s.L(lang,
      "Notations sur l'échelle standard Banque mondiale en 6 niveaux : HS (Très satisfaisant), S (Satisfaisant), MS (Modérément satisfaisant), MU (Modérément insatisfaisant), U (Insatisfaisant), HU (Très insatisfaisant).",
      "Ratings on the standard World Bank 6-level scale: HS (Highly Satisfactory), S (Satisfactory), MS (Moderately Satisfactory), MU (Moderately Unsatisfactory), U (Unsatisfactory), HU (Highly Unsatisfactory).", "Calificaciones en la escala estándar del Banco Mundial de 6 niveles: HS (Muy satisfactorio), S (Satisfactorio), MS (Moderadamente satisfactorio), MU (Moderadamente insatisfactorio), U (Insatisfactorio), HU (Muy insatisfactorio).")));

    const hdr = { bold: true, color: "FFFFFF", fill: WB_BLUE };
    const rows = [Row([
      Cell(s.L(lang, "Domaine", "Area", "Ámbito"),                       { ...hdr, width: 3500 }),
      Cell(s.L(lang, "Notation actuelle", "Current rating", "Calificación actual"),  { ...hdr, width: 2200, align: window.docx.AlignmentType.CENTER }),
      Cell(s.L(lang, "Évolution depuis dernier ISR", "Change since last ISR", "Evolución desde el último ISR"), { ...hdr, width: 3660, align: window.docx.AlignmentType.CENTER }),
    ])];
    const areas = [
      { fr: "Progrès vers atteinte du PDO",        en: "Progress towards achievement of PDO", es: "Avance hacia el logro del PDO" },
      { fr: "Performance globale d'exécution",     en: "Overall implementation performance", es: "Desempeño global de la ejecución" },
      { fr: "Gestion financière",                  en: "Financial management", es: "Gestión financiera" },
      { fr: "Passation de marchés",                en: "Procurement", es: "Adquisiciones" },
      { fr: "Conformité aux clauses légales",      en: "Compliance with legal covenants", es: "Cumplimiento de las cláusulas legales" },
      { fr: "Politique de sauvegarde environnementale", en: "Environmental safeguard policy", es: "Política de salvaguarda ambiental" },
      { fr: "Politique de sauvegarde sociale",      en: "Social safeguard policy", es: "Política de salvaguarda social" },
      { fr: "Suivi & évaluation",                  en: "Monitoring & Evaluation", es: "Seguimiento y evaluación" },
    ];
    areas.forEach((a) => rows.push(Row([
      Cell(s.L(lang, a.fr, a.en),       { width: 3500, size: 18 }),
      Cell(s.L(lang, "À noter", "TBD", "Por determinar"), { width: 2200, size: 18, align: window.docx.AlignmentType.CENTER }),
      Cell("—",                          { width: 3660, size: 18, align: window.docx.AlignmentType.CENTER }),
    ])));
    out.push(Tbl(rows, { columnWidths: [3500, 2200, 3660] }));

    return out;
  }

  function buildRiskAssessment({ lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, PageBreak } = s;
    const out = [];
    out.push(PageBreak());
    out.push(H(1, s.L(lang, "6. Évaluation des risques (cadre ORAF allégé)", "6. Risk Assessment (Light ORAF framework)", "6. Evaluación de riesgos (marco ORAF simplificado)"), { color: WB_BLUE }));
    out.push(P(s.L(lang,
      "Les risques sont évalués selon le cadre Operations Risk Assessment Framework (ORAF) de la Banque mondiale, en deux dimensions : risque inhérent et risque résiduel après mesures.",
      "Risks are assessed per the World Bank Operations Risk Assessment Framework (ORAF), across two dimensions: inherent risk and residual risk after mitigation.", "Los riesgos se evalúan según el marco Operations Risk Assessment Framework (ORAF) del Banco Mundial, en dos dimensiones: riesgo inherente y riesgo residual tras las medidas.")));

    const hdr = { bold: true, color: "FFFFFF", fill: WB_BLUE };
    const rows = [Row([
      Cell(s.L(lang, "Catégorie de risque", "Risk category", "Categoría de riesgo"),  { ...hdr, width: 3000 }),
      Cell(s.L(lang, "Inhérent", "Inherent", "Inherente"),                  { ...hdr, width: 1600, align: window.docx.AlignmentType.CENTER }),
      Cell(s.L(lang, "Mesures clés", "Key mitigation", "Medidas clave"),        { ...hdr, width: 3160 }),
      Cell(s.L(lang, "Résiduel", "Residual", "Residual"),                  { ...hdr, width: 1600, align: window.docx.AlignmentType.CENTER }),
    ])];
    const cats = [
      { fr: "Macroéconomique",          en: "Macroeconomic", es: "Macroeconómico",
        ih: s.L(lang, "Substantiel", "Substantial", "Sustancial"),
        m_fr: "Veille budgétaire trimestrielle, clauses de réajustement.", m_en: "Quarterly budget watch, adjustment clauses.", m_es: "Vigilancia presupuestaria trimestral, cláusulas de reajuste.",
        re: s.L(lang, "Modéré", "Moderate", "Moderado") },
      { fr: "Politique & gouvernance",  en: "Political & Governance", es: "Política y gobernanza",
        ih: s.L(lang, "Élevé", "High", "Alto"),
        m_fr: "Dialogue institutionnel renforcé, alignement CPF.", m_en: "Strengthened institutional dialogue, CPF alignment.", m_es: "Diálogo institucional reforzado, alineación con el CPF.",
        re: s.L(lang, "Substantiel", "Substantial", "Sustancial") },
      { fr: "Capacité institutionnelle", en: "Institutional Capacity", es: "Capacidad institucional",
        ih: s.L(lang, "Substantiel", "Substantial", "Sustancial"),
        m_fr: "Assistance technique, formation cadres ministériels.", m_en: "Technical assistance, training of ministry officers.", m_es: "Asistencia técnica, formación de cuadros ministeriales.",
        re: s.L(lang, "Modéré", "Moderate", "Moderado") },
      { fr: "Fiduciaire",               en: "Fiduciary", es: "Fiduciario",
        ih: s.L(lang, "Modéré", "Moderate", "Moderado"),
        m_fr: "Audits annuels, FM Assessment, expertise PRAG.", m_en: "Annual audits, FM Assessment, PRAG expertise.", m_es: "Auditorías anuales, FM Assessment, experiencia PRAG.",
        re: s.L(lang, "Modéré", "Moderate", "Moderado") },
      { fr: "Environnemental & social",  en: "Environmental & Social", es: "Ambiental y social",
        ih: s.L(lang, "Modéré", "Moderate", "Moderado"),
        m_fr: "Application des Cadres environnementaux et sociaux (ESF).", m_en: "Implementation of the Environmental & Social Framework (ESF).", m_es: "Aplicación de los Marcos ambientales y sociales (ESF).",
        re: s.L(lang, "Faible", "Low", "Baja") },
      { fr: "Autres (sécurité, climat)", en: "Other (security, climate)", es: "Otros (seguridad, clima)",
        ih: s.L(lang, "Variable", "Variable"),
        m_fr: "Plans de continuité, suivi sécuritaire, adaptation climatique.", m_en: "Continuity plans, security tracking, climate adaptation.", m_es: "Planes de continuidad, seguimiento de seguridad, adaptación climática.",
        re: s.L(lang, "Modéré", "Moderate", "Moderado") },
    ];
    cats.forEach((c) => rows.push(Row([
      Cell(s.L(lang, c.fr, c.en),       { width: 3000, size: 18 }),
      Cell(c.ih,                        { width: 1600, size: 18, align: window.docx.AlignmentType.CENTER }),
      Cell(s.L(lang, c.m_fr, c.m_en),   { width: 3160, size: 18 }),
      Cell(c.re,                        { width: 1600, size: 18, align: window.docx.AlignmentType.CENTER }),
    ])));

    out.push(Tbl(rows, { columnWidths: [3000, 1600, 3160, 1600] }));

    return out;
  }

  function buildLessons({ lang }) {
    const s = _shared();
    const { H, P, PageBreak } = s;
    const out = [];
    out.push(PageBreak());
    out.push(H(1, s.L(lang, "7. Leçons apprises", "7. Lessons Learned", "7. Lecciones aprendidas"), { color: WB_BLUE }));
    out.push(P(s.L(lang,
      "Cette section capture les leçons opérationnelles et stratégiques tirées de la mise en œuvre depuis le dernier ISR. Elle alimente le module Apprentissage de MELR et les évaluations à mi-parcours.",
      "This section captures operational and strategic lessons drawn from implementation since the last ISR. It feeds the MELR Learning module and mid-term evaluations.", "Esta sección recoge las lecciones operativas y estratégicas extraídas de la implementación desde el último ISR. Alimenta el módulo de Aprendizaje de MELR y las evaluaciones de medio término.")));
    out.push(P("• " + s.L(lang, "Ce qui a bien fonctionné — pratiques à conserver et amplifier",
                                "What worked well — practices to maintain and scale up", "Lo que funcionó bien — prácticas a mantener y ampliar"), { run: { size: 22 } }));
    out.push(P("• " + s.L(lang, "Ce qui a moins bien fonctionné — pratiques à ajuster",
                                "What worked less well — practices to adjust", "Lo que funcionó menos bien — prácticas a ajustar"), { run: { size: 22 } }));
    out.push(P("• " + s.L(lang, "Surprises et apprentissages non anticipés",
                                "Surprises and unanticipated learnings", "Sorpresas y aprendizajes no anticipados"), { run: { size: 22 } }));
    out.push(P("• " + s.L(lang, "Recommandations pour la prochaine période ISR",
                                "Recommendations for the next ISR period", "Recomendaciones para el próximo periodo ISR"), { run: { size: 22 } }));
    out.push(P(s.L(lang, "(À compléter manuellement à partir du module Apprentissage MELR.)",
                        "(To be completed manually from the MELR Learning module.)", "(A completar manualmente a partir del módulo de Aprendizaje MELR.)"), { run: { italics: true, color: s.COLORS.MUTED } }));
    return out;
  }

  function buildDoc({ projects, indicators, scope, year, scopeLabel, orgName, lang }) {
    if (!_ok()) throw new Error("melrDonor shared module not loaded");
    const { Document, Footer, PageNumber, TextRun, Paragraph, AlignmentType } = window.docx;
    const s = _shared();
    const children = [];
    children.push(...buildCover({ orgName, scopeLabel, year, lang }));
    children.push(s.PageBreak());
    children.push(...buildPDO({ scopeLabel, lang }));
    children.push(...buildStatusSummary({ projects, year, lang }));
    children.push(...buildPdoIndicators({ indicators, year, lang }));
    children.push(...buildIntermediateIndicators({ indicators, year, lang }));
    children.push(...buildPerformanceRatings({ lang }));
    children.push(...buildRiskAssessment({ lang }));
    children.push(...buildLessons({ lang }));
    return new Document({
      creator: "MELR",
      title: "World Bank ISR — " + (scopeLabel || "Project") + " — FY" + year,
      description: "World Bank ISR auto-generated by MELR",
      styles: { default: { document: { run: { font: "Calibri", size: 22 } } } },
      sections: [{
        properties: { page: { margin: { top: 1200, right: 1200, bottom: 1200, left: 1200 }, size: { width: 12240, height: 15840 } } }, // US Letter
        footers: {
          default: new Footer({
            children: [new Paragraph({
              alignment: AlignmentType.CENTER,
              children: [
                new TextRun({ text: "World Bank ISR · " + (scopeLabel || "Project") + " · FY" + year + " · ", color: s.COLORS.MUTED, size: 18 }),
                new TextRun({ children: [PageNumber.CURRENT], color: s.COLORS.MUTED, size: 18 }),
                new TextRun({ text: " / ", color: s.COLORS.MUTED, size: 18 }),
                new TextRun({ children: [PageNumber.TOTAL_PAGES], color: s.COLORS.MUTED, size: 18 }),
              ],
            })],
          }),
        },
        children,
      }],
    });
  }

  async function exportWorldBankIsr(args) {
    args = args || {};
    if (!_ok()) { alert((args.lang || "fr") === "fr" ? "Module partagé indisponible." : "Shared module unavailable."); return; }
    const s = _shared();
    try {
      const doc = buildDoc({
        projects: args.projects || [],
        indicators: args.indicators || [],
        scope: args.scope || { mode: "all" },
        year: args.year || new Date().getFullYear(),
        scopeLabel: args.scopeLabel || s.L(args.lang, "Project", "Project"),
        orgName: args.orgName || "",
        lang: args.lang || "fr",
      });
      await s.saveDocx(doc, (args.filename || ("WorldBank-ISR-FY" + (args.year || new Date().getFullYear()))), args.lang);
    } catch (e) {
      console.error("[World Bank export]", e);
      alert(((args.lang || "fr") === "fr" ? "Erreur Banque mondiale : " : "World Bank error: ") + e.message);
    }
  }
  window.exportWorldBankIsr = exportWorldBankIsr;
})();
