/* global React */
// ==================== SECTORS & PROJECTS — shared data ====================

const SECTORS = [
  { id: "sante",       fr: "Santé",                 en: "Health",                color: "oklch(0.58 0.18 25)",  bg: "oklch(0.96 0.04 25)",  icon: "heart" },
  { id: "nutrition",   fr: "Nutrition",             en: "Nutrition",             color: "oklch(0.62 0.16 55)",  bg: "oklch(0.96 0.05 55)",  icon: "scale" },
  { id: "vih",         fr: "VIH-SIDA",              en: "HIV-AIDS",              color: "oklch(0.55 0.17 350)", bg: "oklch(0.96 0.05 350)", icon: "shieldHalf" },
  { id: "education",   fr: "Éducation",             en: "Education",             color: "oklch(0.50 0.17 256)", bg: "oklch(0.96 0.04 256)", icon: "brain" },
  { id: "peche",       fr: "Pêche",                 en: "Fisheries",             color: "oklch(0.55 0.13 195)", bg: "oklch(0.96 0.04 195)", icon: "wifi" },
  { id: "agriculture", fr: "Agriculture",           en: "Agriculture",           color: "oklch(0.55 0.14 145)", bg: "oklch(0.96 0.04 145)", icon: "trees" },
  { id: "finances",    fr: "Finances publiques",    en: "Public finance",        color: "oklch(0.55 0.15 290)", bg: "oklch(0.96 0.04 290)", icon: "euro" },
  { id: "gouvernance", fr: "Gouvernance",           en: "Governance",            color: "oklch(0.42 0.04 250)", bg: "oklch(0.95 0.01 250)", icon: "building" },
  { id: "eau",         fr: "Eau & assainissement",  en: "Water & sanitation",    color: "oklch(0.55 0.12 220)", bg: "oklch(0.96 0.04 220)", icon: "thermometer" },
  { id: "energie",     fr: "Énergie",               en: "Energy",                color: "oklch(0.62 0.15 75)",  bg: "oklch(0.96 0.06 75)",  icon: "zap" },
  { id: "genre",       fr: "Genre & inclusion",     en: "Gender & inclusion",    color: "oklch(0.55 0.16 12)",  bg: "oklch(0.96 0.05 12)",  icon: "users" },
  { id: "port",        fr: "Gestion portuaire",     en: "Port management",       color: "oklch(0.45 0.12 240)", bg: "oklch(0.95 0.04 240)", icon: "building" },
];

function sectorById(id) { return SECTORS.find((s) => s.id === id) || SECTORS[0]; }
function sectorLabel(s, lang) { return lang === "en" ? s.en : s.fr; }

