/* global window, XLSX */
// ============================================================================
// MELR · ADA (Austrian Development Agency) — annexe budgétaire (Excel)
// ----------------------------------------------------------------------------
// Phase 2a du chantier ADA : génère l'annexe financière au format ADA
// « LR Budget » (cf. Updates/ADA-WHG-LED/lr-budget-template-ada-july-2025.xlsx)
// en .xlsx via SheetJS (window.XLSX, déjà chargé pour les autres exports Excel).
//
// 3 feuilles reproduisant le template ADA :
//   1. Guide  — notes (pré-rempli vs à compléter, devise, vouchers).
//   2. Budget — Catégorie → Ligne, colonnes ADA (Unité / Nb / Coût unitaire /
//      Total) ENRICHIES d'un volet réalisé (Budget / Engagé / Décaissé / Solde
//      / Exéc. %), PRÉ-REMPLIES depuis la table MELR budget_lines
//      (budget, committed, disbursed par ligne). Sous-totaux par catégorie +
//      total général.
//   3. Sources de financement — Bénéficiaire / Subvention ADA / Autres
//      (cofinancement) ; total pré-rempli, répartition à compléter.
//
// PORTÉE (option a — « Excel pré-rempli à compléter ») : ce qui est chiffré
// dans MELR est injecté ; le détail unitaire et la répartition des sources
// restent à compléter. Les pièces justificatives (vouchers) exigées par ADA
// sont à joindre séparément — MELR ne stocke pas encore les vouchers (→ option
// b, cf. note de chantier).
//
// Point d'entrée : window.exportAdaBudget({ budgetLines, scopeLabel, year,
//   orgName, lang, filename }).
// ============================================================================

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

  function L(lang, fr, en, es) { const l = lang || "fr"; return l === "es" ? (es != null ? es : en) : l === "fr" ? fr : en; }
  function num(n) { const x = Number(n); return isFinite(x) ? x : 0; }

  function exportAdaBudget(args) {
    args = args || {};
    const lang = args.lang || "fr";
    if (typeof XLSX === "undefined" || !XLSX.utils) {
      alert(L(lang, "La librairie Excel (XLSX) n'est pas disponible (CDN bloqué ?).", "The Excel library (XLSX) is not available (CDN blocked?).", "La biblioteca Excel (XLSX) no está disponible (¿CDN bloqueado?)."));
      return;
    }
    const lines = (args.budgetLines || []).slice().sort((a, b) => (a.position || 0) - (b.position || 0));
    const scopeLabel = args.scopeLabel || L(lang, "Intervention", "Intervention", "Intervención");
    const year = args.year || new Date().getFullYear();
    const ccy = (lines.find((l) => l.currency) || {}).currency || "EUR";
    const wb = XLSX.utils.book_new();

    // ── Feuille 1 : Guide / notes ──────────────────────────────────────────
    const guide = [
      [L(lang, "Rapport financier ADA — Budget vs réalisé", "ADA financial report — Budget vs actual", "Informe financiero ADA — Presupuesto vs ejecutado")],
      [],
      [L(lang, "Intervention :", "Intervention:", "Intervención:"), scopeLabel],
      [L(lang, "Exercice :", "Fiscal year:", "Ejercicio:"), year],
      [L(lang, "Devise :", "Currency:", "Moneda:"), ccy],
      [L(lang, "Généré par :", "Generated by:", "Generado por:"), "MELR · REFT Africa"],
      [],
      [L(lang, "Notes", "Notes", "Notas")],
      [L(lang, "• Reproduit la structure du template ADA « LR Budget » (Catégorie → Ligne + Sources de financement).", "• Reproduces the ADA \"LR Budget\" template structure (Category → Line + Sources of funding).", "• Reproduce la estructura de la plantilla ADA «LR Budget» (Categoría → Línea + Fuentes de financiación).")],
      [L(lang, "• PRÉ-REMPLI depuis MELR : Budget, Engagé, Décaissé par ligne (table budget_lines).", "• PRE-FILLED from MELR: Budget, Committed, Disbursed per line (budget_lines table).", "• PRELLENADO desde MELR: Presupuesto, Comprometido, Desembolsado por línea (tabla budget_lines).")],
      [L(lang, "• À COMPLÉTER : Unité / Nb d'unités / Coût unitaire, et la répartition des sources de financement.", "• TO COMPLETE: Unit / # of units / Unit cost, and the funding-source split.", "• A COMPLETAR: Unidad / N.º de unidades / Costo unitario, y el desglose de fuentes de financiación.")],
      [L(lang, "• Les pièces justificatives (vouchers) exigées par ADA sont à joindre séparément (MELR ne les stocke pas encore).", "• The vouchers required by ADA must be attached separately (MELR does not store them yet).", "• Los comprobantes exigidos por ADA deben adjuntarse por separado (MELR aún no los almacena).")],
      [L(lang, "• Si la devise n'est pas l'EUR, convertir au taux de la date de reporting (ADA reporte en EUR).", "• If the currency is not EUR, convert at the reporting-date rate (ADA reports in EUR).", "• Si la moneda no es EUR, convertir al tipo de la fecha de informe (ADA informa en EUR).")],
    ];
    const wsGuide = XLSX.utils.aoa_to_sheet(guide);
    wsGuide["!cols"] = [{ wch: 30 }, { wch: 78 }];
    XLSX.utils.book_append_sheet(wb, wsGuide, L(lang, "Guide", "Guide", "Guía"));

    // ── Feuille 2 : Budget (vs réalisé) ────────────────────────────────────
    const hdr = [
      L(lang, "Catégorie", "Category", "Categoría"),
      L(lang, "Ligne budgétaire", "Budget line", "Línea presupuestaria"),
      L(lang, "Description", "Cost description", "Descripción"),
      L(lang, "Unité", "Unit", "Unidad"),
      L(lang, "Nb unités", "# units", "N.º unidades"),
      L(lang, "Coût/unité", "Cost/unit", "Costo/unidad"),
      L(lang, "Budget", "Budget", "Presupuesto") + " (" + ccy + ")",
      L(lang, "Engagé", "Committed", "Comprometido") + " (" + ccy + ")",
      L(lang, "Décaissé", "Disbursed", "Desembolsado") + " (" + ccy + ")",
      L(lang, "Solde", "Balance", "Saldo") + " (" + ccy + ")",
      L(lang, "Exéc. %", "Exec. %", "Ejec. %"),
    ];
    const aoa = [
      [L(lang, "Budget & rapport financier — ", "Budget & financial report — ", "Presupuesto e informe financiero — ") + scopeLabel + " · " + year + " (" + ccy + ")"],
      [],
      hdr,
    ];
    const cats = [], byCat = {};
    lines.forEach((l) => {
      const c = l.category || L(lang, "(Sans catégorie)", "(Uncategorized)", "(Sin categoría)");
      if (!byCat[c]) { byCat[c] = []; cats.push(c); }
      byCat[c].push(l);
    });
    let gB = 0, gC = 0, gD = 0;
    cats.forEach((c) => {
      aoa.push([c]);
      let sB = 0, sC = 0, sD = 0;
      byCat[c].forEach((l) => {
        const b = num(l.budget), co = num(l.committed), di = num(l.disbursed);
        sB += b; sC += co; sD += di;
        aoa.push(["", l.label || "", "", "", "", "", b, co, di, b - di, b ? Math.round((di / b) * 100) : ""]);
      });
      aoa.push([L(lang, "Sous-total", "Subtotal", "Subtotal") + " — " + c, "", "", "", "", "", sB, sC, sD, sB - sD, sB ? Math.round((sD / sB) * 100) : ""]);
      gB += sB; gC += sC; gD += sD;
    });
    if (!lines.length) aoa.push([L(lang, "Aucune ligne budgétaire dans MELR pour ce projet — à saisir dans l'onglet Budget du projet.", "No budget lines in MELR for this project — enter them in the project's Budget tab.", "Sin líneas presupuestarias en MELR para este proyecto — introdúzcalas en la pestaña Presupuesto del proyecto.")]);
    aoa.push([]);
    aoa.push([L(lang, "TOTAL", "TOTAL", "TOTAL"), "", "", "", "", "", gB, gC, gD, gB - gD, gB ? Math.round((gD / gB) * 100) : ""]);
    const wsB = XLSX.utils.aoa_to_sheet(aoa);
    wsB["!cols"] = [{ wch: 24 }, { wch: 30 }, { wch: 24 }, { wch: 8 }, { wch: 9 }, { wch: 11 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 9 }];
    XLSX.utils.book_append_sheet(wb, wsB, L(lang, "Budget", "Budget", "Presupuesto"));

    // ── Feuille 3 : Sources de financement ─────────────────────────────────
    const src = [
      [L(lang, "Sources de financement", "Sources of funding", "Fuentes de financiación") + " — " + scopeLabel],
      [],
      [L(lang, "Source", "Source", "Fuente"), L(lang, "Montant", "Amount", "Importe") + " (" + ccy + ")", "%"],
      [L(lang, "Contribution du bénéficiaire", "Contribution of grant applicant", "Contribución del beneficiario"), "", ""],
      [L(lang, "Subvention ADA", "ADA Grant", "Subvención ADA"), "", ""],
      [L(lang, "Autres contributions (cofinancement)", "Other contributions (co-financing)", "Otras contribuciones (cofinanciación)"), "", ""],
      [L(lang, "TOTAL", "TOTAL", "TOTAL"), gB, ""],
      [],
      [L(lang, "Total pré-rempli = somme des budgets de lignes. Répartition par source à compléter.", "Pre-filled total = sum of line budgets. Source split to complete.", "Total prellenado = suma de los presupuestos de línea. Desglose por fuente a completar.")],
    ];
    const wsS = XLSX.utils.aoa_to_sheet(src);
    wsS["!cols"] = [{ wch: 44 }, { wch: 20 }, { wch: 8 }];
    XLSX.utils.book_append_sheet(wb, wsS, L(lang, "Sources de financement", "Sources of funding", "Fuentes"));

    const fname = (args.filename || ("ADA-Budget-" + year)) + ".xlsx";
    try { XLSX.writeFile(wb, fname); }
    catch (e) { console.error("[ADA budget]", e); alert(L(lang, "Erreur export budget ADA : ", "ADA budget export error: ", "Error de exportación presupuesto ADA: ") + e.message); }
  }

  window.exportAdaBudget = exportAdaBudget;
})();
