/* global React, Icon, window */
// ============================================================================
// MELR · MTDS / SDMT — tableau de bord coût-risque d'un portefeuille de dette.
// Moteur : public/mtds-calc.jsx (window.MTDS). Saisie de la composition du
// portefeuille (par tranche) + macro optionnelle → indicateurs ATM/ATR, parts
// de risque et ratios de coût. Honnêteté : indicateurs, PAS la simulation
// pluriannuelle sous chocs (outil officiel Banque mondiale MTDS-ABPT.xlsm).
// ============================================================================

(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 ? 2 : d));
  const pct = (v) => (v == null ? "—" : (100 * v).toFixed(1) + " %");

  const SUGGESTED = ["SEN", "CIV", "MLI", "BFA", "NER", "BEN", "TGO", "GHA"];

  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, currency: "dom", rateType: "fixed", maturity: null, refixing: null, rate: null, due1y: null };

  function MtdsScreen({ lang, effectiveOrgId, isSuperAdmin, hasPerm }) {
    const L = (fr, en) => (lang === "fr" ? fr : en);
    const M = window.MTDS;
    const canManage = isSuperAdmin
      || (typeof hasPerm === "function" && (hasPerm("users.manage") || hasPerm("evaluations.manage")));

    const [iso3, setIso3] = useState(() => { try { return localStorage.getItem("melr.mtds.iso3") || "SEN"; } catch (_) { return "SEN"; } });
    useEffect(() => { try { localStorage.setItem("melr.mtds.iso3", iso3); } catch (_) {} }, [iso3]);

    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 || !iso3) return;
      window.melr.fetchMtdsProfile(effectiveOrgId, iso3.trim().toUpperCase())
        .then((p) => { if (!cancelled) setProfile(p || { portfolio: [], macro: {} }); })
        .catch(() => { if (!cancelled) setProfile({ portfolio: [], macro: {} }); });
      return () => { cancelled = true; };
    }, [effectiveOrgId, iso3]);

    const portfolio = (profile && profile.portfolio) || [];
    const macro = (profile && profile.macro) || {};
    const setPortfolio = (pf) => { setProfile({ ...(profile || {}), portfolio: pf }); setDirty(true); };
    const setMacro = (k, v) => { setProfile({ ...(profile || {}), macro: { ...macro, [k]: v } }); setDirty(true); };
    const addRow = () => setPortfolio([...portfolio, { ...BLANK }]);
    const removeRow = (i) => setPortfolio(portfolio.filter((_, j) => j !== i));
    const updateRow = (i, k, v) => setPortfolio(portfolio.map((r, j) => (j === i ? { ...r, [k]: v } : r)));
    const numv = (e) => (e.target.value === "" ? null : Number(e.target.value));

    const ind = profile ? M.indicators(portfolio, macro) : null;

    const saveProfile = async () => {
      setSaveBusy(true); setSaveMsg(null);
      try {
        await window.melr.saveMtdsProfile(effectiveOrgId, iso3.trim().toUpperCase(), {
          country_name: profile.country_name || null,
          portfolio: portfolio, macro: macro, 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" };

    return (
      <div className="page">
        <div className="page-header">
          <div className="page-eyebrow">{L("ÉVALUATIONS · STRATÉGIE DE DETTE", "EVALUATIONS · DEBT STRATEGY")}</div>
          <h1 className="page-title">{L("MTDS / SDMT — coût-risque du portefeuille de dette", "MTDS / SDMT — debt portfolio cost-risk")}</h1>
          <div className="page-sub">{L("Indicateurs coût-risque (ATM, ATR, parts de risque) d'après le cadre MTDS (Banque mondiale/FMI).", "Cost-risk indicators (ATM, ATR, risk shares) per the MTDS framework (World Bank/IMF).")}</div>
        </div>

        {/* Pays + enregistrement */}
        <div style={sec("purple")}>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap", alignItems: "flex-end" }}>
            <div>
              <label style={{ fontSize: 10.5, fontWeight: 600, display: "block", marginBottom: 2 }}>{L("Pays (ISO3)", "Country (ISO3)")}</label>
              <input className="input" list="mtds-countries" value={iso3} disabled={!canManage}
                onChange={(e) => setIso3(e.target.value.toUpperCase())} style={{ width: 120, fontSize: 12 }} />
              <datalist id="mtds-countries">{SUGGESTED.map((s) => <option key={s} value={s} />)}</datalist>
            </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>

        {/* Composition du portefeuille */}
        <div style={sec("amber")}>
          <div style={secT("amber")}>🏦 {L("Composition du portefeuille (par tranche/instrument)", "Portfolio composition (by tranche/instrument)")}</div>
          <div style={{ overflowX: "auto" }}>
            <table style={{ borderCollapse: "collapse", fontSize: 11.5, minWidth: 720 }}>
              <thead>
                <tr>
                  <th style={th}>{L("Libellé", "Label")}</th>
                  <th style={th}>{L("Encours", "Amount")}</th>
                  <th style={th}>{L("Devise", "Currency")}</th>
                  <th style={th}>{L("Type taux", "Rate type")}</th>
                  <th style={th}>{L("Maturité (a)", "Maturity (y)")}</th>
                  <th style={th}>{L("Révision (a)", "Refixing (y)")}</th>
                  <th style={th}>{L("Taux %", "Rate %")}</th>
                  <th style={th}>{L("Éch. ≤1a", "Due ≤1y")}</th>
                  <th style={th}></th>
                </tr>
              </thead>
              <tbody>
                {portfolio.map((r, i) => (
                  <tr key={i}>
                    <td style={{ padding: "1px 3px" }}><input style={{ ...cellSel, width: 150 }} 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" }}>
                      <select style={cellSel} disabled={!canManage} value={r.currency} onChange={(e) => updateRow(i, "currency", e.target.value)}>
                        <option value="dom">{L("Interne", "Domestic")}</option>
                        <option value="fx">{L("Devises", "FX")}</option>
                      </select>
                    </td>
                    <td style={{ padding: "1px 3px" }}>
                      <select style={cellSel} disabled={!canManage} value={r.rateType} onChange={(e) => updateRow(i, "rateType", e.target.value)}>
                        <option value="fixed">{L("Fixe", "Fixed")}</option>
                        <option value="variable">{L("Variable", "Variable")}</option>
                      </select>
                    </td>
                    <td style={{ padding: "1px 3px" }}><input type="number" step="0.1" style={cellInput} disabled={!canManage} value={r.maturity == null ? "" : r.maturity} onChange={(e) => updateRow(i, "maturity", numv(e))} /></td>
                    <td style={{ padding: "1px 3px" }}><input type="number" step="0.1" style={cellInput} disabled={!canManage || r.rateType !== "variable"} value={r.refixing == null ? "" : r.refixing} onChange={(e) => updateRow(i, "refixing", numv(e))} title={L("Uniquement pour taux variable", "Variable rate only")} /></td>
                    <td style={{ padding: "1px 3px" }}><input type="number" step="0.1" style={cellInput} disabled={!canManage} value={r.rate == null ? "" : r.rate} onChange={(e) => updateRow(i, "rate", numv(e))} /></td>
                    <td style={{ padding: "1px 3px" }}><input type="number" style={cellInput} disabled={!canManage} value={r.due1y == null ? "" : r.due1y} onChange={(e) => updateRow(i, "due1y", numv(e))} /></td>
                    <td style={{ padding: "1px 3px" }}>{canManage && <button className="btn xs ghost" onClick={() => removeRow(i)} title={L("Retirer", "Remove")}>×</button>}</td>
                  </tr>
                ))}
                {!portfolio.length && <tr><td colSpan={9} className="text-faint" style={{ padding: 8, fontSize: 11.5 }}>{L("Aucune tranche. Ajoutez des instruments pour calculer les indicateurs.", "No tranche. Add instruments to compute indicators.")}</td></tr>}
              </tbody>
            </table>
          </div>
          {canManage && <button className="btn xs" style={{ marginTop: 6 }} onClick={addRow}><Icon.plus /> {L("Ajouter une tranche", "Add tranche")}</button>}
          <div className="text-faint" style={{ fontSize: 10.5, marginTop: 6 }}>
            {L("« Révision » = temps jusqu'à la prochaine révision de taux (dette à taux variable). « Éch. ≤1a » = principal arrivant à échéance sous 1 an. Encours dans une même unité.",
               "'Refixing' = time to next rate reset (variable-rate debt). 'Due ≤1y' = principal maturing within 1 year. Amounts in one common unit.")}
          </div>
        </div>

        {/* Macro optionnelle */}
        <div style={sec()}>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap", alignItems: "flex-end" }}>
            {[["gdp", L("PIB", "GDP")], ["revenue", L("Recettes", "Revenue")], ["debtService", L("Service de la dette (an)", "Debt service (yr)")]].map(([k, lab]) => (
              <div key={k}>
                <label style={{ fontSize: 10.5, fontWeight: 600, display: "block", marginBottom: 2 }}>{lab}</label>
                <input type="number" className="input" disabled={!canManage} value={macro[k] == null ? "" : macro[k]}
                  onChange={(e) => setMacro(k, e.target.value === "" ? null : Number(e.target.value))} style={{ width: 130, fontSize: 12, textAlign: "right" }} />
              </div>
            ))}
            <span className="text-faint" style={{ fontSize: 10.5 }}>{L("(optionnel — pour dette/PIB et service/recettes)", "(optional — for debt/GDP and service/revenue)")}</span>
          </div>
        </div>

        {/* Indicateurs coût-risque */}
        <div style={sec("blue")}>
          <div style={secT("blue")}>📊 {L("Indicateurs coût-risque", "Cost-risk indicators")}</div>
          {ind ? (
            <>
              <div style={{ fontWeight: 700, fontSize: 11.5, margin: "2px 0 6px" }}>{L("Risque", "Risk")}</div>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 10 }}>
                <Kpi label="ATM" value={fmt(ind.atm, 1)} hint={L("ans · refinancement", "yrs · refinancing")} />
                <Kpi label="ATR" value={fmt(ind.atr, 1)} hint={L("ans · taux", "yrs · rate")} />
                <Kpi label={L("Part variable", "Variable share")} value={pct(ind.shareVariable)} hint={L("risque de taux", "interest rate risk")} />
                <Kpi label={L("Part devises", "FX share")} value={pct(ind.shareFx)} hint={L("risque de change", "exchange rate risk")} />
                <Kpi label={L("Re-fixée ≤1a", "Re-fixing ≤1y")} value={pct(ind.refixShare1y)} />
                {ind.share1y != null && <Kpi label={L("Éch. ≤1a", "Maturing ≤1y")} value={pct(ind.share1y)} hint={L("refinancement", "refinancing")} />}
              </div>
              <div style={{ fontWeight: 700, fontSize: 11.5, margin: "2px 0 6px" }}>{L("Coût", "Cost")}</div>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                <Kpi label={L("Taux moyen pondéré", "Weighted avg rate")} value={ind.wavgRate == null ? "—" : fmt(ind.wavgRate, 2) + " %"} />
                {ind.debtToGdp != null && <Kpi label={L("Dette / PIB", "Debt / GDP")} value={pct(ind.debtToGdp)} />}
                {ind.serviceToRev != null && <Kpi label={L("Service / recettes", "Service / revenue")} value={pct(ind.serviceToRev)} />}
                <Kpi label={L("Encours total", "Total outstanding")} value={fmt(ind.total, 0)} />
              </div>
            </>
          ) : <div className="text-faint" style={{ fontSize: 11.5 }}>{L("Ajoutez des tranches au portefeuille pour calculer les indicateurs.", "Add portfolio tranches to compute the indicators.")}</div>}
        </div>

        <div className="text-faint" style={{ fontSize: 10.5, marginTop: 4 }}>
          {L("Indicateurs coût-risque d'après le cadre MTDS (Banque mondiale/FMI). ⚠ Ce module calcule les indicateurs et compare des stratégies — il ne reproduit PAS la simulation pluriannuelle sous scénarios de choc (taux, change), pour laquelle l'outil officiel MTDS-ABPT.xlsm de la Banque mondiale fait foi.",
             "Cost-risk indicators per the MTDS framework (World Bank/IMF). ⚠ This module computes the indicators and compares strategies — it does NOT reproduce the multi-year simulation under shock scenarios (rate, FX), for which the World Bank's official MTDS-ABPT.xlsm tool is authoritative.")}
        </div>
      </div>
    );
  }

  window.MtdsScreen = MtdsScreen;
})();