// 12 diverse projects across sectors
const PROJECTS = [
  { id: "P-241", sector: "sante",       nameFr: "Renforcement santé primaire Sahel",                  nameEn: "Sahel Primary Health Strengthening",         countriesFr: "Mali · BF · Niger",       countriesEn: "Mali · BF · Niger",       lead: "Aïssata Diallo",   status: "active",    progress: 64, budget: 3.36, disbursed: 2.15, indic: 28, sites: 42, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "warn", donor: "AFD · UE · Gavi" },
  { id: "P-188", sector: "nutrition",   nameFr: "Nutrition scolaire & cantines",                       nameEn: "School nutrition & canteens",                 countriesFr: "Burkina Faso · Niger",      countriesEn: "Burkina Faso · Niger",    lead: "Halima Issoufou",  status: "active",    progress: 82, budget: 1.84, disbursed: 1.51, indic: 18, sites: 26, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "ok",   donor: "WFP · UNICEF · AFD" },
  { id: "P-302", sector: "agriculture", nameFr: "Filière riz irrigué — Office du Niger",               nameEn: "Irrigated rice value chain",                  countriesFr: "Mali",                      countriesEn: "Mali",                    lead: "Modibo Keïta",     status: "active",    progress: 41, budget: 4.80, disbursed: 1.98, indic: 22, sites: 18, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "ok",   donor: "AFD · BAD · FIDA" },
  { id: "P-415", sector: "peche",       nameFr: "Modernisation pêche artisanale littorale",            nameEn: "Coastal artisanal fisheries modernization",   countriesFr: "Sénégal · Mauritanie",      countriesEn: "Senegal · Mauritania",    lead: "Ousmane Sarr",     status: "appraisal", progress: 12, budget: 4.20, disbursed: 0.18, indic: 0,  sites: 0,  phaseFr: "Évaluation ex ante",    phaseEn: "Ex-ante appraisal", risk: "warn", donor: "AFD · UE" },
  { id: "P-156", sector: "education",   nameFr: "Numérique éducatif rural — collèges",                 nameEn: "Rural ed-tech for middle schools",            countriesFr: "BF · Togo · Bénin",         countriesEn: "BF · Togo · Benin",       lead: "Salif Ouédraogo",  status: "active",    progress: 73, budget: 2.95, disbursed: 2.10, indic: 24, sites: 34, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "ok",   donor: "AFD · Banque mondiale" },
  { id: "P-098", sector: "finances",    nameFr: "Modernisation administration fiscale",                nameEn: "Tax administration modernization",            countriesFr: "Mauritanie",                countriesEn: "Mauritania",              lead: "Fatima Ould Cheikh", status: "active",  progress: 56, budget: 6.20, disbursed: 3.10, indic: 14, sites: 8,  phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "warn", donor: "FMI · BAD · UE" },
  { id: "P-377", sector: "eau",         nameFr: "Eau & assainissement centres santé",                  nameEn: "WASH in health facilities",                   countriesFr: "Tchad",                     countriesEn: "Chad",                    lead: "Mahamat Saleh",    status: "active",    progress: 28, budget: 2.60, disbursed: 0.62, indic: 16, sites: 19, phaseFr: "Démarrage",             phaseEn: "Inception",       risk: "bad",  donor: "UNICEF · AFD" },
  { id: "P-220", sector: "vih",         nameFr: "Prévention TARV jeunes urbains",                       nameEn: "ART prevention for urban youth",              countriesFr: "Côte d'Ivoire · Ghana",     countriesEn: "Ivory Coast · Ghana",     lead: "Aminata Coulibaly", status: "active",  progress: 38, budget: 1.45, disbursed: 0.51, indic: 12, sites: 24, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "warn", donor: "Fonds mondial · PEPFAR" },
  { id: "P-462", sector: "gouvernance", nameFr: "Décentralisation & redevabilité communale",            nameEn: "Decentralization & municipal accountability", countriesFr: "Régional · 6 pays",          countriesEn: "Regional · 6 countries",  lead: "Karim Bensaad",    status: "active",    progress: 55, budget: 5.80, disbursed: 3.20, indic: 36, sites: 78, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "warn", donor: "UE · GIZ · AFD" },
  { id: "P-507", sector: "genre",       nameFr: "Autonomisation économique des femmes rurales",         nameEn: "Rural women economic empowerment",            countriesFr: "Sénégal · Mali",            countriesEn: "Senegal · Mali",          lead: "Mariama Bâ",       status: "active",    progress: 47, budget: 2.10, disbursed: 0.98, indic: 19, sites: 32, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "ok",   donor: "ONU Femmes · AFD" },
  { id: "P-491", sector: "energie",     nameFr: "Mini-réseaux solaires ruraux",                         nameEn: "Rural solar mini-grids",                      countriesFr: "Niger · Mali",              countriesEn: "Niger · Mali",            lead: "Boubacar Touré",   status: "active",    progress: 35, budget: 7.40, disbursed: 2.60, indic: 16, sites: 48, phaseFr: "Mise en œuvre",        phaseEn: "Implementation",  risk: "ok",   donor: "AFD · BEI · KfW" },
  { id: "P-538", sector: "agriculture", nameFr: "Pastoralisme transfrontalier Sahel",                  nameEn: "Cross-border Sahel pastoralism",              countriesFr: "BF · Niger · Tchad",         countriesEn: "BF · Niger · Chad",       lead: "Yacouba Sanou",    status: "closing",   progress: 96, budget: 1.20, disbursed: 1.18, indic: 14, sites: 22, phaseFr: "Clôture",               phaseEn: "Closing",         risk: "ok",   donor: "AFD · FIDA" },
  { id: "P-612", sector: "port",        nameFr: "Modernisation du Port autonome de Dakar",             nameEn: "Modernization of Dakar Autonomous Port",       countriesFr: "Sénégal",                   countriesEn: "Senegal",                 lead: "Cheikh Anta Mbaye", status: "active",    progress: 52, budget: 8.40, disbursed: 4.20, indic: 21, sites: 6,  phaseFr: "Mise en œuvre",         phaseEn: "Implementation",  risk: "warn", donor: "AFD · BEI · Banque mondiale" },
  { id: "P-619", sector: "port",        nameFr: "Concession terminal à conteneurs Lomé",                nameEn: "Lomé container terminal concession",          countriesFr: "Togo",                       countriesEn: "Togo",                    lead: "Komlan Aziamblé",   status: "appraisal", progress: 18, budget: 12.60, disbursed: 0.84, indic: 0,  sites: 1,  phaseFr: "Évaluation ex ante",     phaseEn: "Ex-ante appraisal", risk: "warn", donor: "BAD · IFC" },
];

