/* global React, Icon, Modal, sectorById, NewSectorModal */
const { useState: useStateSEC, useEffect: useEffectSEC } = React;

// ============================================================================
// SECTORS MANAGEMENT — super-admin screen
// ----------------------------------------------------------------------------
// Lets a platform super-admin rename, recolour and add sectors. Sectors are
// universal labels used everywhere (projects, programmes, indicators) so
// changes propagate automatically via the existing realtime channel on
// public.sectors (useSectors() refreshes every consumer immediately).
//
// Permission model:
//   • Visible only when isSuperAdmin === true (Sidebar already filters via
//     the `superAdminOnly` flag on the NAV entry).
//   • Even if a non-super-admin reaches the URL, the RLS on public.sectors
//     would refuse any UPDATE / DELETE coming from them (see sectors.sql),
//     so the screen is defence-in-depth.
//
// Built-in vs custom:
//   • is_builtin = true → seeded by the platform (the 12 originals: Santé,
//     Nutrition, …). Can be RENAMED + RECOLOURED by super-admin but cannot
//     be DELETED.
//   • is_builtin = false → created by an admin via the "+ Nouveau secteur"
//     flow. Can be renamed, recoloured and archived by super-admin.
// ============================================================================

// Pre-baked colour palette (same 9 pairs as NewSectorModal so colours stay
// consistent across the app).
const SECTOR_PALETTE_SEC = [
  { key: "blue",    fr: "Bleu",     en: "Blue", es: "Azul",     color: "oklch(0.50 0.17 256)", bg: "oklch(0.96 0.04 256)" },
  { key: "teal",    fr: "Sarcelle", en: "Teal", es: "Verde azulado",     color: "oklch(0.55 0.12 195)", bg: "oklch(0.96 0.04 195)" },
  { key: "green",   fr: "Vert",     en: "Green", es: "Verde",    color: "oklch(0.55 0.14 145)", bg: "oklch(0.96 0.04 145)" },
  { key: "amber",   fr: "Ambre",    en: "Amber", es: "Ámbar",    color: "oklch(0.62 0.15 75)",  bg: "oklch(0.96 0.06 75)"  },
  { key: "red",     fr: "Rouge",    en: "Red", es: "Rojo",      color: "oklch(0.58 0.18 25)",  bg: "oklch(0.96 0.04 25)"  },
  { key: "pink",    fr: "Rose",     en: "Pink", es: "Rosa",     color: "oklch(0.55 0.16 12)",  bg: "oklch(0.96 0.05 12)"  },
  { key: "purple",  fr: "Violet",   en: "Purple", es: "Violeta",   color: "oklch(0.55 0.15 290)", bg: "oklch(0.96 0.04 290)" },
  { key: "magenta", fr: "Magenta",  en: "Magenta", es: "Magenta",  color: "oklch(0.55 0.17 350)", bg: "oklch(0.96 0.05 350)" },
  { key: "slate",   fr: "Ardoise",  en: "Slate", es: "Pizarra",    color: "oklch(0.42 0.04 250)", bg: "oklch(0.95 0.01 250)" },
];

