/* global React, Icon, Modal, window */
// ============================================================================
// MELR · Évaluation des politiques publiques — critères OCDE/CAD 2019
// ----------------------------------------------------------------------------
// Phase 4a du module ÉVALUATIONS (PEFA/DESIGN-MODULE-EVALUATIONS.md §7).
// Squelette méthodologique standard, réutilisable par les types
// mi-parcours / finale :
//   Cadrage → Matrice d'évaluation (questions → critères → jugement →
//   indicateurs → sources) → Constats par critère → Conclusions &
//   recommandations → Réponse managériale. Export Word du rapport.
//
// Données : registre `evaluations` (type 'policy') + feuilles JSONB
// `evaluation_sheets` (sheets framing / matrix / findings / conclusions /
// response). Aucune table spécifique au type.
// ============================================================================

(function () {
  const { useState, useEffect, useMemo } = React;

  // Conventions visuelles partagées du groupe ÉVALUATIONS (window.MelrSection,
  // définies dans screens-evaluations.jsx) : sections teintées + exports pleins.
  const sec = (c, extra) => (window.MelrSection ? window.MelrSection.style(c, extra) : { marginBottom: 14, ...(extra || {}) });
  const secT = (c) => (window.MelrSection ? window.MelrSection.title(c) : { fontSize: 13, fontWeight: 700, marginBottom: 8 });
  const xbtn = (bg) => (window.MelrSection ? window.MelrSection.btn(bg) : {});

  // Les 6 critères officiels OCDE/CAD (2019)
  const DAC_CRITERIA = [
    { key: "relevance",      fr: "Pertinence",              en: "Relevance", es: "Pertinencia",
      hint_fr: "L'intervention répond-elle aux besoins et priorités des bénéficiaires et du pays ?",
      hint_en: "Is the intervention doing the right things?" },
    { key: "coherence",      fr: "Cohérence",               en: "Coherence", es: "Coherencia",
      hint_fr: "L'intervention s'accorde-t-elle avec les autres interventions (internes et externes) ?",
      hint_en: "How well does the intervention fit?" },
    { key: "effectiveness",  fr: "Efficacité",              en: "Effectiveness", es: "Eficacia",
      hint_fr: "Les objectifs et résultats attendus sont-ils atteints ?",
      hint_en: "Is the intervention achieving its objectives?" },
    { key: "efficiency",     fr: "Efficience",              en: "Efficiency", es: "Eficiencia",
      hint_fr: "Les ressources sont-elles utilisées de manière économique et en temps voulu ?",
      hint_en: "How well are resources being used?" },
    { key: "impact",         fr: "Impact",                  en: "Impact", es: "Impacto",
      hint_fr: "Quels effets significatifs de niveau supérieur, positifs ou négatifs, attendus ou non ?",
      hint_en: "What difference does the intervention make?" },
    { key: "sustainability", fr: "Viabilité / durabilité",  en: "Sustainability", es: "Viabilidad / sostenibilidad",
      hint_fr: "Les bénéfices sont-ils susceptibles de perdurer après la fin de l'intervention ?",
      hint_en: "Will the benefits last?" },
  ];
  const CRITERIA_BY_KEY = {};
  DAC_CRITERIA.forEach((c) => { CRITERIA_BY_KEY[c.key] = c; });

  // Échelle d'appréciation par critère (usuelle chez les bailleurs)
  const RATINGS = {
    hs: { fr: "Très satisfaisant",  en: "Highly satisfactory", es: "Muy satisfactorio",  color: "#15803d", fill: "#dcfce7" },
    s:  { fr: "Satisfaisant",       en: "Satisfactory", es: "Satisfactorio",         color: "#1d4ed8", fill: "#dbeafe" },
    ms: { fr: "Peu satisfaisant",   en: "Moderately unsatisfactory", es: "Poco satisfactorio", color: "#b45309", fill: "#fef3c7" },
    us: { fr: "Insatisfaisant",     en: "Unsatisfactory", es: "Insatisfactorio",       color: "#b91c1c", fill: "#fee2e2" },
  };

  const FRAMING_FIELDS = [
    { key: "object",      fr: "Objet de l'évaluation",          en: "Evaluation object", es: "Objeto de la evaluación",
      hint_fr: "Politique / programme évalué, période couverte, périmètre géographique et institutionnel.",
      hint_en: "Policy / programme evaluated, period covered, geographic and institutional scope." },
    { key: "purpose",     fr: "Finalité et utilisateurs",       en: "Purpose and users", es: "Finalidad y usuarios",
      hint_fr: "Pourquoi évaluer maintenant, pour quels décideurs, quelles décisions à éclairer.",
      hint_en: "Why evaluate now, for which decision-makers, which decisions to inform." },
    { key: "questions",   fr: "Questions évaluatives",          en: "Evaluation questions", es: "Preguntas evaluativas",
      hint_fr: "Les grandes questions (reprises et détaillées dans la matrice d'évaluation).",
      hint_en: "The main questions (detailed in the evaluation matrix)." },
    { key: "toc",         fr: "Théorie du changement",          en: "Theory of change", es: "Teoría del cambio",
      hint_fr: "Chaîne de résultats, hypothèses, risques.",
      hint_en: "Results chain, assumptions, risks." },
    { key: "methods",     fr: "Méthodologie",                   en: "Methodology", es: "Metodología",
      hint_fr: "Méthodes de collecte et d'analyse (mixtes, contrefactuelles…), échantillonnage, limites.",
      hint_en: "Collection and analysis methods (mixed, counterfactual…), sampling, limitations." },
    { key: "calendar",    fr: "Calendrier et gouvernance",      en: "Timeline and governance", es: "Calendario y gobernanza",
      hint_fr: "Jalons, comité de pilotage, équipe d'évaluation.",
      hint_en: "Milestones, steering committee, evaluation team." },
  ];

  const RESPONSE_CHOICES = {
    accepted:  { fr: "Acceptée",              en: "Accepted", es: "Aceptada" },
    partial:   { fr: "Partiellement acceptée", en: "Partially accepted", es: "Parcialmente aceptada" },
    rejected:  { fr: "Rejetée",               en: "Rejected", es: "Rechazada" },
  };
  const RESPONSE_STATUSES = {
    todo:        { fr: "À faire",  en: "To do", es: "Por hacer" },
    in_progress: { fr: "En cours", en: "In progress", es: "En curso" },
    done:        { fr: "Réalisée", en: "Done", es: "Realizada" },
  };

  // Constantes partagées avec les autres types fondés sur les critères CAD
  // (mi-parcours / finale — screens-midterm-eval.jsx).
  window.MELR_DAC = {
    CRITERIA: DAC_CRITERIA,
    RATINGS,
    RESPONSE_CHOICES,
    RESPONSE_STATUSES,
  };

  // Teinte OKLCH distincte par onglet (.pd-tabs / .pd-tab, comme Projets / Ex-ante).
  const TABS = [
    { key: "overview",    fr: "Vue d'ensemble",                en: "Overview", es: "Visión general",                       hue: 230 },
    { key: "framing",     fr: "Cadrage",                       en: "Framing", es: "Encuadre",                        hue: 50 },
    { key: "matrix",      fr: "Matrice d'évaluation",          en: "Evaluation matrix", es: "Matriz de evaluación",              hue: 25 },
    { key: "findings",    fr: "Constats par critère",          en: "Findings by criterion", es: "Constataciones por criterio",          hue: 150 },
    { key: "conclusions", fr: "Conclusions & recommandations", en: "Conclusions & recommendations", es: "Conclusiones y recomendaciones",  hue: 285 },
    { key: "response",    fr: "Réponse managériale",           en: "Management response", es: "Respuesta directiva",            hue: 350 },
  ];

  function RatingPill({ rating, lang }) {
    const m = RATINGS[rating];
    if (!m) return <span style={{ fontSize: 11, color: "var(--text-faint)" }}>—</span>;
    return (
      <span style={{ fontSize: 10.5, fontWeight: 700, padding: "2px 8px", borderRadius: 999, background: m.fill, color: m.color }}>
        {(lang === "es" ? (m.es != null ? m.es : m.en) : lang === "fr" ? m.fr : m.en)}
      </span>
    );
  }

  // ── Export Word du rapport d'évaluation ──────────────────────────────────
  function exportPolicyReportWord(lang, evaluation, sheets) {
    const D = window.docx;
    if (!D) { window.alert(window.L("Bibliothèque Word indisponible.", "Word library unavailable.", "Biblioteca Word no disponible.")); return; }
    const L = (fr, en) => (lang === "fr" ? fr : en);
    const title = lang === "fr" ? (evaluation.title_fr || "Évaluation") : (evaluation.title_en || evaluation.title_fr || "Evaluation");
    const P = (text, o) => new D.Paragraph({
      children: [new D.TextRun({ text, size: (o && o.size) || 21, bold: !!(o && o.bold), color: (o && o.color) || "111827", font: "Arial", italics: !!(o && o.italics) })],
      spacing: { after: (o && o.after) != null ? o.after : 100 },
    });
    const H1 = (t) => P(t, { size: 26, bold: true, color: "0F2740", after: 140 });
    const H2 = (t) => P(t, { size: 22, bold: true, color: "1D4ED8", after: 90 });
    const block = (text) => ((text || "").trim() || L("(à compléter)", "(to be completed)"))
      .split(/\n+/).map((line) => P(line));
    const framing = sheets.framing || {}, findings = sheets.findings || {},
          conclusions = sheets.conclusions || {}, response = sheets.response || {},
          matrix = (sheets.matrix && sheets.matrix.rows) || [];
    const children = [
      P(L("RAPPORT D'ÉVALUATION — POLITIQUE PUBLIQUE", "EVALUATION REPORT — PUBLIC POLICY"), { size: 28, bold: true, color: "0F2740", after: 80 }),
      P(title, { size: 25, bold: true, color: "1D4ED8", after: 60 }),
      P(L("Critères OCDE/CAD (2019) · Période : ", "OECD/DAC criteria (2019) · Period: ")
        + (evaluation.period_start || "—") + (evaluation.period_end ? " → " + evaluation.period_end : ""),
        { size: 18, color: "64748B", after: 240 }),
      H1(L("1. Cadrage de l'évaluation", "1. Evaluation framing")),
    ];
    FRAMING_FIELDS.forEach((f) => {
      children.push(H2((lang === "es" ? (f.es != null ? f.es : f.en) : lang === "fr" ? f.fr : f.en)));
      children.push(...block(framing[f.key]));
    });
    children.push(H1(L("2. Matrice d'évaluation", "2. Evaluation matrix")));
    if (matrix.length === 0) children.push(...block(""));
    matrix.forEach((row, i) => {
      const c = CRITERIA_BY_KEY[row.criterion];
      children.push(P((i + 1) + ". " + (row.question || "—")
        + (c ? "  [" + ((lang === "es" ? (c.es != null ? c.es : c.en) : lang === "fr" ? c.fr : c.en)) + "]" : ""), { size: 20, bold: true, after: 40 }));
      if (row.judgement)  children.push(P(L("Critères de jugement : ", "Judgement criteria: ") + row.judgement, { size: 18, after: 30 }));
      if (row.indicators) children.push(P(L("Indicateurs : ", "Indicators: ") + row.indicators, { size: 18, after: 30 }));
      if (row.sources)    children.push(P(L("Sources / méthodes : ", "Sources / methods: ") + row.sources, { size: 18, after: 80 }));
    });
    children.push(H1(L("3. Constats par critère", "3. Findings by criterion")));
    DAC_CRITERIA.forEach((c) => {
      const f = (findings[c.key] || {});
      const r = RATINGS[f.rating];
      children.push(H2(((lang === "es" ? (c.es != null ? c.es : c.en) : lang === "fr" ? c.fr : c.en)) + (r ? L(" — Appréciation : ", " — Rating: ") + ((lang === "es" ? (r.es != null ? r.es : r.en) : lang === "fr" ? r.fr : r.en)) : "")));
      children.push(...block(f.text));
    });
    children.push(H1(L("4. Conclusions", "4. Conclusions")));
    children.push(...block(conclusions.text));
    children.push(H1(L("5. Recommandations et réponse managériale", "5. Recommendations and management response")));
    const recs = (conclusions.recommendations || []);
    if (recs.length === 0) children.push(...block(""));
    recs.forEach((rec, i) => {
      children.push(P("R" + (i + 1) + ". " + (rec.text || "—")
        + (rec.addressee ? L(" — Destinataire : ", " — Addressee: ") + rec.addressee : ""), { size: 20, bold: true, after: 40 }));
      const resp = (response.items || {})[String(i)] || {};
      const ch = RESPONSE_CHOICES[resp.decision];
      if (ch || resp.comment) {
        children.push(P(L("Réponse : ", "Response: ")
          + (ch ? ((lang === "es" ? (ch.es != null ? ch.es : ch.en) : lang === "fr" ? ch.fr : ch.en)) : "—")
          + (resp.comment ? " — " + resp.comment : "")
          + (resp.responsible ? L(" · Responsable : ", " · Responsible: ") + resp.responsible : "")
          + (resp.due ? L(" · Échéance : ", " · Due: ") + resp.due : ""),
          { size: 18, italics: true, after: 80 }));
      }
    });
    const doc = new D.Document({ sections: [{ children }] });
    const fname = "Evaluation_politique_" + (evaluation.title_fr || "rapport").replace(/[^\wÀ-ſ-]+/g, "_") + ".docx";
    D.Packer.toBlob(doc).then((blob) => {
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url; a.download = fname; a.click();
      setTimeout(() => URL.revokeObjectURL(url), 4000);
    });
  }

  // ── Modale de création ───────────────────────────────────────────────────
  function NewPolicyEvalModal({ lang, effectiveOrgId, onClose, onCreated }) {
    const { projects } = window.melr.useProjects ? window.melr.useProjects() : { projects: [] };
    const [titleFr, setTitleFr] = useState("");
    const [titleEn, setTitleEn] = useState("");
    const [periodStart, setPeriodStart] = useState("");
    const [periodEnd, setPeriodEnd] = useState("");
    const [projectId, setProjectId] = useState("");
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState(null);
    const L = (fr, en) => (lang === "fr" ? fr : en);
    const lbl = { fontSize: 12, fontWeight: 600, display: "block", marginBottom: 4 };
    const submit = async (e) => {
      e.preventDefault();
      if (!titleFr.trim()) { setErr(L("Le titre (FR) est requis.", "Title (FR) is required.")); return; }
      setBusy(true); setErr(null);
      try {
        const ev = await window.melr.evaluationsCrud.create({
          organization_id: effectiveOrgId,
          type: "policy",
          title_fr: titleFr.trim(),
          title_en: titleEn.trim() || titleFr.trim(),
          status: "planning",
          period_start: periodStart || null,
          period_end: periodEnd || null,
          project_id: projectId || null,
        });
        if (onCreated) onCreated(ev);
      } catch (ex) { setErr(ex.message); setBusy(false); }
    };
    return (
      <Modal title={L("Nouvelle évaluation de politique publique", "New public policy evaluation")} onClose={onClose} onSubmit={submit}
        footer={(<>
          <button type="button" className="btn sm ghost" onClick={onClose}>{L("Annuler", "Cancel")}</button>
          <button type="submit" className="btn sm primary" disabled={busy}>{busy ? "…" : L("Créer", "Create")}</button>
        </>)}>
        <div style={{ marginBottom: 12 }}>
          <label style={lbl}>{L("Titre (FR) *", "Title (FR) *")}</label>
          <input className="input" value={titleFr} onChange={(e) => setTitleFr(e.target.value)}
            placeholder={L("ex. Évaluation de la politique nationale de santé 2019-2024", "e.g. Evaluation of the national health policy 2019-2024")}
            style={{ width: "100%" }} />
        </div>
        <div style={{ marginBottom: 12 }}>
          <label style={lbl}>{L("Titre (EN)", "Title (EN)")}</label>
          <input className="input" value={titleEn} onChange={(e) => setTitleEn(e.target.value)} style={{ width: "100%" }} />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12 }}>
          <div>
            <label style={lbl}>{L("Début", "Start")}</label>
            <input type="date" className="input" value={periodStart} onChange={(e) => setPeriodStart(e.target.value)} style={{ width: "100%" }} />
          </div>
          <div>
            <label style={lbl}>{L("Fin", "End")}</label>
            <input type="date" className="input" value={periodEnd} onChange={(e) => setPeriodEnd(e.target.value)} style={{ width: "100%" }} />
          </div>
        </div>
        <div style={{ marginBottom: 12 }}>
          <label style={lbl}>{L("Projet lié (optionnel)", "Linked project (optional)")}</label>
          {/* useProjects() remappe : uuid = UUID (FK), id = CODE, nameFr/nameEn. */}
          <select className="input" value={projectId} onChange={(e) => setProjectId(e.target.value)} style={{ width: "100%" }}>
            <option value="">{L("— Aucun —", "— None —")}</option>
            {(projects || []).map((p) => (
              <option key={p.uuid} value={p.uuid}>{p.id} · {(lang === "es" ? (p.nameEs != null ? p.nameEs : p.nameEn || p.nameFr) : lang === "fr" ? p.nameFr : p.nameEn || p.nameFr)}</option>
            ))}
          </select>
        </div>
        {err && <div style={{ color: "#b91c1c", fontSize: 12 }}>{err}</div>}
      </Modal>
    );
  }

  // ── Écran principal ──────────────────────────────────────────────────────
  function PolicyEvalScreen({ lang, effectiveOrgId, isSuperAdmin, hasPerm }) {
    const L = (fr, en) => (lang === "fr" ? fr : en);
    const { data: allEvals, refresh } = window.melr.useEvaluations
      ? window.melr.useEvaluations(effectiveOrgId)
      : { data: [], refresh: () => {} };
    const evals = useMemo(() => (allEvals || []).filter((e) => e.type === "policy"), [allEvals]);

    const [tab, setTab] = useState("overview");
    const [selectedId, setSelectedId] = useState(() => {
      try { return localStorage.getItem("melr.policy.selected") || null; } catch (_) { return null; }
    });
    const selected = useMemo(
      () => evals.find((e) => e.id === selectedId) || evals[0] || null,
      [evals, selectedId]
    );
    useEffect(() => {
      if (selected && selected.id !== selectedId) {
        setSelectedId(selected.id);
        try { localStorage.setItem("melr.policy.selected", selected.id); } catch (_) {}
      }
    }, [selected, selectedId]);

    const canManage = isSuperAdmin
      || (typeof hasPerm === "function" && (hasPerm("users.manage") || hasPerm("evaluations.manage")));

    // Feuilles (chargées en bloc à la sélection)
    const [sheets, setSheets] = useState({});
    const [dirty, setDirty] = useState(false);
    const [busy, setBusy] = useState(false);
    const [msg, setMsg] = useState(null);
    useEffect(() => {
      let cancelled = false;
      setSheets({}); setDirty(false); setMsg(null);
      if (!selected) return;
      Promise.all(["framing", "matrix", "findings", "conclusions", "response"]
        .map((s) => window.melr.fetchEvaluationSheet(selected.id, s)))
        .then((rows) => {
          if (cancelled) return;
          const next = {};
          ["framing", "matrix", "findings", "conclusions", "response"].forEach((s, i) => {
            next[s] = (rows[i] && rows[i].data) || {};
          });
          setSheets(next);
        })
        .catch((e) => { if (!cancelled) setMsg(e.message); });
      return () => { cancelled = true; };
    }, [selected && selected.id]);

    const patchSheet = (sheet, data) => { setSheets({ ...sheets, [sheet]: data }); setDirty(true); };
    const saveAll = async () => {
      if (!selected) return;
      setBusy(true); setMsg(null);
      try {
        for (const s of ["framing", "matrix", "findings", "conclusions", "response"]) {
          await window.melr.saveEvaluationSheet(selected.id, s, sheets[s] || {});
        }
        setDirty(false);
        setMsg(L("Évaluation enregistrée.", "Evaluation saved."));
      } catch (e) { setMsg(L("Erreur : ", "Error: ") + e.message); }
      finally { setBusy(false); }
    };

    const [newOpen, setNewOpen] = useState(false);
    const framing = sheets.framing || {};
    const matrixRows = (sheets.matrix && sheets.matrix.rows) || [];
    const findings = sheets.findings || {};
    const conclusions = sheets.conclusions || {};
    const recommendations = conclusions.recommendations || [];
    const response = sheets.response || {};
    const lbl = { fontSize: 11, fontWeight: 600, display: "block", marginBottom: 2 };
    const STATUS_META = window.EVALUATION_STATUS_META || {};

    return (
      <div className="page" data-screen-label="Policy evaluation">
        <div className="page-header">
          <div className="page-eyebrow">{L("ÉVALUATIONS · POLITIQUES PUBLIQUES", "EVALUATIONS · PUBLIC POLICY")}</div>
          <div className="page-header-row">
            <div>
              <h1 className="page-title">
                {L("Évaluation des politiques publiques", "Public policy evaluation")}
                {selected && <span style={{ fontWeight: 500, color: "var(--text-faint)" }}>
                  {" — "}{(lang === "es" ? (selected.title_es != null ? selected.title_es : selected.title_en || selected.title_fr) : lang === "fr" ? selected.title_fr : selected.title_en || selected.title_fr)}
                </span>}
              </h1>
              <div className="page-sub">
                {L("Les 6 critères OCDE/CAD 2019 : pertinence, cohérence, efficacité, efficience, impact, viabilité.",
                   "The 6 OECD/DAC 2019 criteria: relevance, coherence, effectiveness, efficiency, impact, sustainability.")}
              </div>
            </div>
            <div className="page-header-actions">
              {canManage && (
                <button className="btn sm primary" onClick={() => setNewOpen(true)}>
                  <Icon.plus /> {L("Nouvelle évaluation", "New evaluation")}
                </button>
              )}
            </div>
          </div>
        </div>

        {evals.length > 1 && (
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <span className="text-faint" style={{ fontSize: 11.5 }}>{L("Évaluation :", "Evaluation:")}</span>
            <select className="input" value={selected ? selected.id : ""}
              onChange={(e) => {
                setSelectedId(e.target.value);
                try { localStorage.setItem("melr.policy.selected", e.target.value); } catch (_) {}
              }}>
              {evals.map((e) => (
                <option key={e.id} value={e.id}>{(lang === "es" ? (e.title_es != null ? e.title_es : e.title_en || e.title_fr) : lang === "fr" ? e.title_fr : e.title_en || e.title_fr)}</option>
              ))}
            </select>
          </div>
        )}
        <div className="pd-tabs" style={{ marginBottom: 16 }}>
          {TABS.map((tb) => (
            <button key={tb.key}
              className={"pd-tab" + (tab === tb.key ? " active" : "")}
              onClick={() => setTab(tb.key)}
              data-hue={tb.hue}
              style={{ "--tab-hue": tb.hue }}>
              {(lang === "es" ? (tb.es != null ? tb.es : tb.en) : lang === "fr" ? tb.fr : tb.en)}
            </button>
          ))}
        </div>

        {/* Barre d'actions commune (hors vue d'ensemble) */}
        {tab !== "overview" && selected && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
            {canManage && (
              <button className="btn sm primary" disabled={busy || !dirty} onClick={saveAll}>
                {busy ? "…" : L("Enregistrer", "Save")}
              </button>
            )}
            <button style={xbtn("#2563eb")} onClick={() => exportPolicyReportWord(lang, selected, sheets)}>
              📄 {L("Rapport (Word)", "Report (Word)")}
            </button>
            {dirty && <span style={{ fontSize: 11, color: "#b45309" }}>{L("Modifications non enregistrées", "Unsaved changes")}</span>}
            {msg && <span className="text-faint" style={{ fontSize: 11 }}>{msg}</span>}
          </div>
        )}
        {tab !== "overview" && !selected && (
          <div className="card"><div className="card-body" style={{ padding: 22, color: "var(--text-faint)", fontSize: 12.5 }}>
            {L("Créez d'abord une évaluation (bouton en haut à droite).", "Create an evaluation first (top-right button).")}
          </div></div>
        )}

        {/* ═ Vue d'ensemble ═ */}
        {tab === "overview" && (
          <div style={sec("green")}>
            <div>
              <table className="tbl" style={{ width: "100%" }}>
                <thead><tr>
                  <th>{L("Titre", "Title")}</th><th>{L("Période", "Period")}</th>
                  <th>{L("Projet", "Project")}</th><th>{L("Statut", "Status")}</th><th></th>
                </tr></thead>
                <tbody>
                  {evals.length === 0 && (
                    <tr><td colSpan={5} className="text-faint" style={{ padding: 16, fontSize: 12 }}>
                      {L("Aucune évaluation de politique publique pour le moment.", "No public policy evaluation yet.")}
                    </td></tr>
                  )}
                  {evals.map((e) => {
                    const sm = STATUS_META[e.status] || { fr: e.status, en: e.status, color: "#6b7280", fill: "#f3f4f6" };
                    return (
                      <tr key={e.id} style={{ background: selected && selected.id === e.id ? "var(--bg-sunken)" : undefined }}>
                        <td style={{ fontWeight: 600, fontSize: 12.5 }}>{(lang === "es" ? (e.title_es != null ? e.title_es : e.title_en || e.title_fr) : lang === "fr" ? e.title_fr : e.title_en || e.title_fr)}</td>
                        <td style={{ fontSize: 12 }}>{(e.period_start || "—")}{e.period_end ? " → " + e.period_end : ""}</td>
                        <td style={{ fontSize: 12 }}>{e.projects ? e.projects.code : "—"}</td>
                        <td><span style={{ display: "inline-block", padding: "2px 8px", borderRadius: 10, background: sm.fill, color: sm.color, fontSize: 11, fontWeight: 600 }}>
                          {(lang === "es" ? (sm.es != null ? sm.es : sm.en) : lang === "fr" ? sm.fr : sm.en)}</span></td>
                        <td style={{ textAlign: "right", paddingRight: 12 }}>
                          <button className="btn xs ghost" onClick={() => {
                            setSelectedId(e.id);
                            try { localStorage.setItem("melr.policy.selected", e.id); } catch (_) {}
                            setTab("framing");
                          }}>{L("Ouvrir", "Open")} →</button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* ═ Cadrage ═ */}
        {tab === "framing" && selected && FRAMING_FIELDS.map((f) => (
          <div key={f.key} style={sec("green", { marginBottom: 12 })}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 2 }}>{(lang === "es" ? (f.es != null ? f.es : f.en) : lang === "fr" ? f.fr : f.en)}</div>
              <div className="text-faint" style={{ fontSize: 11.5, marginBottom: 8 }}>{(lang === "es" ? (f.hint_es != null ? f.hint_es : f.hint_en) : lang === "fr" ? f.hint_fr : f.hint_en)}</div>
              <textarea className="input" rows={3} disabled={!canManage}
                style={{ width: "100%", resize: "vertical", fontSize: 12.5 }}
                value={framing[f.key] || ""}
                onChange={(e) => patchSheet("framing", { ...framing, [f.key]: e.target.value })} />
            </div>
          </div>
        ))}

        {/* ═ Matrice ═ */}
        {tab === "matrix" && selected && (
          <div style={sec("amber")}>
            <div>
              <div className="text-faint" style={{ fontSize: 11.5, marginBottom: 10 }}>
                {L("Chaque ligne relie une question évaluative à un critère CAD, ses critères de jugement, ses indicateurs et ses sources / méthodes de collecte.",
                   "Each row links an evaluation question to a DAC criterion, its judgement criteria, indicators and sources / collection methods.")}
              </div>
              <div style={{ overflowX: "auto" }}>
                <table className="tbl" style={{ minWidth: 860 }}>
                  <thead><tr>
                    <th style={{ minWidth: 220 }}>{L("Question évaluative", "Evaluation question")}</th>
                    <th style={{ minWidth: 130 }}>{L("Critère CAD", "DAC criterion")}</th>
                    <th style={{ minWidth: 180 }}>{L("Critères de jugement", "Judgement criteria")}</th>
                    <th style={{ minWidth: 160 }}>{L("Indicateurs", "Indicators")}</th>
                    <th style={{ minWidth: 160 }}>{L("Sources / méthodes", "Sources / methods")}</th>
                    <th></th>
                  </tr></thead>
                  <tbody>
                    {matrixRows.map((row, i) => {
                      const setRow = (k, v) => {
                        const rows = matrixRows.map((r, j) => (j === i ? { ...r, [k]: v } : r));
                        patchSheet("matrix", { rows });
                      };
                      return (
                        <tr key={i}>
                          <td><textarea className="input" rows={2} disabled={!canManage} value={row.question || ""}
                            onChange={(e) => setRow("question", e.target.value)} style={{ width: "100%", fontSize: 11.5, resize: "vertical" }} /></td>
                          <td>
                            <select className="input" disabled={!canManage} value={row.criterion || ""}
                              onChange={(e) => setRow("criterion", e.target.value)} style={{ width: "100%", fontSize: 11.5 }}>
                              <option value="">—</option>
                              {DAC_CRITERIA.map((c) => <option key={c.key} value={c.key}>{(lang === "es" ? (c.es != null ? c.es : c.en) : lang === "fr" ? c.fr : c.en)}</option>)}
                            </select>
                          </td>
                          <td><textarea className="input" rows={2} disabled={!canManage} value={row.judgement || ""}
                            onChange={(e) => setRow("judgement", e.target.value)} style={{ width: "100%", fontSize: 11.5, resize: "vertical" }} /></td>
                          <td><textarea className="input" rows={2} disabled={!canManage} value={row.indicators || ""}
                            onChange={(e) => setRow("indicators", e.target.value)} style={{ width: "100%", fontSize: 11.5, resize: "vertical" }} /></td>
                          <td><textarea className="input" rows={2} disabled={!canManage} value={row.sources || ""}
                            onChange={(e) => setRow("sources", e.target.value)} style={{ width: "100%", fontSize: 11.5, resize: "vertical" }} /></td>
                          <td style={{ textAlign: "center" }}>
                            {canManage && (
                              <button className="btn xs ghost" title={L("Supprimer la ligne", "Remove row")}
                                onClick={() => patchSheet("matrix", { rows: matrixRows.filter((_, j) => j !== i) })}>
                                <Icon.x />
                              </button>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              {canManage && (
                <button className="btn xs ghost" style={{ marginTop: 8 }}
                  onClick={() => patchSheet("matrix", { rows: [...matrixRows, {}] })}>
                  <Icon.plus /> {L("Ajouter une question", "Add a question")}
                </button>
              )}
            </div>
          </div>
        )}

        {/* ═ Constats ═ */}
        {tab === "findings" && selected && DAC_CRITERIA.map((c) => {
          const f = findings[c.key] || {};
          const linked = matrixRows.filter((r) => r.criterion === c.key);
          return (
            <div key={c.key} style={sec("green", { marginBottom: 12 })}>
              <div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 2 }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{(lang === "es" ? (c.es != null ? c.es : c.en) : lang === "fr" ? c.fr : c.en)}</div>
                  <RatingPill rating={f.rating} lang={lang} />
                  {canManage && (
                    <select className="input" value={f.rating || ""} style={{ fontSize: 11, marginLeft: "auto" }}
                      onChange={(e) => patchSheet("findings", { ...findings, [c.key]: { ...f, rating: e.target.value || undefined } })}>
                      <option value="">{L("— Appréciation —", "— Rating —")}</option>
                      {Object.keys(RATINGS).map((k) => (
                        <option key={k} value={k}>{(lang === "es" ? (RATINGS[k].es != null ? RATINGS[k].es : RATINGS[k].en) : lang === "fr" ? RATINGS[k].fr : RATINGS[k].en)}</option>
                      ))}
                    </select>
                  )}
                </div>
                <div className="text-faint" style={{ fontSize: 11.5, marginBottom: 6 }}>{(lang === "es" ? (c.hint_es != null ? c.hint_es : c.hint_en) : lang === "fr" ? c.hint_fr : c.hint_en)}</div>
                {linked.length > 0 && (
                  <div className="text-faint" style={{ fontSize: 11, marginBottom: 6 }}>
                    {L("Questions liées : ", "Linked questions: ")}{linked.map((r) => r.question).filter(Boolean).join(" · ") || "—"}
                  </div>
                )}
                <textarea className="input" rows={4} disabled={!canManage}
                  placeholder={L("Constats, données probantes, analyse…", "Findings, evidence, analysis…")}
                  style={{ width: "100%", resize: "vertical", fontSize: 12.5 }}
                  value={f.text || ""}
                  onChange={(e) => patchSheet("findings", { ...findings, [c.key]: { ...f, text: e.target.value } })} />
              </div>
            </div>
          );
        })}

        {/* ═ Conclusions & recommandations ═ */}
        {tab === "conclusions" && selected && (
          <div>
            <div style={sec("green", { marginBottom: 12 })}>
              <div>
                <div style={secT("green")}>{L("Conclusions", "Conclusions")}</div>
                <textarea className="input" rows={5} disabled={!canManage}
                  style={{ width: "100%", resize: "vertical", fontSize: 12.5 }}
                  value={conclusions.text || ""}
                  onChange={(e) => patchSheet("conclusions", { ...conclusions, text: e.target.value })} />
              </div>
            </div>
            <div style={sec("amber")}>
              <div>
                <div style={secT("amber")}>{L("Recommandations", "Recommendations")}</div>
                {recommendations.map((rec, i) => (
                  <div key={i} style={{ display: "grid", gridTemplateColumns: "44px 1fr 200px auto", gap: 8, alignItems: "start", padding: "6px 0", borderTop: "1px dashed var(--line)" }}>
                    <span style={{ fontSize: 12, fontWeight: 700, paddingTop: 6 }}>R{i + 1}</span>
                    <textarea className="input" rows={2} disabled={!canManage} value={rec.text || ""}
                      placeholder={L("Recommandation…", "Recommendation…")}
                      onChange={(e) => {
                        const next = recommendations.map((r, j) => (j === i ? { ...r, text: e.target.value } : r));
                        patchSheet("conclusions", { ...conclusions, recommendations: next });
                      }}
                      style={{ width: "100%", fontSize: 12, resize: "vertical" }} />
                    <input className="input" disabled={!canManage} value={rec.addressee || ""}
                      placeholder={L("Destinataire", "Addressee")}
                      onChange={(e) => {
                        const next = recommendations.map((r, j) => (j === i ? { ...r, addressee: e.target.value } : r));
                        patchSheet("conclusions", { ...conclusions, recommendations: next });
                      }}
                      style={{ fontSize: 11.5 }} />
                    {canManage && (
                      <button className="btn xs ghost" style={{ marginTop: 4 }}
                        onClick={() => patchSheet("conclusions", { ...conclusions, recommendations: recommendations.filter((_, j) => j !== i) })}>
                        <Icon.x />
                      </button>
                    )}
                  </div>
                ))}
                {canManage && (
                  <button className="btn xs ghost" style={{ marginTop: 8 }}
                    onClick={() => patchSheet("conclusions", { ...conclusions, recommendations: [...recommendations, {}] })}>
                    <Icon.plus /> {L("Ajouter une recommandation", "Add a recommendation")}
                  </button>
                )}
              </div>
            </div>
          </div>
        )}

        {/* ═ Réponse managériale ═ */}
        {tab === "response" && selected && (
          <div style={sec("purple")}>
            <div>
              <div className="text-faint" style={{ fontSize: 11.5, marginBottom: 10 }}>
                {L("Pour chaque recommandation (onglet précédent), la décision du management, le responsable, l'échéance et l'état de mise en œuvre.",
                   "For each recommendation (previous tab), the management decision, owner, due date and implementation status.")}
              </div>
              {recommendations.length === 0 && (
                <div className="text-faint" style={{ fontSize: 12 }}>
                  {L("Aucune recommandation définie pour le moment.", "No recommendation defined yet.")}
                </div>
              )}
              {recommendations.map((rec, i) => {
                const item = (response.items || {})[String(i)] || {};
                const setItem = (patch) => patchSheet("response", {
                  ...response,
                  items: { ...(response.items || {}), [String(i)]: { ...item, ...patch } },
                });
                return (
                  <div key={i} style={{ padding: "8px 0", borderTop: "1px dashed var(--line)" }}>
                    <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 6 }}>R{i + 1}. {rec.text || "—"}</div>
                    <div style={{ display: "grid", gridTemplateColumns: "170px 1fr 160px 130px 130px", gap: 8 }}>
                      <select className="input" disabled={!canManage} value={item.decision || ""}
                        onChange={(e) => setItem({ decision: e.target.value || undefined })} style={{ fontSize: 11.5 }}>
                        <option value="">{L("— Décision —", "— Decision —")}</option>
                        {Object.keys(RESPONSE_CHOICES).map((k) => (
                          <option key={k} value={k}>{(lang === "es" ? (RESPONSE_CHOICES[k].es != null ? RESPONSE_CHOICES[k].es : RESPONSE_CHOICES[k].en) : lang === "fr" ? RESPONSE_CHOICES[k].fr : RESPONSE_CHOICES[k].en)}</option>
                        ))}
                      </select>
                      <input className="input" disabled={!canManage} value={item.comment || ""}
                        placeholder={L("Commentaire / mesures prévues", "Comment / planned measures")}
                        onChange={(e) => setItem({ comment: e.target.value })} style={{ fontSize: 11.5 }} />
                      <input className="input" disabled={!canManage} value={item.responsible || ""}
                        placeholder={L("Responsable", "Responsible")}
                        onChange={(e) => setItem({ responsible: e.target.value })} style={{ fontSize: 11.5 }} />
                      <input type="date" className="input" disabled={!canManage} value={item.due || ""}
                        onChange={(e) => setItem({ due: e.target.value })} style={{ fontSize: 11.5 }} />
                      <select className="input" disabled={!canManage} value={item.status || "todo"}
                        onChange={(e) => setItem({ status: e.target.value })} style={{ fontSize: 11.5 }}>
                        {Object.keys(RESPONSE_STATUSES).map((k) => (
                          <option key={k} value={k}>{(lang === "es" ? (RESPONSE_STATUSES[k].es != null ? RESPONSE_STATUSES[k].es : RESPONSE_STATUSES[k].en) : lang === "fr" ? RESPONSE_STATUSES[k].fr : RESPONSE_STATUSES[k].en)}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {newOpen && (
          <NewPolicyEvalModal lang={lang} effectiveOrgId={effectiveOrgId}
            onClose={() => setNewOpen(false)}
            onCreated={(ev) => {
              setNewOpen(false);
              setSelectedId(ev.id);
              try { localStorage.setItem("melr.policy.selected", ev.id); } catch (_) {}
              refresh && refresh();
              setTab("framing");
            }} />
        )}
      </div>
    );
  }

  window.PolicyEvalScreen = PolicyEvalScreen;
})();
