/* global React, Icon, Modal, window */
// ============================================================================
// MELR · ÉVALUATIONS — registre transversal (phase 1)
// ----------------------------------------------------------------------------
// Point d'entrée du groupe ÉVALUATIONS : liste toutes les évaluations de
// l'organisation, tous types confondus (PEFA, ex ante, politiques
// publiques, …), avec leur cycle de vie commun. Chaque type est un module
// séparable (MODULE_CATALOG) — un client peut n'activer que PEFA.
//
// Design : PEFA/DESIGN-MODULE-EVALUATIONS.md. Phase 1 : seuls PEFA (nouveau)
// et Ex ante (module existant) sont actifs ; les autres types apparaissent
// dans le catalogue comme « à venir » (phase 4).
// ============================================================================

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

  // ── Conventions visuelles du groupe ÉVALUATIONS ─────────────────────────
  // Alignées sur MSC / Learning / Ex-ante et VALABLES POUR TOUS LES MODULES
  // À VENIR (décision utilisateur 2026-06-13) :
  //   - Sections teintées à bordure gauche colorée :
  //       amber  = outils / paramètres / workflow / formulaires d'ajout
  //       blue   = progression / KPIs
  //       green  = contenu principal / saisie
  //       purple = synthèse / qualité / comparaison
  //   - Boutons d'export pleins : Word bleu, PDF rouge, Excel vert
  //     (mêmes couleurs que ExanteCardExport).
  // Exposées sur window.MelrSection pour réutilisation (screens-pefa,
  // screens-policy-eval, futurs types).
  // Teintes en TRANSPARENCE (alpha sur le fond du thème) pour rester
  // lisibles en mode clair COMME en mode sombre : le texte garde les
  // variables du thème (var(--text)). Les titres basculent de nuance
  // selon le thème courant (recalculé à chaque rendu — le toggle dark
  // re-rend tous les écrans via tweaks).
  const SECTION_COLORS = {
    amber:  { tint: "rgba(217, 119, 6, 0.10)",  border: "#d97706", title: "#92400e", titleDark: "#fbbf24" },
    blue:   { tint: "rgba(59, 130, 246, 0.10)", border: "#3b82f6", title: "#1e40af", titleDark: "#93c5fd" },
    green:  { tint: "rgba(22, 163, 74, 0.10)",  border: "#16a34a", title: "#166534", titleDark: "#86efac" },
    purple: { tint: "rgba(147, 51, 234, 0.10)", border: "#9333ea", title: "#6b21a8", titleDark: "#d8b4fe" },
  };
  const isDarkTheme = () => typeof document !== "undefined"
    && document.documentElement.getAttribute("data-theme") === "dark";
  window.MelrSection = {
    colors: SECTION_COLORS,
    style: (c, extra) => ({
      background: SECTION_COLORS[c].tint,
      borderLeft: "4px solid " + SECTION_COLORS[c].border,
      borderRadius: 8, padding: "14px 16px", marginBottom: 14,
      ...(extra || {}),
    }),
    title: (c) => ({
      fontSize: 13.5, fontWeight: 800, margin: "0 0 8px",
      color: isDarkTheme() ? SECTION_COLORS[c].titleDark : SECTION_COLORS[c].title,
      display: "flex", alignItems: "center", gap: 8,
    }),
    // Boutons d'export pleins : MelrSection.btn("#2563eb") → Word, etc.
    btn: (bg) => ({
      padding: "7px 12px", borderRadius: 6, border: "1px solid " + bg,
      background: bg, color: "white", cursor: "pointer",
      fontWeight: 600, fontSize: 12,
    }),
    WORD: "#2563eb", PDF: "#dc2626", EXCEL: "#15803d",
  };

  // ── Catalogue des types d'évaluation ────────────────────────────────────
  // available: true  → créable / navigable dès maintenant
  // route            → écran spécialisé (sinon : registre seulement)
  const EVAL_TYPES = [
    { code: "pefa",            available: true,  route: "pefa",
      fr: "PEFA", en: "PEFA", es: "PEFA",
      desc_fr: "Dépense publique et responsabilité financière — cadre 2016 + modules Genre (GRPFM) et Climat (CRPFM).",
      desc_en: "Public Expenditure and Financial Accountability — 2016 framework + Gender (GRPFM) and Climate (CRPFM) modules." },
    { code: "exante",          available: true,  route: "exante", external: true,
      fr: "Évaluation ex ante", en: "Ex-ante appraisal", es: "Evaluación ex ante",
      desc_fr: "Analyse coût-bénéfice, multicritère et sensibilité avant démarrage (module existant).",
      desc_en: "Cost-benefit, multi-criteria and sensitivity analysis before start (existing module)." },
    { code: "policy",          available: true,  route: "policy",
      fr: "Politiques publiques", en: "Public policy", es: "Políticas públicas",
      desc_fr: "Les 6 critères OCDE/CAD 2019 : pertinence, cohérence, efficacité, efficience, impact, viabilité. Matrice d'évaluation, constats, réponse managériale.",
      desc_en: "The 6 OECD/DAC 2019 criteria: relevance, coherence, effectiveness, efficiency, impact, sustainability. Evaluation matrix, findings, management response." },
    { code: "midterm_final",   available: true,  route: "midterm",
      fr: "Mi-parcours & finale", en: "Mid-term & final", es: "Intermedia y final",
      desc_fr: "Revue à mi-vie ou en clôture : cadre logique prévu/réalisé, leçons apprises, réponse managériale.",
      desc_en: "Mid-life or closing review: planned vs actual logframe, lessons learned, management response." },
    { code: "impact_training", available: true,  route: "impact",
      fr: "Impact & formations", en: "Impact & training", es: "Impacto y formación",
      desc_fr: "Kirkpatrick 4 niveaux (+ ROI Phillips) pour les formations ; méthodes contrefactuelles pour l'impact.",
      desc_en: "Kirkpatrick 4 levels (+ Phillips ROI) for training; counterfactual methods for impact." },
    { code: "gfp_diag",        available: true,  route: "gfp_diag",
      fr: "Diagnostics GFP (TADAT, DeMPA, PIMA, MAPS)", en: "PFM diagnostics (TADAT, DeMPA, PIMA, MAPS)", es: "Diagnósticos GFP (TADAT, DeMPA, PIMA, MAPS)",
      desc_fr: "Administration fiscale, gestion de la dette, investissement public et marchés publics — moteur de notation commun, fidèle à chaque cadre officiel.",
      desc_en: "Tax administration, debt management, public investment and procurement — one scoring engine, faithful to each official framework." },
  ];
  const TYPE_BY_CODE = {};
  EVAL_TYPES.forEach((x) => { TYPE_BY_CODE[x.code] = x; });

  // Cycle de vie commun (aligné sur les 4 phases PEFA + clôture)
  const STATUS_META = {
    planning:  { fr: "Planification",      en: "Planning", es: "Planificación",      color: "#92400e", fill: "#fef3c7" },
    fieldwork: { fr: "Travail de terrain", en: "Fieldwork", es: "Trabajo de campo",     color: "#1d4ed8", fill: "#dbeafe" },
    reporting: { fr: "Rapport",            en: "Reporting", es: "Informe",     color: "#6b21a8", fill: "#ede9fe" },
    follow_up: { fr: "Suivi des réformes", en: "Follow-up", es: "Seguimiento de las reformas",     color: "#15803d", fill: "#dcfce7" },
    closed:    { fr: "Clôturée",           en: "Closed", es: "Cerrada",        color: "#6b7280", fill: "#f3f4f6" },
  };
  const STATUSES = ["planning", "fieldwork", "reporting", "follow_up", "closed"];

  function StatusBadge({ status, lang }) {
    const m = STATUS_META[status] || STATUS_META.planning;
    return (
      <span style={{
        display: "inline-block", padding: "2px 8px", borderRadius: 10,
        background: m.fill, color: m.color, fontSize: 11, fontWeight: 600,
      }}>{(lang === "es" ? (m.es != null ? m.es : m.en) : lang === "fr" ? m.fr : m.en)}</span>
    );
  }

  // ── Modale de création d'une évaluation PEFA ────────────────────────────
  // Partagée entre le registre et l'écran PEFA (window.NewPefaModal).
  function NewPefaModal({ lang, effectiveOrgId, onClose, onCreated }) {
    const { projects } = window.melr.useProjects ? window.melr.useProjects() : { projects: [] };
    const [titleFr, setTitleFr] = useState("");
    const [titleEn, setTitleEn] = useState("");
    const [level, setLevel] = useState("national");
    const [periodStart, setPeriodStart] = useState("");
    const [periodEnd, setPeriodEnd] = useState("");
    const [fiscalYears, setFiscalYears] = useState("");
    const [projectId, setProjectId] = useState("");
    const [withGender, setWithGender] = useState(false);
    const [withClimate, setWithClimate] = useState(false);
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState(null);

    const submit = async (e) => {
      e.preventDefault();
      if (!titleFr.trim()) { setErr(window.L("Le titre (FR) est requis.", "Title (FR) is required.", "El título (FR) es obligatorio.")); return; }
      setBusy(true); setErr(null);
      try {
        const years = fiscalYears.split(/[,;\s]+/).map((s) => s.trim()).filter(Boolean);
        const res = await window.melr.createPefaAssessment(effectiveOrgId, {
          title_fr: titleFr.trim(),
          title_en: titleEn.trim() || titleFr.trim(),
          government_level: level,
          period_start: periodStart || null,
          period_end:   periodEnd   || null,
          project_id:   projectId   || null,
          scope: { fiscal_years: years },
          modules: { gender: withGender, climate: withClimate },
        });
        if (onCreated) onCreated(res);
      } catch (ex) { setErr(ex.message); setBusy(false); }
    };

    const L = (fr, en) => (lang === "fr" ? fr : en);
    const lbl = { fontSize: 12, fontWeight: 600, display: "block", marginBottom: 4 };
    const row = { marginBottom: 12 };

    return (
      <Modal title={L("Nouvelle évaluation PEFA", "New PEFA assessment")} 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={row}>
          <label style={lbl}>{L("Titre (FR) *", "Title (FR) *")}</label>
          <input className="input" value={titleFr} onChange={(e) => setTitleFr(e.target.value)}
            placeholder={L("ex. PEFA Sénégal 2026", "e.g. PEFA Senegal 2026")} style={{ width: "100%" }} />
        </div>
        <div style={row}>
          <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, ...row }}>
          <div>
            <label style={lbl}>{L("Niveau", "Level")}</label>
            <select className="input" value={level} onChange={(e) => setLevel(e.target.value)} style={{ width: "100%" }}>
              <option value="national">{L("National", "National")}</option>
              <option value="subnational">{L("Infranational", "Subnational")}</option>
            </select>
          </div>
          <div>
            <label style={lbl}>{L("Exercices couverts", "Fiscal years covered")}</label>
            <input className="input" value={fiscalYears} onChange={(e) => setFiscalYears(e.target.value)}
              placeholder="2023, 2024, 2025" style={{ width: "100%" }} />
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, ...row }}>
          <div>
            <label style={lbl}>{L("Début (prévu)", "Start (planned)")}</label>
            <input type="date" className="input" value={periodStart} onChange={(e) => setPeriodStart(e.target.value)} style={{ width: "100%" }} />
          </div>
          <div>
            <label style={lbl}>{L("Fin (prévue)", "End (planned)")}</label>
            <input type="date" className="input" value={periodEnd} onChange={(e) => setPeriodEnd(e.target.value)} style={{ width: "100%" }} />
          </div>
        </div>
        <div style={row}>
          <label style={lbl}>{L("Projet lié (optionnel)", "Linked project (optional)")}</label>
          {/* useProjects() remappe les lignes : uuid = UUID Supabase (clé
              étrangère), id = CODE projet, nameFr/nameEn (camelCase). */}
          <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>
        <div style={{ ...row, padding: "10px 12px", background: "var(--bg-sunken)", borderRadius: 8 }}>
          <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 6 }}>
            {L("Modules complémentaires", "Supplementary modules")}
          </div>
          <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, marginBottom: 4 }}>
            <input type="checkbox" checked={withGender} onChange={(e) => setWithGender(e.target.checked)} />
            {L("Genre — GRPFM 2020 (9 indicateurs)", "Gender — GRPFM 2020 (9 indicators)")}
          </label>
          <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
            <input type="checkbox" checked={withClimate} onChange={(e) => setWithClimate(e.target.checked)} />
            {L("Climat — CRPFM 2024 (14 indicateurs)", "Climate — CRPFM 2024 (14 indicators)")}
          </label>
          <div className="text-faint" style={{ fontSize: 11, marginTop: 6 }}>
            {L("Modifiable ensuite dans la note conceptuelle (section Ensemble d'indicateurs).",
               "Can be changed later in the concept note (Indicator set section).")}
          </div>
        </div>
        {err && <div style={{ color: "#b91c1c", fontSize: 12 }}>{err}</div>}
      </Modal>
    );
  }
  window.NewPefaModal = NewPefaModal;

  // ── Écran registre ───────────────────────────────────────────────────────
  function EvaluationsRegistry({ lang, setRoute, effectiveOrgId, isSuperAdmin, hasPerm }) {
    const { data: evals, loading } = window.melr.useEvaluations
      ? window.melr.useEvaluations(effectiveOrgId)
      : { data: [], loading: false };
    const [typeFilter, setTypeFilter] = useState("__all__");
    const [statusFilter, setStatusFilter] = useState("__all__");
    const [newPefaOpen, setNewPefaOpen] = useState(false);

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

    const L = (fr, en) => (lang === "fr" ? fr : en);

    const filtered = useMemo(() => {
      let r = evals || [];
      if (typeFilter !== "__all__")   r = r.filter((x) => x.type === typeFilter);
      if (statusFilter !== "__all__") r = r.filter((x) => x.status === statusFilter);
      return r;
    }, [evals, typeFilter, statusFilter]);

    const openEvaluation = (ev) => {
      if (ev.type === "pefa") {
        const pa = Array.isArray(ev.pefa_assessments) ? ev.pefa_assessments[0] : ev.pefa_assessments;
        if (pa && pa.id) { try { localStorage.setItem("melr.pefa.selected", pa.id); } catch (_) {} }
        setRoute && setRoute("pefa");
        return;
      }
      if (ev.type === "policy") {
        try { localStorage.setItem("melr.policy.selected", ev.id); } catch (_) {}
        setRoute && setRoute("policy");
        return;
      }
      if (ev.type === "impact_training") {
        try { localStorage.setItem("melr.impact.selected", ev.id); } catch (_) {}
        setRoute && setRoute("impact");
        return;
      }
      if (ev.type === "midterm_final") {
        try { localStorage.setItem("melr.midterm.selected", ev.id); } catch (_) {}
        setRoute && setRoute("midterm");
        return;
      }
      if (ev.type === "gfp_diag") {
        try { localStorage.setItem("melr.gfpdiag.selected", ev.id); } catch (_) {}
        setRoute && setRoute("gfp_diag");
      }
    };

    const onTypeCardClick = (ty) => {
      if (!ty.available) return;
      if (ty.code === "pefa") { setRoute && setRoute("pefa"); return; }
      if (ty.route) setRoute && setRoute(ty.route);
    };

    return (
      <div className="page" data-screen-label="Evaluations / Registry">
        <div className="page-header">
          <div className="page-eyebrow">{L("ÉVALUATIONS", "EVALUATIONS")}</div>
          <div className="page-header-row">
            <div>
              <h1 className="page-title">{L("Registre des évaluations", "Evaluations registry")}</h1>
              <div className="page-sub">
                {L("Toutes les évaluations de l'organisation, tous types confondus. Chaque type est un module activable séparément.",
                   "All the organization's evaluations, across all types. Each type is a separately activatable module.")}
              </div>
            </div>
            <div className="page-header-actions">
              {canManage && (
                <button className="btn sm primary" onClick={() => setNewPefaOpen(true)}>
                  <Icon.plus /> {L("Nouvelle évaluation PEFA", "New PEFA assessment")}
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Catalogue des types */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(290px, 1fr))", gap: 12, marginBottom: 18 }}>
          {EVAL_TYPES.map((ty) => (
            <div key={ty.code}
              onClick={() => onTypeCardClick(ty)}
              style={{
                background: "var(--bg-elev)", border: "1px solid var(--line)", borderRadius: 10,
                padding: "14px 16px", cursor: ty.available ? "pointer" : "default",
                opacity: ty.available ? 1 : 0.62,
              }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                <div style={{ fontWeight: 700, fontSize: 13.5 }}>{(lang === "es" ? (ty.es != null ? ty.es : ty.en) : lang === "fr" ? ty.fr : ty.en)}</div>
                {ty.available
                  ? <span style={{ fontSize: 10.5, fontWeight: 700, color: "#15803d", background: "#dcfce7", padding: "2px 8px", borderRadius: 999 }}>
                      {L("Disponible", "Available")}
                    </span>
                  : <span style={{ fontSize: 10.5, fontWeight: 700, color: "#6b7280", background: "#f3f4f6", padding: "2px 8px", borderRadius: 999 }}>
                      {L("À venir", "Coming soon")}
                    </span>}
              </div>
              <div className="text-faint" style={{ fontSize: 11.5, marginTop: 6, lineHeight: 1.45 }}>
                {(lang === "es" ? (ty.desc_es != null ? ty.desc_es : ty.desc_en) : lang === "fr" ? ty.desc_fr : ty.desc_en)}
              </div>
            </div>
          ))}
        </div>

        {/* Filtres */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center", marginBottom: 12 }}>
          <select className="input" value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)}>
            <option value="__all__">{L("Tous les types", "All types")}</option>
            {EVAL_TYPES.filter((x) => !x.external).map((x) => (
              <option key={x.code} value={x.code}>{(lang === "es" ? (x.es != null ? x.es : x.en) : lang === "fr" ? x.fr : x.en)}</option>
            ))}
          </select>
          <select className="input" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
            <option value="__all__">{L("Tous les statuts", "All statuses")}</option>
            {STATUSES.map((s) => (
              <option key={s} value={s}>{(lang === "es" ? (STATUS_META[s].es != null ? STATUS_META[s].es : STATUS_META[s].en) : lang === "fr" ? STATUS_META[s].fr : STATUS_META[s].en)}</option>
            ))}
          </select>
          <div className="text-faint" style={{ fontSize: 11.5 }}>
            {filtered.length} {L("évaluation(s)", "evaluation(s)")}
          </div>
        </div>

        {/* Liste (green = contenu principal — convention MelrSection) */}
        <div style={window.MelrSection.style("green")}>
          <div>
            <table className="tbl" style={{ width: "100%" }}>
              <thead>
                <tr>
                  <th>{L("Type", "Type")}</th>
                  <th>{L("Titre", "Title")}</th>
                  <th>{L("Période", "Period")}</th>
                  <th>{L("Projet", "Project")}</th>
                  <th>{L("Statut", "Status")}</th>
                </tr>
              </thead>
              <tbody>
                {loading && (
                  <tr><td colSpan={5} style={{ padding: 18, color: "var(--text-faint)" }}>{L("Chargement…", "Loading…")}</td></tr>
                )}
                {!loading && filtered.length === 0 && (
                  <tr><td colSpan={5} style={{ padding: 18, color: "var(--text-faint)" }}>
                    {L("Aucune évaluation. Créez la première avec « Nouvelle évaluation PEFA ».",
                       "No evaluation yet. Create the first one with “New PEFA assessment”.")}
                  </td></tr>
                )}
                {filtered.map((ev) => {
                  const ty = TYPE_BY_CODE[ev.type];
                  return (
                    <tr key={ev.id} onClick={() => openEvaluation(ev)}
                      style={{ cursor: (ev.type === "pefa" || ev.type === "policy" || ev.type === "impact_training" || ev.type === "midterm_final" || ev.type === "gfp_diag") ? "pointer" : "default" }}>
                      <td style={{ fontWeight: 600, fontSize: 12.5 }}>{ty ? ((lang === "es" ? (ty.es != null ? ty.es : ty.en) : lang === "fr" ? ty.fr : ty.en)) : ev.type}</td>
                      <td style={{ fontSize: 12.5 }}>{(lang === "es" ? (ev.title_es != null ? ev.title_es : ev.title_en || ev.title_fr) : lang === "fr" ? ev.title_fr : ev.title_en || ev.title_fr)}</td>
                      <td style={{ fontSize: 12 }}>
                        {(ev.period_start || "—")}{ev.period_end ? " → " + ev.period_end : ""}
                      </td>
                      <td style={{ fontSize: 12 }}>{ev.projects ? ev.projects.code : "—"}</td>
                      <td><StatusBadge status={ev.status} lang={lang} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {newPefaOpen && (
          <NewPefaModal lang={lang} effectiveOrgId={effectiveOrgId}
            onClose={() => setNewPefaOpen(false)}
            onCreated={(res) => {
              setNewPefaOpen(false);
              try { localStorage.setItem("melr.pefa.selected", res.assessment.id); } catch (_) {}
              setRoute && setRoute("pefa");
            }} />
        )}
      </div>
    );
  }

  window.EvaluationsRegistry = EvaluationsRegistry;
  window.EVALUATION_STATUS_META = STATUS_META;
})();
