/* global React, Icon, window */
// ============================================================================
// MELR · Étiquetage budgétaire climat — tableau de bord (window.ClimTagScreen).
// Moteur : public/climtag-calc.jsx (window.CLIMTAG). Étiquette les lignes
// budgétaires (Rio Markers atténuation/adaptation + CDN, coefficients
// configurables) et agrège les dépenses pertinentes climat. Alimente
// PEFA-Climat CRPFM-2 (budgété) et CRPFM-14 (exécuté).
// ============================================================================

(function () {
  const { useState, useEffect } = React;
  const sec = (c, extra) => (window.MelrSection && window.MelrSection.colors && window.MelrSection.colors[c] ? window.MelrSection.style(c, extra) : { marginBottom: 14, ...(extra || {}) });
  const secT = (c) => (window.MelrSection && window.MelrSection.colors && window.MelrSection.colors[c] ? window.MelrSection.title(c) : { fontSize: 13, fontWeight: 700, marginBottom: 8 });
  const fmt = (v, d) => (v == null || Number.isNaN(Number(v)) ? "—" : Number(v).toFixed(d == null ? 0 : d));
  const pct = (v) => (v == null ? "—" : (100 * v).toFixed(1) + " %");

  function Kpi({ label, value, hint }) {
    return (
      <div style={{ background: "var(--bg-elev)", border: "1px solid var(--line)", borderRadius: 8, padding: "9px 12px", minWidth: 120, flex: 1 }}>
        <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".3px", color: "var(--muted)", fontWeight: 600 }}>{label}</div>
        <div style={{ fontSize: 19, fontWeight: 800, marginTop: 2 }}>{value}</div>
        {hint && <div style={{ fontSize: 9.5, color: "var(--muted)" }}>{hint}</div>}
      </div>
    );
  }
  const cellInput = { width: "100%", fontSize: 11.5, padding: "2px 4px", textAlign: "right", border: "1px solid var(--line)", borderRadius: 4, background: "var(--bg, white)", color: "var(--text)" };
  const cellSel = { ...cellInput, textAlign: "left" };
  const BLANK = { label: "", amount: null, executed: null, mitig: 0, adapt: 0, ndc: false, sector: "" };

  function ClimTagScreen({ lang, effectiveOrgId, isSuperAdmin, hasPerm }) {
    const L = (fr, en) => (lang === "fr" ? fr : en);
    const T = window.CLIMTAG;
    const canManage = isSuperAdmin
      || (typeof hasPerm === "function" && (hasPerm("users.manage") || hasPerm("evaluations.manage")));
    const mLabel = (m) => { const x = T.MARKERS.find((k) => k.code === m); return x ? (lang === "fr" ? x.fr : x.en) : m; };

    const [year, setYear] = useState(() => { try { return localStorage.getItem("melr.climtag.year") || "2026"; } catch (_) { return "2026"; } });
    useEffect(() => { try { localStorage.setItem("melr.climtag.year", year); } catch (_) {} }, [year]);

    const [profile, setProfile] = useState(null);
    const [dirty, setDirty] = useState(false);
    const [saveBusy, setSaveBusy] = useState(false);
    const [saveMsg, setSaveMsg] = useState(null);
    useEffect(() => {
      let cancelled = false;
      setProfile(null); setDirty(false); setSaveMsg(null);
      if (!effectiveOrgId || !year) return;
      window.melr.fetchClimTagProfile(effectiveOrgId, year.trim())
        .then((p) => { if (!cancelled) setProfile(p || { lines: [], weights: { ...T.DEFAULT_WEIGHTS } }); })
        .catch(() => { if (!cancelled) setProfile({ lines: [], weights: { ...T.DEFAULT_WEIGHTS } }); });
      return () => { cancelled = true; };
    }, [effectiveOrgId, year]);

    const lines = (profile && profile.lines) || [];
    const weights = (profile && profile.weights) || T.DEFAULT_WEIGHTS;
    const setLines = (ls) => { setProfile({ ...(profile || {}), lines: ls }); setDirty(true); };
    const setWeight = (m, v) => { setProfile({ ...(profile || {}), weights: { ...weights, [m]: v } }); setDirty(true); };
    const addRow = () => setLines([...lines, { ...BLANK }]);
    const removeRow = (i) => setLines(lines.filter((_, j) => j !== i));
    const updateRow = (i, k, v) => setLines(lines.map((r, j) => (j === i ? { ...r, [k]: v } : r)));
    const numv = (e) => (e.target.value === "" ? null : Number(e.target.value));

    const agg = profile ? T.aggregate(lines, weights) : null;

    const saveProfile = async () => {
      setSaveBusy(true); setSaveMsg(null);
      try {
        await window.melr.saveClimTagProfile(effectiveOrgId, year.trim(), {
          lines: lines, weights: weights, notes: profile.notes || null,
        });
        setDirty(false); setSaveMsg(L("Enregistré.", "Saved."));
      } catch (e) { setSaveMsg(L("Erreur : ", "Error: ") + e.message); }
      finally { setSaveBusy(false); }
    };

    const th = { fontSize: 10, fontWeight: 700, color: "var(--muted)", padding: "2px 4px", textAlign: "left", whiteSpace: "nowrap" };
    const markerSel = (i, k) => (
      <select style={cellSel} disabled={!canManage} value={lines[i][k]} onChange={(e) => updateRow(i, k, Number(e.target.value))}>
        {T.MARKERS.map((m) => <option key={m.code} value={m.code}>{m.code} · {mLabel(m.code)}</option>)}
      </select>
    );

    return (
      <div className="page">
        <div className="page-header">
          <div className="page-eyebrow">{L("ÉVALUATIONS · BUDGET VERT", "EVALUATIONS · GREEN BUDGET")}</div>
          <h1 className="page-title">{L("Étiquetage budgétaire climat", "Climate budget tagging")}</h1>
          <div className="page-sub">{L("Rio Markers (atténuation/adaptation) + CDN, coefficients configurables. Alimente PEFA-Climat CRPFM-2 et CRPFM-14.", "Rio Markers (mitigation/adaptation) + NDC, configurable coefficients. Feeds PEFA-Climate CRPFM-2 and CRPFM-14.")}</div>
        </div>

        {/* Année + coefficients + enregistrement */}
        <div style={sec("purple")}>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap", alignItems: "flex-end" }}>
            <div>
              <label style={{ fontSize: 10.5, fontWeight: 600, display: "block", marginBottom: 2 }}>{L("Exercice budgétaire", "Fiscal year")}</label>
              <input className="input" value={year} disabled={!canManage} onChange={(e) => setYear(e.target.value)} style={{ width: 90, fontSize: 12 }} />
            </div>
            <div>
              <label style={{ fontSize: 10.5, fontWeight: 600, display: "block", marginBottom: 2 }}>{L("Coef. « Significatif » (%)", "'Significant' coef. (%)")}</label>
              <input type="number" step="5" className="input" disabled={!canManage} value={weights[1] == null ? "" : Math.round(weights[1] * 100)}
                onChange={(e) => setWeight(1, e.target.value === "" ? 0 : Number(e.target.value) / 100)} style={{ width: 90, fontSize: 12, textAlign: "right" }} />
            </div>
            <div>
              <label style={{ fontSize: 10.5, fontWeight: 600, display: "block", marginBottom: 2 }}>{L("Coef. « Principal » (%)", "'Principal' coef. (%)")}</label>
              <input type="number" step="5" className="input" disabled={!canManage} value={weights[2] == null ? "" : Math.round(weights[2] * 100)}
                onChange={(e) => setWeight(2, e.target.value === "" ? 0 : Number(e.target.value) / 100)} style={{ width: 90, fontSize: 12, textAlign: "right" }} />
            </div>
            {canManage && (
              <button className="btn sm primary" disabled={saveBusy || !dirty} onClick={saveProfile}>
                {saveBusy ? "…" : <><Icon.save /> {L("Enregistrer", "Save")}</>}
              </button>
            )}
            {saveMsg && <span className="text-faint" style={{ fontSize: 11.5 }}>{saveMsg}</span>}
          </div>
          <div className="text-faint" style={{ fontSize: 10.5, marginTop: 6 }}>
            {L("Aucune norme officielle : coefficients « OCDE-like » par défaut (significatif 40 %, principal 100 %) — à ajuster selon votre convention.",
               "No official standard: default 'OECD-like' coefficients (significant 40%, principal 100%) — adjust to your convention.")}
          </div>
        </div>

        {/* Lignes budgétaires étiquetées */}
        <div style={sec("amber")}>
          <div style={secT("amber")}>🏷️ {L("Lignes budgétaires étiquetées", "Tagged budget lines")}</div>
          <div style={{ overflowX: "auto" }}>
            <table style={{ borderCollapse: "collapse", fontSize: 11.5, minWidth: 760 }}>
              <thead>
                <tr>
                  <th style={th}>{L("Ligne / programme", "Line / programme")}</th>
                  <th style={th}>{L("Budget", "Budget")}</th>
                  <th style={th}>{L("Exécuté", "Executed")}</th>
                  <th style={th}>{L("Atténuation", "Mitigation")}</th>
                  <th style={th}>{L("Adaptation", "Adaptation")}</th>
                  <th style={th}>{L("CDN", "NDC")}</th>
                  <th style={th}></th>
                </tr>
              </thead>
              <tbody>
                {lines.map((r, i) => (
                  <tr key={i}>
                    <td style={{ padding: "1px 3px" }}><input style={{ ...cellSel, width: 170 }} disabled={!canManage} value={r.label || ""} onChange={(e) => updateRow(i, "label", e.target.value)} /></td>
                    <td style={{ padding: "1px 3px" }}><input type="number" style={cellInput} disabled={!canManage} value={r.amount == null ? "" : r.amount} onChange={(e) => updateRow(i, "amount", numv(e))} /></td>
                    <td style={{ padding: "1px 3px" }}><input type="number" style={cellInput} disabled={!canManage} value={r.executed == null ? "" : r.executed} onChange={(e) => updateRow(i, "executed", numv(e))} /></td>
                    <td style={{ padding: "1px 3px", minWidth: 120 }}>{markerSel(i, "mitig")}</td>
                    <td style={{ padding: "1px 3px", minWidth: 120 }}>{markerSel(i, "adapt")}</td>
                    <td style={{ padding: "1px 3px", textAlign: "center" }}><input type="checkbox" disabled={!canManage} checked={!!r.ndc} onChange={(e) => updateRow(i, "ndc", e.target.checked)} /></td>
                    <td style={{ padding: "1px 3px" }}>{canManage && <button className="btn xs ghost" onClick={() => removeRow(i)} title={L("Retirer", "Remove")}>×</button>}</td>
                  </tr>
                ))}
                {!lines.length && <tr><td colSpan={7} className="text-faint" style={{ padding: 8, fontSize: 11.5 }}>{L("Aucune ligne. Ajoutez des lignes budgétaires à étiqueter.", "No line. Add budget lines to tag.")}</td></tr>}
              </tbody>
            </table>
          </div>
          {canManage && <button className="btn xs" style={{ marginTop: 6 }} onClick={addRow}><Icon.plus /> {L("Ajouter une ligne", "Add line")}</button>}
        </div>

        {/* Agrégation */}
        <div style={sec("blue")}>
          <div style={secT("blue")}>📊 {L("Dépenses pertinentes climat", "Climate-relevant expenditure")}</div>
          {agg ? (
            <>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 8 }}>
                <Kpi label={L("Pertinent climat", "Climate-relevant")} value={fmt(agg.climateRelevant, 0)} hint={pct(agg.shareClimate) + " " + L("du budget", "of budget")} />
                <Kpi label={L("Part climat (CRPFM-2)", "Climate share (CRPFM-2)")} value={pct(agg.shareClimate)} />
                <Kpi label={L("Atténuation", "Mitigation")} value={fmt(agg.mitigation, 0)} />
                <Kpi label={L("Adaptation", "Adaptation")} value={fmt(agg.adaptation, 0)} />
                <Kpi label={L("Aligné CDN", "NDC-aligned")} value={fmt(agg.ndcAligned, 0)} />
              </div>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                <Kpi label={L("Exécuté climat (CRPFM-14)", "Climate executed (CRPFM-14)")} value={fmt(agg.climateExecuted, 0)} hint={agg.shareExecuted != null ? pct(agg.shareExecuted) + " " + L("de l'exécuté", "of executed") : null} />
                <Kpi label={L("Budget total", "Total budget")} value={fmt(agg.total, 0)} />
                {agg.executedTotal > 0 && <Kpi label={L("Exécuté total", "Total executed")} value={fmt(agg.executedTotal, 0)} />}
              </div>
            </>
          ) : <div className="text-faint" style={{ fontSize: 11.5 }}>{L("Ajoutez des lignes budgétaires pour calculer les dépenses pertinentes climat.", "Add budget lines to compute climate-relevant expenditure.")}</div>}
        </div>

        <div className="text-faint" style={{ fontSize: 10.5, marginTop: 4 }}>
          {L("Méthodologie Rio Markers (OCDE 2021, repère non normatif). Pertinence climat = poids maximal des objectifs atténuation/adaptation (évite le double comptage). Coefficients paramétrables ; l'étiquetage relève d'une convention nationale.",
             "Rio Markers methodology (OECD 2021, non-normative reference). Climate relevance = maximum weight of mitigation/adaptation objectives (avoids double counting). Coefficients are configurable; tagging follows a national convention.")}
        </div>
      </div>
    );
  }

  window.ClimTagScreen = ClimTagScreen;
})();
