/* global window */
// ============================================================================
// MELR · JICA — Project Design Matrix (PDM) + fiche de suivi
// ----------------------------------------------------------------------------
// Génère au format .docx les deux instruments de suivi de la JICA : la PDM
// (Project Design Matrix), matrice à quatre colonnes qui constitue le cadre
// logique de référence de l'agence, et la fiche de suivi des indicateurs.
//
// Particularité JICA, structurante pour ce module : la PDM distingue
// explicitement les INTRANTS de la partie japonaise et ceux de la partie
// bénéficiaire, et fait figurer les « conditions préalables » (pre-conditions)
// comme une ligne à part entière de la matrice. Aucun autre bailleur outillé
// dans MELR ne raisonne ainsi.
//
// Structure générée :
//   A. Fiche projet
//   B. Matrice de conception du projet (PDM) — 4 colonnes
//   C. Intrants (partie japonaise / partie bénéficiaire)
//   D. Suivi des indicateurs
//   E. Avancement et enjeux de mise en œuvre
//   F. Appréciation selon les critères du CAD
//   G. Leçons apprises
//
// ⚠️ Structure fondée sur le cadre PUBLIC de la JICA. Aucun gabarit officiel
// n'était disponible : libellés et numérotation à confronter au formulaire en
// vigueur avant transmission.
//
// Point d'entrée : window.exportJicaPdm({...})
// ============================================================================

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

  const JICA_RED = "B03A2E";
  const JICA_SLATE = "34495E";

  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 s = _shared();
    const L = s.L;
    const C = (text, o) => new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { after: (o && o.after) || 200, before: (o && o.before) || 0 },
      children: [new TextRun({ text, ...(o && o.run ? o.run : {}) })],
    });
    return [
      new Paragraph({ spacing: { before: 1200 }, children: [] }),
      C("JICA", { run: { bold: true, size: 56, color: JICA_RED }, after: 60 }),
      C("Japan International Cooperation Agency", { run: { italics: true, size: 22, color: s.COLORS.MUTED }, after: 500 }),
      C(L(lang, "Matrice de conception du projet (PDM) et fiche de suivi",
                "Project Design Matrix (PDM) and monitoring sheet",
                "Matriz de diseño del proyecto (PDM) y ficha de seguimiento"),
        { run: { bold: true, size: 28, color: JICA_RED }, after: 400 }),
      C(scopeLabel || L(lang, "Projet", "Project", "Proyecto"), { run: { bold: true, size: 28 } }),
      C(orgName || L(lang, "Organisme d'exécution", "Implementing agency", "Organismo ejecutor"),
        { run: { size: 24, color: s.COLORS.MUTED } }),
      C(L(lang, "Période de référence", "Reporting period", "Período de referencia") + " : " + year,
        { run: { size: 22 }, before: 700 }),
      C(L(lang, "Document généré le ", "Generated on ", "Documento generado el ") +
        new Date().toLocaleDateString(window.L("fr-FR", "en-US", "es-ES")),
        { run: { size: 20, italics: true, color: s.COLORS.MUTED }, after: 1500 }),
      C(L(lang, "Généré automatiquement par MELR · REFT Africa",
                "Auto-generated by MELR · REFT Africa",
                "Generado automáticamente por MELR · REFT Africa"),
        { run: { size: 18, color: s.COLORS.MUTED } }),
    ];
  }

  function buildProjectSheet({ projects, scopeLabel, orgName, year, lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, Spacer } = s;
    const p = (projects && projects[0]) || {};
    const out = [];
    out.push(H(1, s.L(lang, "A. Fiche projet", "A. Project sheet", "A. Ficha del proyecto"), { color: JICA_RED }));
    out.push(P(s.L(lang,
      "Cette fiche identifie le projet et sert d'en-tête de référence à la matrice de conception.",
      "This sheet identifies the project and serves as the reference header for the design matrix.",
      "Esta ficha identifica el proyecto y sirve de encabezado de referencia para la matriz de diseño.")));
    const row = (k, v) => Row([
      Cell(k, { width: 3200, bold: true, size: 20, fill: "FDF2F0" }),
      Cell(v || "—", { width: 6160, size: 20 }),
    ]);
    out.push(Tbl([
      row(s.L(lang, "Intitulé du projet", "Project title", "Título del proyecto"), scopeLabel),
      row(s.L(lang, "Organisme d'exécution", "Implementing agency", "Organismo ejecutor"), orgName),
      row(s.L(lang, "Code / référence", "Code / reference", "Código / referencia"), p.code),
      row(s.L(lang, "Secteur", "Sector", "Sector"), p.sector),
      row(s.L(lang, "Zone cible", "Target area", "Zona objetivo"), p.country),
      row(s.L(lang, "Période de référence", "Reporting period", "Período de referencia"), String(year)),
    ], { columnWidths: [3200, 6160] }));
    out.push(Spacer());
    return out;
  }

  // ── B. PDM — la matrice à 4 colonnes ───────────────────────────────────
  function buildPdm({ indicators, year, lang, periods }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, Spacer } = s;
    const out = [];
    out.push(H(1, s.L(lang, "B. Matrice de conception du projet (PDM)",
                            "B. Project Design Matrix (PDM)",
                            "B. Matriz de diseño del proyecto (PDM)"), { color: JICA_RED }));
    out.push(P(s.L(lang,
      "La PDM articule sur quatre colonnes le résumé narratif, les indicateurs objectivement vérifiables, leurs moyens de vérification et les hypothèses importantes. Les indicateurs proviennent de MELR ; les moyens de vérification et les hypothèses restent à renseigner par l'équipe de projet, ces informations n'étant pas portées par le système de suivi.",
      "The PDM sets out, in four columns, the narrative summary, objectively verifiable indicators, their means of verification and important assumptions. Indicators come from MELR; means of verification and assumptions remain to be completed by the project team, as this information is not held by the monitoring system.",
      "La PDM articula en cuatro columnas el resumen narrativo, los indicadores objetivamente verificables, sus medios de verificación y los supuestos importantes. Los indicadores provienen de MELR; los medios de verificación y los supuestos deben completarse por el equipo del proyecto.")));

    const bag = s.groupByLevel(indicators);
    const nameOf = (i) => (lang === "fr" ? (i.name_fr || i.name) : (i.name_en || i.name)) || "—";
    const ovi = (list) => (list.length
      ? list.map((i) => "• " + (i.id || i.code || "") + " " + nameOf(i) +
          (i.target != null ? " — " + s.L(lang, "cible", "target", "meta") + " " + s.fmtNum(i.target, i.unit) : "")).join("\n")
      : "—");

    const th = (t, w) => Cell(t, { width: w, bold: true, fill: JICA_RED, color: "FFFFFF", size: 17 });
    const rows = [Row([
      th(s.L(lang, "Résumé narratif", "Narrative summary", "Resumen narrativo"), 2000),
      th(s.L(lang, "Indicateurs objectivement vérifiables", "Objectively verifiable indicators", "Indicadores objetivamente verificables"), 3600),
      th(s.L(lang, "Moyens de vérification", "Means of verification", "Medios de verificación"), 1900),
      th(s.L(lang, "Hypothèses importantes", "Important assumptions", "Supuestos importantes"), 1860),
    ])];
    const line = (label, list) => Row([
      Cell(label, { width: 2000, bold: true, size: 18, fill: "FDF2F0" }),
      Cell(ovi(list), { width: 3600, size: 17 }),
      Cell("", { width: 1900 }),
      Cell("", { width: 1860 }),
    ]);
    rows.push(line(s.L(lang, "But global", "Overall goal", "Meta global"), bag.Impact));
    rows.push(line(s.L(lang, "Objectif du projet", "Project purpose", "Objetivo del proyecto"), bag.Outcome));
    rows.push(line(s.L(lang, "Produits", "Outputs", "Productos"), bag.Output));
    rows.push(Row([
      Cell(s.L(lang, "Activités", "Activities", "Actividades"), { width: 2000, bold: true, size: 18, fill: "FDF2F0" }),
      Cell("", { width: 3600 }),
      Cell("", { width: 1900 }),
      Cell("", { width: 1860 }),
    ]));
    // Ligne « conditions préalables » : propre à la PDM.
    rows.push(Row([
      Cell(s.L(lang, "Conditions préalables", "Pre-conditions", "Condiciones previas"),
        { width: 2000, bold: true, size: 18, fill: "F4F6F7" }),
      Cell("", { width: 7360, colSpan: 3, fill: "F4F6F7" }),
    ]));
    out.push(Tbl(rows, { columnWidths: [2000, 3600, 1900, 1860] }));
    out.push(Spacer());
    return out;
  }

  // ── C. Intrants des deux parties ───────────────────────────────────────
  function buildInputs({ lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, Spacer } = s;
    const out = [];
    out.push(H(1, s.L(lang, "C. Intrants", "C. Inputs", "C. Insumos"), { color: JICA_RED }));
    out.push(P(s.L(lang,
      "La PDM distingue les apports de la partie japonaise de ceux de la partie bénéficiaire. Cette symétrie engage les deux parties et conditionne l'appréciation de l'efficience.",
      "The PDM distinguishes inputs from the Japanese side from those of the recipient side. This symmetry commits both parties and underpins the efficiency assessment.",
      "La PDM distingue los aportes de la parte japonesa de los de la parte beneficiaria. Esta simetría compromete a ambas partes y sustenta la apreciación de la eficiencia.")));
    const th = (t, w) => Cell(t, { width: w, bold: true, fill: JICA_SLATE, color: "FFFFFF", size: 18 });
    const cat = (l) => [
      s.L(lang, "Experts / personnel", "Experts / personnel", "Expertos / personal"),
      s.L(lang, "Équipements et matériels", "Equipment and materials", "Equipos y materiales"),
      s.L(lang, "Formation et bourses", "Training and fellowships", "Capacitación y becas"),
      s.L(lang, "Coûts opérationnels locaux", "Local operational costs", "Costos operativos locales"),
    ];
    const rows = [Row([
      th(s.L(lang, "Nature de l'intrant", "Input type", "Tipo de insumo"), 3400),
      th(s.L(lang, "Partie japonaise", "Japanese side", "Parte japonesa"), 2980),
      th(s.L(lang, "Partie bénéficiaire", "Recipient side", "Parte beneficiaria"), 2980),
    ])];
    cat(lang).forEach((c) => rows.push(Row([
      Cell(c, { width: 3400, bold: true, size: 18 }),
      Cell("", { width: 2980 }),
      Cell("", { width: 2980 }),
    ])));
    out.push(Tbl(rows, { columnWidths: [3400, 2980, 2980] }));
    out.push(P(s.L(lang, "(À compléter par l'équipe de projet.)", "(To be completed by the project team.)", "(A completar por el equipo del proyecto.)"),
      { run: { italics: true, color: s.COLORS.MUTED, size: 18 } }));
    out.push(Spacer());
    return out;
  }

  // ── D. Suivi des indicateurs ───────────────────────────────────────────
  function buildMonitoring({ indicators, year, lang, periods }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, Spacer } = s;
    const out = [];
    out.push(H(1, s.L(lang, "D. Suivi des indicateurs", "D. Indicator monitoring", "D. Seguimiento de indicadores"), { color: JICA_RED }));
    out.push(P(s.L(lang,
      "Le tableau reprend chaque indicateur objectivement vérifiable de la PDM, avec sa référence, ses cibles et ses valeurs atteintes sur les périodes suivies.",
      "The table restates each objectively verifiable indicator of the PDM, with its baseline, targets and actual values over the tracked periods.",
      "El cuadro retoma cada indicador objetivamente verificable de la PDM, con su línea de base, metas y valores alcanzados en los períodos seguidos.")));
    const list = indicators || [];
    if (!list.length) {
      out.push(P(s.L(lang, "Aucun indicateur n'est rattaché au périmètre sélectionné.",
                           "No indicator is attached to the selected scope.",
                           "Ningún indicador está vinculado al alcance seleccionado."),
        { run: { italics: true, color: s.COLORS.MUTED } }));
      return out;
    }
    const Y = periods;
    const perf0 = s.computePerformance(list[0], year, Y);
    const header = [
      Cell(s.L(lang, "Code", "Code", "Código"), { width: 800, bold: true, fill: JICA_RED, color: "FFFFFF", size: 18 }),
      Cell(s.L(lang, "Indicateur", "Indicator", "Indicador"), { width: 2600, bold: true, fill: JICA_RED, color: "FFFFFF", size: 18 }),
      Cell(s.L(lang, "Unité", "Unit", "Unidad"), { width: 600, bold: true, fill: JICA_RED, color: "FFFFFF", size: 18 }),
      Cell(s.L(lang, "Réf.", "Base.", "Ref."), { width: 800, bold: true, fill: JICA_RED, color: "FFFFFF", size: 18 }),
    ];
    for (let i = 0; i < Y; i++) {
      header.push(Cell(perf0.years[i] + " " + s.L(lang, "cible", "target", "meta"), { width: 800, bold: true, fill: JICA_RED, color: "FFFFFF", size: 16 }));
      header.push(Cell(perf0.years[i] + " " + s.L(lang, "réel", "actual", "real"), { width: 800, bold: true, fill: JICA_RED, color: "FFFFFF", size: 16 }));
      header.push(Cell("%", { width: 520, bold: true, fill: JICA_RED, color: "FFFFFF", size: 16 }));
    }
    const rows = [Row(header)];
    list.forEach((ind) => rows.push(s.iptRow(ind, s.computePerformance(ind, year, Y), lang, Y)));
    out.push(Tbl(rows));
    out.push(Spacer());
    return out;
  }

  // ── E. Avancement et enjeux ────────────────────────────────────────────
  function buildProgress({ lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, Spacer } = s;
    const out = [];
    out.push(H(1, s.L(lang, "E. Avancement et enjeux de mise en œuvre",
                            "E. Implementation progress and issues",
                            "E. Avance y cuestiones de ejecución"), { color: JICA_RED }));
    out.push(P(s.L(lang,
      "Cette section consigne l'état d'avancement des activités et les difficultés rencontrées, avec les mesures arrêtées entre les deux parties.",
      "This section records the progress of activities and the difficulties encountered, along with the measures agreed between the two parties.",
      "Esta sección registra el avance de las actividades y las dificultades encontradas, junto con las medidas acordadas entre ambas partes.")));
    const th = (t, w) => Cell(t, { width: w, bold: true, fill: JICA_SLATE, color: "FFFFFF", size: 18 });
    out.push(Tbl([
      Row([
        th(s.L(lang, "Enjeu identifié", "Issue identified", "Cuestión identificada"), 3400),
        th(s.L(lang, "Mesure convenue", "Agreed measure", "Medida acordada"), 3400),
        th(s.L(lang, "Partie responsable", "Responsible party", "Parte responsable"), 2560),
      ]),
      Row([Cell("", { width: 3400 }), Cell("", { width: 3400 }), Cell("", { width: 2560 })]),
      Row([Cell("", { width: 3400 }), Cell("", { width: 3400 }), Cell("", { width: 2560 })]),
    ], { columnWidths: [3400, 3400, 2560] }));
    out.push(Spacer());
    return out;
  }

  // ── F. Critères du CAD ─────────────────────────────────────────────────
  function buildDac({ lang }) {
    const s = _shared();
    const { H, P, Cell, Row, Tbl, Spacer } = s;
    const out = [];
    out.push(H(1, s.L(lang, "F. Appréciation selon les critères du CAD",
                            "F. Assessment against DAC criteria",
                            "F. Apreciación según los criterios del CAD"), { color: JICA_RED }));
    out.push(P(s.L(lang,
      "La JICA évalue ses opérations au regard des critères du Comité d'aide au développement de l'OCDE. L'appréciation ci-dessous prépare l'évaluation ex post.",
      "JICA assesses its operations against the OECD Development Assistance Committee criteria. The assessment below prepares the ex-post evaluation.",
      "JICA evalúa sus operaciones con arreglo a los criterios del Comité de Ayuda al Desarrollo de la OCDE. La apreciación siguiente prepara la evaluación ex post.")));
    const th = (t, w) => Cell(t, { width: w, bold: true, fill: JICA_RED, color: "FFFFFF", size: 18 });
    const crit = [
      s.L(lang, "Pertinence", "Relevance", "Pertinencia"),
      s.L(lang, "Cohérence", "Coherence", "Coherencia"),
      s.L(lang, "Efficacité", "Effectiveness", "Eficacia"),
      s.L(lang, "Efficience", "Efficiency", "Eficiencia"),
      s.L(lang, "Impact", "Impact", "Impacto"),
      s.L(lang, "Durabilité", "Sustainability", "Sostenibilidad"),
    ];
    const rows = [Row([
      th(s.L(lang, "Critère", "Criterion", "Criterio"), 2600),
      th(s.L(lang, "Appréciation", "Assessment", "Apreciación"), 5200),
      th(s.L(lang, "Note", "Rating", "Calificación"), 1560),
    ])];
    crit.forEach((c) => rows.push(Row([
      Cell(c, { width: 2600, bold: true, size: 18 }),
      Cell("", { width: 5200 }),
      Cell("", { width: 1560 }),
    ])));
    out.push(Tbl(rows, { columnWidths: [2600, 5200, 1560] }));
    out.push(Spacer());
    return out;
  }

  function buildLessons({ lang }) {
    const s = _shared();
    const { H, P } = s;
    const out = [];
    out.push(H(1, s.L(lang, "G. Leçons apprises", "G. Lessons learned", "G. Lecciones aprendidas"), { color: JICA_RED }));
    out.push(P(s.L(lang,
      "Les enseignements consignés ici alimentent l'évaluation ex post et la conception des coopérations suivantes.",
      "The lessons recorded here feed the ex-post evaluation and the design of subsequent cooperation.",
      "Las lecciones registradas aquí alimentan la evaluación ex post y el diseño de cooperaciones posteriores.")));
    [
      s.L(lang, "Facteurs ayant favorisé l'atteinte de l'objectif du projet", "Factors that helped achieve the project purpose", "Factores que favorecieron el logro del objetivo"),
      s.L(lang, "Facteurs ayant entravé la mise en œuvre", "Factors that hindered implementation", "Factores que obstaculizaron la ejecución"),
      s.L(lang, "Recommandations aux deux parties", "Recommendations to both parties", "Recomendaciones a ambas partes"),
    ].forEach((t) => out.push(P("• " + t, { run: { size: 22 } })));
    out.push(P(s.L(lang, "(À compléter à partir du module Apprentissage de MELR.)",
                         "(To be completed from the MELR Learning module.)",
                         "(A completar a partir del módulo de Aprendizaje de MELR.)"),
      { run: { italics: true, color: s.COLORS.MUTED } }));
    return out;
  }

  function buildDoc(a) {
    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(a));
    children.push(s.PageBreak());
    children.push(...buildProjectSheet(a));
    children.push(...buildPdm(a));
    children.push(...buildInputs(a));
    children.push(...buildMonitoring(a));
    children.push(...buildProgress(a));
    children.push(...buildDac(a));
    children.push(...buildLessons(a));
    return new Document({
      creator: "MELR",
      title: "JICA PDM — " + (a.scopeLabel || "Project") + " — " + a.year,
      description: "JICA Project Design Matrix auto-generated by MELR",
      styles: { default: { document: { run: { font: "Calibri", size: 22 } } } },
      sections: [{
        properties: { page: { margin: { top: 1200, right: 1200, bottom: 1200, left: 1200 } } },
        footers: {
          default: new Footer({
            children: [new Paragraph({
              alignment: AlignmentType.CENTER,
              children: [
                new TextRun({ text: "JICA · PDM · " + (a.scopeLabel || "Projet") + " · " + a.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 exportJicaPdm(args) {
    args = args || {};
    if (!_ok()) { alert((args.lang || "fr") === "fr" ? "Module partagé indisponible." : "Shared module unavailable."); return; }
    const s = _shared();
    try {
      const year = args.year || new Date().getFullYear();
      const doc = buildDoc({
        projects: args.projects || [],
        indicators: args.indicators || [],
        year,
        scopeLabel: args.scopeLabel || s.L(args.lang, "Projet", "Project", "Proyecto"),
        orgName: args.orgName || "",
        lang: args.lang || "fr",
        periods: args.periods || 3,
      });
      await s.saveDocx(doc, (args.filename || ("JICA-PDM-" + year)), args.lang);
    } catch (e) {
      console.error("[JICA export]", e);
      alert(((args.lang || "fr") === "fr" ? "Erreur JICA : " : "JICA error: ") + e.message);
    }
  }
  window.exportJicaPdm = exportJicaPdm;
})();
