/* global React, Icon, Modal */
const { useState: useStateO, useEffect: useEffectO } = React;

// ============================================================================
// ORGANIZATIONS — super-admin tool to create / archive / delete organizations
// ----------------------------------------------------------------------------
// Visible only to users with the "orgs.manage" permission. Backed by the
// "organizations_super_admin_*" RLS policies in organizations-super-admin.sql.
// ============================================================================

function Organizations({ t, lang }) {
  const { has, loading: permsLoading } = window.melr.useCurrentUserPermissions();
  const { data: orgs, loading, realtime, refresh } = window.melr.useAllOrganizations();
  const LiveBadge = window.melr.LiveBadge;
  const [editing, setEditing]   = useStateO(null);    // "new" | org row | null
  const [confirming, setConfirming] = useStateO(null); // org pending hard-delete
  const [showArchived, setShowArchived] = useStateO(false);
  const [busyId, setBusyId]     = useStateO(null);

  if (permsLoading) {
    return <div className="page"><div style={{ padding: 28 }}>{window.L("Chargement…", "Loading…", "Cargando…")}</div></div>;
  }
  if (!has("orgs.manage")) {
    return (
      <div className="page">
        <div className="page-header">
          <div className="page-eyebrow">{window.L("ADMINISTRATION", "ADMINISTRATION", "ADMINISTRACIÓN")}</div>
          <h1 className="page-title">{window.L("Organisations", "Organizations", "Organizaciones")}</h1>
        </div>
        <div className="card" style={{ marginTop: 16, padding: 24 }}>
          <div className="text-faint" style={{ textAlign: "center" }}>
            {window.L("Accès réservé aux super-administrateurs (permission orgs.manage).", "Super-admins only (orgs.manage permission required).", "Acceso reservado a los superadministradores (permiso orgs.manage).")}
          </div>
        </div>
      </div>
    );
  }

  // Réactivation manuelle d'une org suspendue (super-admin uniquement).
  // Pass-through vers la RPC unsuspend_organization qui logge dans
  // billing_events automatiquement.
  const onUnsuspend = async (org) => {
    const defaultReason = window.L("Réactivation manuelle par super-admin", "Manual reactivation by super-admin", "Reactivación manual por superadministrador");
    const reason = window.prompt(
      window.L("Raison de la réactivation (loggée dans billing_events) :", "Reactivation reason (logged in billing_events):", "Motivo de la reactivación (registrado en billing_events):"),
      defaultReason);
    if (reason === null) return;  // user cancelled
    setBusyId(org.id);
    try {
      await window.melr.unsuspendOrganization(org.id, reason || defaultReason);
      await refresh();
    } catch (e) { window.alert((window.L("Erreur : ", "Error: ", "Error: ")) + e.message); }
    finally { setBusyId(null); }
  };

  const onToggleArchive = async (org) => {
    setBusyId(org.id);
    try {
      if (org.archived_at) await window.melr.organizationsCrud.unarchive(org.id);
      else                 await window.melr.organizationsCrud.archive(org.id);
      await refresh();
    } catch (e) { window.alert((window.L("Erreur : ", "Error: ", "Error: ")) + e.message); }
    finally { setBusyId(null); }
  };

  const visible = (orgs || []).filter((o) => showArchived ? true : !o.archived_at);
  const archivedCount = (orgs || []).filter((o) => !!o.archived_at).length;

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-eyebrow">{window.L("SUPER-ADMINISTRATION", "SUPER-ADMIN", "SUPERADMINISTRACIÓN")}</div>
        <div className="page-header-row">
          <div>
            <h1 className="page-title">
              {window.L("Organisations", "Organizations", "Organizaciones")}{" "}
              <LiveBadge on={realtime} lang={lang} />
            </h1>
            <div className="page-sub">
              {window.L("Toutes les organisations de la plateforme. Création, archivage et suppression sont irréversibles côté données.", "Every organization on the platform. Creation, archiving and deletion are data-irreversible.", "Todas las organizaciones de la plataforma. La creación, el archivado y la eliminación son irreversibles a nivel de datos.")}
            </div>
          </div>
          <div className="page-header-actions">
            <button className="btn sm primary" onClick={() => setEditing("new")}>
              <Icon.plus /> {window.L("Nouvelle organisation", "New organization", "Nueva organización")}
            </button>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="card-title">
            {window.L("Liste", "List", "Lista")}{" "}
            <span className="tag-mono" style={{ marginLeft: 6 }}>{visible.length} / {(orgs || []).length}</span>
          </div>
          <div style={{ flex: 1 }} />
          {archivedCount > 0 && (
            <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, cursor: "pointer" }}>
              <input type="checkbox" checked={showArchived} onChange={(e) => setShowArchived(e.target.checked)} />
              {window.L("Inclure les archivées", "Include archived", "Incluir las archivadas")}{" "}
              <span className="tag-mono" style={{ marginLeft: 4 }}>{archivedCount}</span>
            </label>
          )}
        </div>
        <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("Aucune organisation. Cliquez « Nouvelle organisation » pour démarrer.", "No organization yet. Click 'New organization' to start.", "Ninguna organización. Haga clic en « Nueva organización » para empezar.")}
            </div>
          ) : (
            <table className="tbl">
              <thead>
                <tr>
                  <th>{window.L("Nom", "Name", "Nombre")}</th>
                  <th>Slug</th>
                  <th>{window.L("Langue", "Locale", "Idioma")}</th>
                  <th className="num">{window.L("Membres", "Members", "Miembros")}</th>
                  <th className="num">{window.L("Projets", "Projects", "Proyectos")}</th>
                  <th>{window.L("Statut", "State", "Estado")}</th>
                  <th>{window.L("Créée le", "Created", "Creada el")}</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {visible.map((o) => (
                  <tr key={o.id} style={{ opacity: o.archived_at ? 0.55 : 1 }}>
                    <td>
                      <div className="strong">{o.name}</div>
                      {o.logo_url && <div className="text-faint" style={{ fontSize: 10 }}>{o.logo_url}</div>}
                    </td>
                    <td className="mono">{o.slug}</td>
                    <td className="mono text-faint">{(o.default_locale || "—").toUpperCase()}</td>
                    <td className="num mono">{o.members_count}</td>
                    <td className="num mono">{o.projects_count}</td>
                    <td>
                      {o.archived_at
                        ? <span className="pill" style={{ background: "#fef3c7", color: "#92400e", fontSize: 10.5 }}>{window.L("Archivée", "Archived", "Archivada")}</span>
                        : o.suspended_at
                          ? <span className="pill" style={{ background: "#fee2e2", color: "#7f1d1d", fontSize: 10.5, fontWeight: 700 }}
                              title={o.suspension_reason || ""}>
                              🔒 {window.L("Suspendue", "Suspended", "Suspendida")}
                            </span>
                          : <span className="pill green dot" style={{ fontSize: 10.5 }}>{window.L("Active", "Active", "Activa")}</span>}
                    </td>
                    <td className="text-faint" style={{ fontSize: 11 }}>
                      {o.created_at ? new Date(o.created_at).toLocaleDateString(window.L("fr-FR", "en-US", "es-ES")) : "—"}
                    </td>
                    <td>
                      <div className="row gap-xs" style={{ justifyContent: "flex-end" }}>
                        {/* Réactivation si suspendue — bouton vert prioritaire */}
                        {o.suspended_at && (
                          <button onClick={() => onUnsuspend(o)} disabled={busyId === o.id}
                            title={window.L("Réactiver l'organisation", "Reactivate organization", "Reactivar la organización")}
                            style={{ padding: "4px 10px", borderRadius: 4, border: "1px solid #15803d", background: "#15803d", color: "white", cursor: "pointer", fontSize: 11, fontWeight: 700 }}>
                            🔓 {window.L("Réactiver", "Reactivate", "Reactivar")}
                          </button>
                        )}
                        <button className="btn xs" onClick={() => setEditing(o)}>
                          <Icon.edit /> {window.L("Modifier", "Edit", "Editar")}
                        </button>
                        <button className="btn xs ghost" onClick={() => onToggleArchive(o)} disabled={busyId === o.id}
                          title={o.archived_at
                            ? (window.L("Restaurer", "Restore", "Restaurar"))
                            : (window.L("Archiver (réversible)", "Archive (reversible)", "Archivar (reversible)"))}>
                          {o.archived_at
                            ? (window.L("Restaurer", "Restore", "Restaurar"))
                            : (window.L("Archiver", "Archive", "Archivar"))}
                        </button>
                        <button className="btn xs ghost" onClick={() => setConfirming(o)} disabled={busyId === o.id}
                          title={window.L("Supprimer (irréversible)", "Delete (irreversible)", "Eliminar (irreversible)")}
                          style={{ color: "#b91c1c" }}>
                          <Icon.x />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      <div className="text-faint" style={{ fontSize: 11, marginTop: 12, lineHeight: 1.55 }}>
        {window.L("💡 Archiver est réversible : les données restent intactes, l'organisation devient masquée par défaut. Supprimer est définitif : cascade sur tous les projets, membres, indicateurs, formulaires, saisies, audits et rapports de l'org.", "💡 Archive is reversible: data stays, the org is hidden by default. Delete is permanent: cascades to every project, member, indicator, form, submission, audit and report of the org.", "💡 Archivar es reversible: los datos permanecen intactos, la organización queda oculta por defecto. Eliminar es definitivo: cascada sobre todos los proyectos, miembros, indicadores, formularios, registros, auditorías e informes de la organización.")}
      </div>

      <DemoLeadsCard lang={lang} />

      {editing && (
        <OrgEditor
          lang={lang}
          existing={editing === "new" ? null : editing}
          onClose={() => setEditing(null)}
          onSaved={refresh}
        />
      )}
      {confirming && (
        <OrgDeleteModal
          lang={lang}
          org={confirming}
          onClose={() => setConfirming(null)}
          onDeleted={refresh}
        />
      )}
    </div>
  );
}

// ── Demandes de démo (leads) ───────────────────────────────────────────────
// Liste des prospects inscrits via le formulaire « Démo » (table demo_signups,
// remplie par le trigger handle_new_user — cf. supabase/demo-signup-flow.sql).
// RLS : lecture super-admin uniquement, donc la carte rend vide pour les autres.
const DEMO_LEAD_MODULE_LABELS = {
  exante:          { fr: "Ex-ante",                en: "Ex-ante", es: "Ex ante" },
  baseline:        { fr: "Baseline",               en: "Baseline", es: "Línea de base" },
  evaluations:     { fr: "Évaluations",            en: "Evaluations", es: "Evaluaciones" },
  pefa:            { fr: "PEFA",                   en: "PEFA", es: "PEFA" },
  policy_eval:     { fr: "Politiques publiques",   en: "Public policy", es: "Políticas públicas" },
  midterm_final:   { fr: "Mi-parcours & finale",   en: "Mid-term & final", es: "Intermedia y final" },
  impact_training: { fr: "Impact & formations",    en: "Impact & training", es: "Impacto y formación" },
  gfp_diag:        { fr: "Diagnostics GFP",        en: "PFM diagnostics", es: "Diagnósticos GFP" },
  audit:           { fr: "Audit S&E",              en: "M&E audit", es: "Auditoría de S&E" },
  learning:        { fr: "Apprentissage",          en: "Learning", es: "Aprendizaje" },
  mobile:          { fr: "Collecte mobile",        en: "Mobile collection", es: "Recolección móvil" },
  form_builder:    { fr: "Formulaires",            en: "Form builder", es: "Formularios" },
  dhis2:           { fr: "DHIS2",                  en: "DHIS2", es: "DHIS2" },
  kobo_odk:        { fr: "Kobo/ODK",               en: "Kobo/ODK", es: "Kobo/ODK" },
};

function DemoLeadsCard({ lang }) {
  const { data: leads, loading, refresh } = window.melr.useDemoSignups();
  const fr = lang === "fr";
  const es = lang === "es";
  const modLabel = (code) => {
    const m = DEMO_LEAD_MODULE_LABELS[code];
    return m ? (es ? (m.es != null ? m.es : m.en) : fr ? m.fr : m.en) : code;
  };
  const exportCsv = () => {
    const head = ["email", "titre", "prenoms", "nom", "organisation", "ville", "pays", "telephone", "modules", "statut", "inscrit_le", "active_le"];
    const rows = (leads || []).map((l) => [
      l.email, l.title || "", l.first_names || "", l.last_name || "", l.organization_name || "",
      l.city || "", l.country || "", l.phone || "", (l.selected_modules || []).join("|"),
      l.status, l.created_at || "", l.activated_at || "",
    ]);
    const csv = [head, ...rows].map((r) => r.map((c) => '"' + String(c).replace(/"/g, '""') + '"').join(",")).join("\n");
    const a = document.createElement("a");
    a.href = URL.createObjectURL(new Blob(["﻿" + csv], { type: "text/csv;charset=utf-8" }));
    a.download = "demo-leads.csv";
    a.click();
  };
  return (
    <div className="card" style={{ marginTop: 18 }}>
      <div className="card-head">
        <div className="card-title">
          {es ? "Solicitudes de demo" : fr ? "Demandes de démo" : "Demo requests"}{" "}
          <span className="tag-mono" style={{ marginLeft: 6 }}>{(leads || []).length}</span>
        </div>
        <div style={{ flex: 1 }} />
        <button className="btn xs ghost" onClick={refresh}>{es ? "Actualizar" : fr ? "Rafraîchir" : "Refresh"}</button>
        <button className="btn xs" onClick={exportCsv} disabled={!leads || leads.length === 0} style={{ marginLeft: 6 }}>
          CSV
        </button>
      </div>
      <div className="card-body flush">
        {loading ? (
          <div className="text-faint" style={{ padding: 20, textAlign: "center" }}>{es ? "Cargando…" : fr ? "Chargement…" : "Loading…"}</div>
        ) : !leads || leads.length === 0 ? (
          <div className="text-faint" style={{ padding: 20, textAlign: "center" }}>
            {es ? "Aún no hay solicitudes de demo." : fr ? "Aucune demande de démo pour le moment." : "No demo request yet."}
          </div>
        ) : (
          <table className="tbl">
            <thead>
              <tr>
                <th>{es ? "Prospecto" : fr ? "Prospect" : "Lead"}</th>
                <th>{es ? "Organización" : fr ? "Organisation" : "Organization"}</th>
                <th>{es ? "Ubicación" : fr ? "Localisation" : "Location"}</th>
                <th>{es ? "Teléfono" : fr ? "Téléphone" : "Phone"}</th>
                <th>{es ? "Módulos solicitados" : fr ? "Modules demandés" : "Requested modules"}</th>
                <th>{es ? "Estado" : fr ? "Statut" : "Status"}</th>
                <th>{es ? "Registrado el" : fr ? "Inscrit le" : "Signed up"}</th>
              </tr>
            </thead>
            <tbody>
              {leads.map((l) => (
                <tr key={l.id}>
                  <td>
                    <div className="strong">{[l.title, l.first_names, l.last_name].filter(Boolean).join(" ") || "—"}</div>
                    <div className="text-faint" style={{ fontSize: 10.5 }}>{l.email}</div>
                  </td>
                  <td>{l.organization_name || "—"}</td>
                  <td className="text-faint" style={{ fontSize: 11 }}>{[l.city, l.country].filter(Boolean).join(", ") || "—"}</td>
                  <td className="mono" style={{ fontSize: 11 }}>{l.phone || "—"}</td>
                  <td style={{ maxWidth: 260 }}>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 3 }}>
                      {(l.selected_modules || []).map((c) => (
                        <span key={c} className="pill" style={{ fontSize: 9.5, background: "#ede9fe", color: "#5b21b6" }}>{modLabel(c)}</span>
                      ))}
                    </div>
                  </td>
                  <td>
                    {l.status === "active"
                      ? <span className="pill green dot" style={{ fontSize: 10.5 }}>{es ? "Correo validado" : fr ? "Email validé" : "Email confirmed"}</span>
                      : <span className="pill" style={{ background: "#fef3c7", color: "#92400e", fontSize: 10.5 }}>{es ? "Correo pendiente" : fr ? "En attente d'email" : "Pending email"}</span>}
                  </td>
                  <td className="text-faint" style={{ fontSize: 11 }}>
                    {l.created_at ? new Date(l.created_at).toLocaleDateString(window.melrLocale(lang)) : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

// ── Create / edit modal ────────────────────────────────────────────────────
function OrgEditor({ lang, existing, onClose, onSaved }) {
  const isNew = !existing;
  const [name, setName]           = useStateO(existing ? existing.name : "");
  const [slug, setSlug]           = useStateO(existing ? existing.slug : "");
  const [locale, setLocale]       = useStateO(existing ? (existing.default_locale || "fr") : "fr");
  const [logoUrl, setLogoUrl]     = useStateO(existing ? (existing.logo_url || "") : "");
  const [busy, setBusy]           = useStateO(false);
  const [err, setErr]             = useStateO(null);
  const [slugManuallyEdited, setSlugManuallyEdited] = useStateO(!isNew);

  // Auto-derive slug from name as the user types (until they touch slug)
  const onNameChange = (v) => {
    setName(v);
    if (!slugManuallyEdited) {
      const auto = v.toLowerCase()
        .normalize("NFD").replace(/[̀-ͯ]/g, "")
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/^-+|-+$/g, "")
        .slice(0, 48);
      setSlug(auto);
    }
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) { setErr(window.L("Nom requis.", "Name required.", "Nombre obligatorio.")); return; }
    if (!slug.trim()) { setErr(window.L("Slug requis.", "Slug required.", "Slug obligatorio.")); return; }
    setBusy(true); setErr(null);
    try {
      const payload = {
        name: name.trim(),
        slug: slug.trim(),
        default_locale: locale || "fr",
        logo_url: logoUrl.trim() || null,
      };
      if (isNew) await window.melr.organizationsCrud.create(payload);
      else       await window.melr.organizationsCrud.update(existing.id, payload);
      if (onSaved) await onSaved();
      onClose();
    } catch (e2) { setErr(e2.message); }
    finally { setBusy(false); }
  };

  const inp = { width: "100%", padding: "8px 10px", borderRadius: 6, border: "1px solid var(--line)", fontSize: 13, background: "var(--bg, white)", color: "var(--text)", boxSizing: "border-box", fontFamily: "inherit" };
  const lbl = { display: "block", fontSize: 11, color: "var(--text-faint)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em" };

  return (
    <Modal
      title={isNew
        ? (window.L("Nouvelle organisation", "New organization", "Nueva organización"))
        : (window.L("Modifier : " + existing.slug, "Edit: " + existing.slug, "Editar: " + existing.slug))}
      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 ? "…" : (isNew ? (window.L("Créer", "Create", "Crear")) : (window.L("Enregistrer", "Save", "Guardar")))}
        </button>
      </>}>
      <div style={{ display: "grid", gap: 12 }}>
        <div>
          <label style={lbl}>{window.L("Nom *", "Name *", "Nombre *")}</label>
          <input style={inp} value={name} onChange={(e) => onNameChange(e.target.value)}
            placeholder={window.L("Mon Organisation", "My Organization", "Mi Organización")}
            required maxLength={120} />
        </div>
        <div>
          <label style={lbl}>{window.L("Slug * (URL-friendly)", "Slug * (URL-friendly)", "Slug * (apto para URL)")}</label>
          <input style={inp} value={slug}
            onChange={(e) => { setSlugManuallyEdited(true); setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-")); }}
            placeholder="mon-orga" required maxLength={48} />
          <div className="text-faint" style={{ fontSize: 10.5, marginTop: 4 }}>
            {window.L("Minuscules, chiffres, tirets uniquement. Auto-généré depuis le nom.", "Lowercase, digits, hyphens only. Auto-generated from the name.", "Solo minúsculas, dígitos y guiones. Generado automáticamente a partir del nombre.")}
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <div>
            <label style={lbl}>{window.L("Langue par défaut", "Default locale", "Idioma por defecto")}</label>
            <select style={inp} value={locale} onChange={(e) => setLocale(e.target.value)}>
              <option value="fr">Français (FR)</option>
              <option value="en">English (EN)</option>
              <option value="es">Español (ES)</option>
              <option value="pt">Português (PT)</option>
            </select>
          </div>
          <div>
            <label style={lbl}>{window.L("URL logo (optionnel)", "Logo URL (optional)", "URL del logo (opcional)")}</label>
            <input style={inp} value={logoUrl} onChange={(e) => setLogoUrl(e.target.value)}
              placeholder="https://…/logo.png" />
          </div>
        </div>
        {isNew && (
          <div style={{ padding: "10px 12px", background: "#eef2ff", color: "#3730a3", borderRadius: 6, fontSize: 12 }}>
            {window.L("ℹ️ Après création, ajoutez le premier admin de l'org via 'Org & rôles' → 'Inscrits en attente' (il doit d'abord créer son compte depuis le panneau de connexion).", "ℹ️ After creation, add the first admin via 'Org & roles' → 'Pending sign-ups' (they must first create their account from the auth panel).", "ℹ️ Tras la creación, añada el primer administrador de la organización mediante 'Org y roles' → 'Inscritos pendientes' (primero debe crear su cuenta desde el panel de conexión).")}
          </div>
        )}
        {err && (
          <div style={{ padding: "8px 10px", background: "#fee2e2", color: "#991b1b", borderRadius: 6, fontSize: 12.5 }}>{err}</div>
        )}
      </div>
    </Modal>
  );
}

// ── Hard-delete confirmation modal ─────────────────────────────────────────
// Requires the user to re-type the slug to proceed. Defends against accidental
// cascade deletion of all org-scoped data.
function OrgDeleteModal({ lang, org, onClose, onDeleted }) {
  const [typed, setTyped] = useStateO("");
  const [busy, setBusy]   = useStateO(false);
  const [err, setErr]     = useStateO(null);
  const matches = typed.trim() === org.slug;

  const onConfirm = async () => {
    if (!matches) return;
    setBusy(true); setErr(null);
    try {
      await window.melr.organizationsCrud.remove(org.id, org.slug);
      if (onDeleted) await onDeleted();
      onClose();
    } catch (e2) { setErr(e2.message); }
    finally { setBusy(false); }
  };

  const inp = { width: "100%", padding: "8px 10px", borderRadius: 6, border: "1px solid var(--line)", fontSize: 13, fontFamily: "ui-monospace, monospace" };
  return (
    <Modal
      title={<>⚠ {window.L("Supprimer l'organisation", "Delete organization", "Eliminar la organización")}</>}
      onClose={onClose}
      footer={<>
        <button type="button" className="btn sm ghost" onClick={onClose} disabled={busy}>
          {window.L("Annuler", "Cancel", "Cancelar")}
        </button>
        <button type="button" onClick={onConfirm} disabled={busy || !matches}
          style={{
            padding: "8px 14px", borderRadius: 6, border: 0,
            background: matches ? "#dc2626" : "#9ca3af",
            color: "white", cursor: matches ? "pointer" : "not-allowed", fontWeight: 600,
          }}>
          {busy ? "…" : (window.L("Supprimer définitivement", "Permanently delete", "Eliminar de forma permanente"))}
        </button>
      </>}>
      <div style={{ display: "grid", gap: 12 }}>
        <div className="strong" style={{ color: "#991b1b" }}>
          {window.L("Action irréversible — cascade sur toutes les données", "Irreversible — cascades to every record", "Acción irreversible — cascada sobre todos los datos")}
        </div>
        <div className="text-faint" style={{ fontSize: 12.5, lineHeight: 1.55 }}>
          {window.L("Cette action supprime définitivement l'organisation « " + org.name + " » ainsi que TOUS ses projets, sites, indicateurs, formulaires, saisies, audits, validations, rapports, tickets et profils membres. Aucun retour possible sans sauvegarde.", "This permanently removes the organization '" + org.name + "' and ALL its projects, sites, indicators, forms, submissions, audits, validations, reports, tickets and member profiles. No undo without a backup.", "Esta acción elimina definitivamente la organización «" + org.name + "» así como TODOS sus proyectos, sitios, indicadores, formularios, entradas, auditorías, validaciones, informes, tickets y perfiles de miembros. Sin posibilidad de recuperación sin copia de seguridad.")}
        </div>
        <div>
          <label style={{ display: "block", fontSize: 11, color: "var(--text-faint)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em" }}>
            {window.L(<>Pour confirmer, retape le slug : <span className="mono strong" style={{ color: "#991b1b" }}>{org.slug}</span></>, <>To confirm, retype the slug: <span className="mono strong" style={{ color: "#991b1b" }}>{org.slug}</span></>, <>Para confirmar, vuelva a escribir el slug: <span className="mono strong" style={{ color: "#991b1b" }}>{org.slug}</span></>)}
          </label>
          <input style={inp} value={typed} onChange={(e) => setTyped(e.target.value)}
            placeholder={org.slug} autoFocus />
        </div>
        {err && (
          <div style={{ padding: "8px 10px", background: "#fee2e2", color: "#991b1b", borderRadius: 6, fontSize: 12.5 }}>{err}</div>
        )}
      </div>
    </Modal>
  );
}

window.Organizations = Organizations;