function SectorsManagement({ t, lang, isSuperAdmin }) {
  const { data: sectors, loading, refresh } = window.melr.useSectors();
  const [editing, setEditing]   = useStateSEC(null); // sector being edited
  const [newOpen, setNewOpen]   = useStateSEC(false);
  const [busy, setBusy]         = useStateSEC(null);
  const [toast, setToast]       = useStateSEC(null);
  const [filterKind, setFilterKind] = useStateSEC("all"); // all | builtin | custom

  const showToast = (ok, msg, ttl) => {
    setToast({ ok, msg });
    setTimeout(() => setToast(null), ttl || 4000);
  };

  if (!isSuperAdmin) {
    return (
      <div className="page">
        <div className="page-header">
          <div className="page-eyebrow">{window.L("ACCÈS REFUSÉ", "ACCESS DENIED", "ACCESO DENEGADO")}</div>
          <h1 className="page-title">{window.L("Gestion des secteurs", "Sectors management", "Gestión de los sectores")}</h1>
        </div>
        <div className="page-body">
          <div className="card" style={{ padding: 24, textAlign: "center" }}>
            <div className="text-faint">
              {window.L("Cette page est réservée aux super-administrateurs de la plateforme.", "This page is restricted to platform super-administrators.", "Esta página está reservada a los superadministradores de la plataforma.")}
            </div>
          </div>
        </div>
      </div>
    );
  }

  const visible = sectors.filter((s) => {
    if (filterKind === "builtin") return !!s.is_builtin;
    if (filterKind === "custom")  return !s.is_builtin;
    return true;
  });

  const onArchive = async (s) => {
    if (s.is_builtin) {
      window.alert(window.L("Les secteurs intégrés (système) ne peuvent pas être supprimés. Vous pouvez les renommer ou les recolorer.", "Built-in (system) sectors cannot be deleted. You can rename or recolour them.", "Los sectores integrados (del sistema) no pueden eliminarse. Puede renombrarlos o cambiarles el color."));
      return;
    }
    if (!window.confirm(window.L(`Archiver le secteur « ${s.fr} » ? Les projets et indicateurs qui s'y rattachent ne seront pas supprimés ; le secteur disparaîtra simplement des listes de choix.`, `Archive the sector "${s.en || s.fr}"? Linked projects / indicators stay; the sector just disappears from picker lists.`, `¿Archivar el sector «${s.en || s.fr}»? Los proyectos e indicadores vinculados no se eliminarán; el sector simplemente desaparecerá de las listas de selección.`))) return;
    setBusy(s.id);
    try {
      const sb = window.melr.supabase;
      const r = await sb.from("sectors").update({ archived_at: new Date().toISOString() }).eq("id", s.id);
      if (r.error) throw new Error(r.error.message);
      showToast(true, window.L("✓ Secteur archivé", "✓ Sector archived", "✓ Sector archivado"));
      refresh();
    } catch (e) {
      showToast(false, (window.L("Erreur : ", "Error: ", "Error: ")) + e.message, 7000);
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-eyebrow">
          🛡 {window.L("SUPER-ADMIN · CATALOGUE TRANSVERSE", "SUPER-ADMIN · CROSS-CUT CATALOGUE", "SUPERADMIN · CATÁLOGO TRANSVERSAL")}
        </div>
        <div className="page-header-row">
          <div>
            <h1 className="page-title">{window.L("Gestion des secteurs", "Sectors management", "Gestión de los sectores")}</h1>
            <div className="page-sub">
              {window.L(`${sectors.length} secteur${sectors.length > 1 ? "s" : ""} actif${sectors.length > 1 ? "s" : ""} · ${sectors.filter((s) => s.is_builtin).length} intégré${sectors.filter((s) => s.is_builtin).length > 1 ? "s" : ""} · ${sectors.filter((s) => !s.is_builtin).length} personnalisé${sectors.filter((s) => !s.is_builtin).length > 1 ? "s" : ""}`, `${sectors.length} active sector${sectors.length > 1 ? "s" : ""} · ${sectors.filter((s) => s.is_builtin).length} built-in · ${sectors.filter((s) => !s.is_builtin).length} custom`, `${sectors.length} sector${sectors.length > 1 ? "es" : ""} activo${sectors.length > 1 ? "s" : ""} · ${sectors.filter((s) => s.is_builtin).length} integrado${sectors.filter((s) => s.is_builtin).length > 1 ? "s" : ""} · ${sectors.filter((s) => !s.is_builtin).length} personalizado${sectors.filter((s) => !s.is_builtin).length > 1 ? "s" : ""}`)}
            </div>
          </div>
          <div className="page-header-actions">
            <button className="btn sm primary" onClick={() => setNewOpen(true)}>
              <Icon.plus /> {window.L("Nouveau secteur", "New sector", "Nuevo sector")}
            </button>
          </div>
        </div>
        <div className="page-tabs">
          {[
            { k: "all",     l: window.L("Tous", "All", "Todos"),      n: sectors.length },
            { k: "builtin", l: window.L("Intégrés", "Built-in", "Integrados"), n: sectors.filter((s) => s.is_builtin).length },
            { k: "custom",  l: window.L("Personnalisés", "Custom", "Personalizados"),   n: sectors.filter((s) => !s.is_builtin).length },
          ].map((tab) => (
            <div key={tab.k} className={"tab" + (filterKind === tab.k ? " active" : "")}
              onClick={() => setFilterKind(tab.k)} style={{ cursor: "pointer" }}>
              {tab.l} <span className="tag-mono" style={{ marginLeft: 4 }}>{tab.n}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="page-body">
        <div className="card">
          <div className="card-body flush">
            {loading ? (
              <div className="text-faint" style={{ padding: 24, textAlign: "center" }}>
                {window.L("Chargement…", "Loading…", "Cargando…")}
              </div>
            ) : visible.length === 0 ? (
              <div className="text-faint" style={{ padding: 24, textAlign: "center" }}>
                {window.L("Aucun secteur dans cette catégorie.", "No sector in this category.", "Ningún sector en esta categoría.")}
              </div>
            ) : (
              <table className="tbl">
                <thead>
                  <tr>
                    <th style={{ width: 60 }}>{window.L("Couleur", "Colour", "Color")}</th>
                    <th>{window.L("Nom (FR)", "Name (FR)", "Nombre (FR)")}</th>
                    <th>{window.L("Nom (EN)", "Name (EN)", "Nombre (EN)")}</th>
                    <th>{window.L("Identifiant", "Slug", "Identificador")}</th>
                    <th>{window.L("Origine", "Origin", "Origen")}</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {visible.map((s) => (
                    <tr key={s.id}>
                      <td>
                        <span className="sector-chip" style={{ background: s.bg, color: s.color, borderColor: s.color, fontSize: 11 }}>
                          ●
                        </span>
                      </td>
                      <td><b>{s.fr}</b></td>
                      <td className="text-faint">{s.en || s.fr}</td>
                      <td className="mono text-faint" style={{ fontSize: 11 }}>{s.id}</td>
                      <td>
                        {s.is_builtin ? (
                          <span className="pill" style={{ fontSize: 10, background: "#dbeafe", color: "#1e3a8a" }}>
                            🛡 {window.L("Intégré", "Built-in", "Integrado")}
                          </span>
                        ) : (
                          <span className="pill" style={{ fontSize: 10, background: "var(--bg-sunken)" }}>
                            {window.L("Personnalisé", "Custom", "Personalizado")}
                          </span>
                        )}
                      </td>
                      <td>
                        <div className="row gap-xs" style={{ justifyContent: "flex-end" }}>
                          <button className="btn xs" onClick={() => setEditing(s)}>
                            <Icon.edit /> {window.L("Modifier", "Edit", "Editar")}
                          </button>
                          {!s.is_builtin && (
                            <button className="btn xs ghost" onClick={() => onArchive(s)} disabled={busy === s.id}
                              title={window.L("Archiver (suppression douce)", "Archive (soft delete)", "Archivar (borrado suave)")}>
                              <Icon.x />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
          {toast && (
            <div style={{
              margin: 12, padding: "8px 12px", borderRadius: 6, fontSize: 12.5,
              background: toast.ok ? "#dcfce7" : "#fee2e2",
              color:      toast.ok ? "#166534" : "#991b1b",
            }}>{toast.msg}</div>
          )}
        </div>
      </div>

      {editing && (
        <SectorEditor lang={lang} sector={editing}
          onClose={() => setEditing(null)}
          onSaved={() => {
            showToast(true, window.L("✓ Secteur mis à jour", "✓ Sector updated", "✓ Sector actualizado"));
            refresh();
          }} />
      )}
      {newOpen && (
        <NewSectorModal lang={lang}
          onClose={() => setNewOpen(false)}
          onCreated={() => { showToast(true, window.L("✓ Secteur créé", "✓ Sector created", "✓ Sector creado")); refresh(); }} />
      )}
    </div>
  );
}

// ─── SectorEditor · rename + recolour ──────────────────────────────────────
// A small modal with FR / EN name inputs and the 9-colour palette picker.
// Saves via sectorsCrud.update which RLS-gates to super-admin for built-ins
// and creator-org admin for customs.
function SectorEditor({ lang, sector, onClose, onSaved }) {
  const [nameFr, setNameFr] = useStateSEC(sector.fr);
  const [nameEn, setNameEn] = useStateSEC(sector.en || "");
  // Pre-select the palette entry whose color matches (if any).
  const [paletteKey, setPaletteKey] = useStateSEC(() => {
    const match = SECTOR_PALETTE_SEC.find((p) => p.color === sector.color && p.bg === sector.bg);
    return match ? match.key : SECTOR_PALETTE_SEC[0].key;
  });
  const [busy, setBusy] = useStateSEC(false);
  const [err, setErr] = useStateSEC(null);

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

  const onSubmit = async (e) => {
    e.preventDefault();
    setErr(null);
    if (!nameFr.trim()) { setErr(window.L("Le nom FR est requis.", "FR name is required.", "El nombre FR es obligatorio.")); return; }
    setBusy(true);
    try {
      await window.melr.sectorsCrud.update(sector.id, {
        name_fr: nameFr.trim(),
        name_en: nameEn.trim() || null,
        color:   palette.color,
        bg:      palette.bg,
      });
      if (onSaved) await onSaved();
      onClose();
    } catch (e2) {
      setErr(e2.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal
      title={<>{window.L("Modifier le secteur", "Edit sector", "Editar el sector")}
        <span className="text-faint" style={{ marginLeft: 8, fontSize: 12, fontWeight: 400 }}>
          ({sector.id})
        </span>
      </>}
      onClose={onClose}
      onSubmit={onSubmit}
      footer={<>
        <button type="button" className="btn sm ghost" onClick={onClose} disabled={busy}>
          {window.L("Annuler", "Cancel", "Cancelar")}
        </button>
        <button type="submit" className="btn sm primary" disabled={busy}>
          {busy
            ? (window.L("Enregistrement…", "Saving…", "Guardando…"))
            : (window.L("Enregistrer", "Save", "Guardar"))}
        </button>
      </>}>
      <div style={{ display: "grid", gap: 12 }}>
        {sector.is_builtin && (
          <div style={{ padding: "8px 10px", background: "#dbeafe", color: "#1e3a8a", borderRadius: 6, fontSize: 12 }}>
            🛡 {window.L("Secteur intégré (système). Vous pouvez renommer et changer la couleur. L'identifiant ne peut pas être modifié.", "Built-in (system) sector. You can rename and recolour. The slug cannot be changed.", "Sector integrado (del sistema). Puede renombrarlo y cambiar el color. El identificador no puede modificarse.")}
          </div>
        )}
        <label style={{ display: "grid", gap: 4 }}>
          <span style={{ fontSize: 11, opacity: 0.75 }}>{window.L("Nom (FR) *", "Name (FR) *", "Nombre (FR) *")}</span>
          <input required value={nameFr} onChange={(e) => setNameFr(e.target.value)}
            style={{ padding: "8px 10px", borderRadius: 6, border: "1px solid var(--line)", fontSize: 13 }}
            autoFocus />
        </label>
        <label style={{ display: "grid", gap: 4 }}>
          <span style={{ fontSize: 11, opacity: 0.75 }}>{window.L("Nom (EN, optionnel)", "Name (EN, optional)", "Nombre (EN, opcional)")}</span>
          <input value={nameEn} onChange={(e) => setNameEn(e.target.value)}
            style={{ padding: "8px 10px", borderRadius: 6, border: "1px solid var(--line)", fontSize: 13 }} />
        </label>
        <div>
          <span style={{ fontSize: 11, opacity: 0.75, display: "block", marginBottom: 6 }}>
            {window.L("Couleur", "Colour", "Color")}
          </span>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {SECTOR_PALETTE_SEC.map((p) => (
              <button key={p.key} type="button" onClick={() => setPaletteKey(p.key)}
                title={(lang === "es" ? (p.es != null ? p.es : p.en) : 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: 8 }}>
            <span className="sector-chip"
              style={{ background: palette.bg, color: palette.color, borderColor: palette.color, fontSize: 12 }}>
              {nameFr.trim() || (window.L("Aperçu", "Preview", "Vista previa"))}
            </span>
          </div>
        </div>
        {err && (
          <div style={{ color: "#b91c1c", fontSize: 12 }}>{err}</div>
        )}
      </div>
    </Modal>
  );
}

window.SectorsManagement = SectorsManagement;