function projectName(p, lang) { return lang === "en" ? p.nameEn : p.nameFr; }
function projectCountries(p, lang) { return lang === "en" ? p.countriesEn : p.countriesFr; }
function projectPhase(p, lang) { return lang === "en" ? p.phaseEn : p.phaseFr; }

// ============================================================================
// NEW-SECTOR MODAL — reusable add-sector flow
// ----------------------------------------------------------------------------
// Used by every form that picks a sector (CreateProjectModal, NewProgrammeModal,
// EditProgrammeModal, indicator-definitions editor…). Renders a small modal
// asking for FR/EN name + optional colour family, calls sectorsCrud.create,
// then hands the freshly-created sector back to its parent so the dropdown
// can re-select it. Realtime on public.sectors makes the new entry appear
// automatically in any other open form as well.
//
// Note: this file pre-loads BEFORE melr-data.jsx, but the modal only fires
// on a user gesture (form submit), by which time window.melr.sectorsCrud
// is guaranteed to be ready.
// ============================================================================

// Palette of pre-baked colour pairs so the user doesn't have to think about
// OKLCH triplets. Each pair has a friendly label for the picker.
const SECTOR_COLOR_PALETTE = [
  { key: "blue",    fr: "Bleu",      en: "Blue",      color: "oklch(0.50 0.17 256)", bg: "oklch(0.96 0.04 256)" },
  { key: "teal",    fr: "Sarcelle",  en: "Teal",      color: "oklch(0.55 0.12 195)", bg: "oklch(0.96 0.04 195)" },
  { key: "green",   fr: "Vert",      en: "Green",     color: "oklch(0.55 0.14 145)", bg: "oklch(0.96 0.04 145)" },
  { key: "amber",   fr: "Ambre",     en: "Amber",     color: "oklch(0.62 0.15 75)",  bg: "oklch(0.96 0.06 75)"  },
  { key: "red",     fr: "Rouge",     en: "Red",       color: "oklch(0.58 0.18 25)",  bg: "oklch(0.96 0.04 25)"  },
  { key: "pink",    fr: "Rose",      en: "Pink",      color: "oklch(0.55 0.16 12)",  bg: "oklch(0.96 0.05 12)"  },
  { key: "purple",  fr: "Violet",    en: "Purple",    color: "oklch(0.55 0.15 290)", bg: "oklch(0.96 0.04 290)" },
  { key: "magenta", fr: "Magenta",   en: "Magenta",   color: "oklch(0.55 0.17 350)", bg: "oklch(0.96 0.05 350)" },
  { key: "slate",   fr: "Ardoise",   en: "Slate",     color: "oklch(0.42 0.04 250)", bg: "oklch(0.95 0.01 250)" },
];

function NewSectorModal({ lang, onClose, onCreated }) {
  const { useState } = React;
  const [nameFr, setNameFr]   = useState("");
  const [nameEn, setNameEn]   = useState("");
  const [paletteKey, setPaletteKey] = useState("blue");
  const [busy, setBusy]       = useState(false);
  const [err, setErr]         = useState(null);

  const palette = SECTOR_COLOR_PALETTE.find((p) => p.key === paletteKey) || SECTOR_COLOR_PALETTE[0];

  const submit = async (e) => {
    e.preventDefault();
    setErr(null);
    if (!nameFr.trim()) {
      setErr(lang === "fr" ? "Le nom FR est requis." : "FR name is required.");
      return;
    }
    setBusy(true);
    try {
      const created = await window.melr.sectorsCrud.create({
        name_fr: nameFr.trim(),
        name_en: nameEn.trim() || null,
        color:   palette.color,
        bg:      palette.bg,
        icon:    "building",
      });
      if (onCreated) await onCreated(created);
      onClose();
    } catch (e2) {
      setErr(e2.message || String(e2));
    } finally {
      setBusy(false);
    }
  };

  const inp = { padding: "8px 10px", borderRadius: 6, border: "1px solid var(--line)", fontSize: 13, background: "var(--bg, white)", color: "var(--text)" };
  const lbl = { fontSize: 11, opacity: 0.75 };

  // Use the shared <Modal> wrapper (defined in modal.jsx — loaded before
  // this file in MELR.html). Provides Escape-to-close, body scroll lock,
  // focus restoration and ARIA labelling for free.
  return (
    <window.Modal
      title={lang === "fr" ? "Nouveau secteur" : "New sector"}
      onClose={onClose}
      onSubmit={submit}
      footer={<>
        <button type="button" className="btn sm ghost" onClick={onClose} disabled={busy}>
          {lang === "fr" ? "Annuler" : "Cancel"}
        </button>
        <button type="submit" className="btn sm primary" disabled={busy}>
          {busy
            ? (lang === "fr" ? "Création…" : "Creating…")
            : (lang === "fr" ? "Créer le secteur" : "Create sector")}
        </button>
      </>}>
      <div style={{ display: "grid", gap: 12 }}>
        <div style={{ fontSize: 12, opacity: 0.75 }}>
          {lang === "fr"
            ? "Le nouveau secteur sera visible par toutes les organisations de la plateforme."
            : "The new sector will be visible to every organisation on the platform."}
        </div>
        <label style={{ display: "grid", gap: 4 }}>
          <span style={lbl}>{lang === "fr" ? "Nom (FR) *" : "Name (FR) *"}</span>
          <input required value={nameFr} onChange={(e) => setNameFr(e.target.value)}
            placeholder={lang === "fr" ? "Biodiversité · Cybersécurité · Mines · …" : "Biodiversity · Cybersecurity · Mining · …"}
            style={inp} autoFocus />
        </label>
        <label style={{ display: "grid", gap: 4 }}>
          <span style={lbl}>{lang === "fr" ? "Nom (EN, optionnel)" : "Name (EN, optional)"}</span>
          <input value={nameEn} onChange={(e) => setNameEn(e.target.value)}
            placeholder={lang === "fr" ? "Biodiversity · Cybersecurity · Mining · …" : "Same as FR if empty"}
            style={inp} />
        </label>
        <div style={{ display: "grid", gap: 4 }}>
          <span style={lbl}>{lang === "fr" ? "Couleur (pour les chips et Gantt)" : "Colour (for chips and Gantt)"}</span>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {SECTOR_COLOR_PALETTE.map((p) => (
              <button key={p.key} type="button"
                onClick={() => setPaletteKey(p.key)}
                title={lang === "fr" ? p.fr : p.en}
                style={{
                  width: 30, height: 30, borderRadius: 6, cursor: "pointer",
                  border: paletteKey === p.key ? "2px solid var(--text)" : "1px solid var(--line)",
                  background: p.bg,
                  position: "relative",
                }}>
                <span style={{
                  display: "block", width: 12, height: 12, borderRadius: "50%",
                  background: p.color, margin: "0 auto",
                }} />
              </button>
            ))}
          </div>
          <div style={{ marginTop: 4 }}>
            <span style={{
              display: "inline-block", padding: "2px 10px", borderRadius: 10,
              background: palette.bg, color: palette.color, fontSize: 12,
              border: "1px solid " + palette.color,
            }}>
              {nameFr.trim() || (lang === "fr" ? "Aperçu" : "Preview")}
            </span>
          </div>
        </div>
        {err && (
          <div style={{ color: "#b91c1c", fontSize: 12 }}>{err}</div>
        )}
      </div>
    </window.Modal>
  );
}

Object.assign(window, { SECTORS, PROJECTS, sectorById, sectorLabel, projectName, projectCountries, projectPhase, NewSectorModal });
