/* AdminIglesia → window. Panel del Pastor.
   Se renderiza INLINE como una pestaña más de la app (no portal) — la
   BottomNav y el Header de la app permanecen visibles, igual que
   SuperAdmin. Estructura preparada para sumar tabs "Roles" e
   "Invitaciones" en etapas siguientes; por ahora solo se muestra
   "Miembros".

   Props:
     - iglesias: lista completa de iglesias activas (del DataProvider
       de app.jsx). Se filtran a las que el pastor administra usando
       /users/{uid}/perfil/iglesias_admin.

   Datos:
     - Suscribe a /iglesias/{iglesiaActivaId}/miembros/ vía
       window.suscribirMiembrosDeIglesia(id, cb). */
(function () {
  const { useState, useEffect, useMemo } = React;
  const { useAuth, useTheme, miPerfil } = window;

  const BRAND = "#2563EB";
  const GREEN = "#58CC02";
  const GREEN_SHADOW = "#46A302";
  const INK = "#3C3C3C";
  const MUTED = "#777";
  const DIVIDER = "#EEE";
  const PANEL_BG = "#F9F9F9";

  // Copia idéntica a SuperAdmin para que el flujo de compartir funcione
  // sin tener que acoplar módulos. Son helpers puros sin estado.
  async function copiarAlClipboard(texto) {
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(texto);
        return true;
      }
    } catch (_) { /* fallback */ }
    try {
      const el = document.createElement("textarea");
      el.value = texto;
      el.setAttribute("readonly", "");
      el.style.position = "fixed";
      el.style.top = "-1000px";
      document.body.appendChild(el);
      el.select();
      const ok = document.execCommand("copy");
      document.body.removeChild(el);
      return ok;
    } catch (_) {
      return false;
    }
  }

  async function compartirLink(titulo, texto, url) {
    if (navigator.share) {
      try {
        await navigator.share({ title: titulo, text: texto, url: url });
        return "nativo";
      } catch (e) {
        if (e && e.name === "AbortError") return "cancelado";
      }
    }
    const ok = await copiarAlClipboard(url);
    return ok ? "copiado" : "error";
  }

  function iglesiasDelPastor(todas, adminMap) {
    if (!Array.isArray(todas)) return [];
    if (!adminMap || typeof adminMap !== "object") return [];
    const ids = Object.keys(adminMap).filter(function (k) { return adminMap[k] === true; });
    if (ids.length === 0) return [];
    const set = {};
    ids.forEach(function (id) { set[id] = true; });
    return todas
      .filter(function (ig) { return ig && set[ig.id]; })
      .slice()
      .sort(function (a, b) {
        return String(a.nombre || "").localeCompare(String(b.nombre || ""));
      });
  }

  function AdminIglesia({ iglesias }) {
    const { user } = useAuth();
    const { dark } = useTheme();

    const colorTexto = dark ? "#F0F0F0" : INK;
    const colorSecundario = dark ? "#9CA3AF" : MUTED;
    const colorMuted = dark ? "#6B7280" : "#9CA3AF";
    const colorBorde = dark ? "#2A2A2A" : DIVIDER;
    const bgPanel = dark ? "#141415" : PANEL_BG;
    const bgCard = dark ? "#1A1A1A" : "#FFFFFF";
    const bgHeader = dark ? "#0F0F10" : "#FFFFFF";
    const bgTabs = dark ? "#1F2937" : "#F0F0F0";
    const bgChipInactivo = dark ? "#1F2937" : "#EEF2FF";
    const bgPlaceholder = dark ? "#1F2937" : "#E0EAFF";
    const shadowCard = dark ? "0 1px 0 #2A2A2A" : "0 1px 0 " + DIVIDER;

    const perfil = typeof miPerfil === "function" ? miPerfil() : null;
    const adminMap = (perfil && perfil.iglesias_admin) || {};
    const iglesiasPastor = useMemo(function () {
      return iglesiasDelPastor(iglesias, adminMap);
    }, [iglesias, adminMap]);

    const [iglesiaActivaId, setIglesiaActivaId] = useState(null);
    useEffect(function () {
      if (iglesiasPastor.length === 0) {
        setIglesiaActivaId(null);
        return;
      }
      const existe = iglesiasPastor.some(function (ig) { return ig.id === iglesiaActivaId; });
      if (!existe) setIglesiaActivaId(iglesiasPastor[0].id);
    }, [iglesiasPastor]);

    const [tabActiva, setTabActiva] = useState("miembros");
    const tabs = [
      { id: "miembros", label: "Miembros" },
      { id: "amigos",   label: "Amigos" },
      { id: "roles",    label: "Roles" },
    ];

    // Usuarios del nodo activo (miembros o amigos de la iglesia).
    const [usuarios, setUsuarios] = useState([]);
    const [cargandoUsuarios, setCargandoUsuarios] = useState(false);
    const [generandoAbierto, setGenerandoAbierto] = useState(false);
    const [toast, setToast] = useState("");

    // Estado para tab Roles.
    const [rolesAsignados, setRolesAsignados] = useState([]);
    const [cargandoRoles, setCargandoRoles] = useState(false);
    const [asignandoRol, setAsignandoRol] = useState(null); // objeto rol del catálogo
    const [revocandoRol, setRevocandoRol] = useState(null); // { item, enCurso }
    const [revocandoEnCurso, setRevocandoEnCurso] = useState(false);
    // Tick para refrescar la pill de tiempo restante sin pedir datos.
    const [ahora, setAhora] = useState(Date.now());
    useEffect(function () {
      if (tabActiva !== "roles") return;
      const id = setInterval(function () { setAhora(Date.now()); }, 60000);
      return function () { clearInterval(id); };
    }, [tabActiva]);

    // Tipo forzado para el ModalGenerarInvitacion según tab activa.
    const tipoInvitacion = tabActiva === "amigos" ? "amigo" : "miembro";

    function mostrarToast(msg) {
      setToast(msg);
      setTimeout(function () { setToast(""); }, 1800);
    }

    useEffect(function () {
      if (!iglesiaActivaId || tabActiva === "roles") {
        // La tab Roles tiene su propia suscripción (abajo); las otras dos
        // reusan la suscripción a miembros/amigos.
        if (tabActiva === "roles") {
          setCargandoUsuarios(false);
        } else {
          setUsuarios([]);
          setCargandoUsuarios(false);
        }
        return;
      }
      const suscriptor = tabActiva === "amigos"
        ? window.suscribirAmigosDeIglesia
        : window.suscribirMiembrosDeIglesia;
      if (typeof suscriptor !== "function") {
        setUsuarios([]);
        setCargandoUsuarios(false);
        return;
      }
      setCargandoUsuarios(true);
      const unsub = suscriptor(iglesiaActivaId, function (arr) {
        setUsuarios(Array.isArray(arr) ? arr : []);
        setCargandoUsuarios(false);
      });
      return function () {
        if (typeof unsub === "function") unsub();
      };
    }, [iglesiaActivaId, tabActiva]);

    // Suscripción de roles asignados (sólo cuando la tab Roles está abierta).
    useEffect(function () {
      if (!iglesiaActivaId || tabActiva !== "roles") {
        setRolesAsignados([]);
        setCargandoRoles(false);
        return;
      }
      if (typeof window.suscribirRolesAsignados !== "function") {
        setRolesAsignados([]);
        setCargandoRoles(false);
        return;
      }
      setCargandoRoles(true);
      const unsub = window.suscribirRolesAsignados(iglesiaActivaId, function (arr) {
        setRolesAsignados(Array.isArray(arr) ? arr : []);
        setCargandoRoles(false);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [iglesiaActivaId, tabActiva]);

    const iglesiaActiva = useMemo(function () {
      return iglesiasPastor.find(function (ig) { return ig.id === iglesiaActivaId; }) || null;
    }, [iglesiasPastor, iglesiaActivaId]);

    async function ejecutarAsignarRol(miembroUid, duracionHoras) {
      if (!iglesiaActivaId || !asignandoRol || !miembroUid) return false;
      if (typeof window.asignarRol !== "function") return false;
      try {
        await window.asignarRol(iglesiaActivaId, miembroUid, asignandoRol.id, duracionHoras);
        const miembro = (usuarios.find(function (u) { return u.uid === miembroUid; }) || null);
        const nombreCorto = miembro && miembro.nombre
          ? miembro.nombre.split(" ")[0]
          : "el miembro";
        mostrarToast("Rol asignado a " + nombreCorto + " ✓");
        setAsignandoRol(null);
        return true;
      } catch (e) {
        console.warn("[AdminIglesia] asignarRol falló:", e);
        mostrarToast("No pudimos asignar. " + (e && e.message ? e.message : ""));
        return false;
      }
    }

    async function ejecutarRevocarRol() {
      if (!iglesiaActivaId || !revocandoRol || revocandoEnCurso) return;
      if (typeof window.revocarRol !== "function") return;
      setRevocandoEnCurso(true);
      try {
        await window.revocarRol(iglesiaActivaId, revocandoRol.miembro_uid, revocandoRol.rol_id);
        mostrarToast("Rol revocado");
        setRevocandoRol(null);
      } catch (e) {
        console.warn("[AdminIglesia] revocarRol falló:", e);
        mostrarToast("No pudimos revocar. " + (e && e.message ? e.message : ""));
      } finally {
        setRevocandoEnCurso(false);
      }
    }

    // --- Renderers ---

    function renderSelectorIglesia() {
      if (iglesiasPastor.length === 0) return null;

      // Caso 1: una sola iglesia → chip fijo, no interactivo.
      if (iglesiasPastor.length === 1) {
        const ig = iglesiasPastor[0];
        return (
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 14px 0" }}>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "8px 12px",
                borderRadius: 999,
                background: bgChipInactivo,
                border: "1px solid " + colorBorde,
                color: colorTexto,
                fontSize: 12,
                fontWeight: 800,
                maxWidth: "100%",
              }}
            >
              <span aria-hidden>🏠</span>
              <span style={{
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
                maxWidth: 260,
              }}>{ig.nombre || "Sin nombre"}</span>
            </div>
          </div>
        );
      }

      // Caso 2: varias iglesias → pills tappables con scroll horizontal.
      return (
        <div
          style={{
            display: "flex",
            gap: 8,
            padding: "10px 14px 0",
            overflowX: "auto",
            WebkitOverflowScrolling: "touch",
          }}
        >
          {iglesiasPastor.map(function (ig) {
            const activa = ig.id === iglesiaActivaId;
            return (
              <button
                key={ig.id}
                type="button"
                onClick={function () { setIglesiaActivaId(ig.id); }}
                style={{
                  flexShrink: 0,
                  padding: "8px 14px",
                  borderRadius: 999,
                  border: "1px solid " + (activa ? BRAND : colorBorde),
                  background: activa ? BRAND : bgChipInactivo,
                  color: activa ? "#FFFFFF" : colorTexto,
                  fontSize: 12,
                  fontWeight: 800,
                  cursor: "pointer",
                  maxWidth: 240,
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                }}
                title={ig.nombre || ""}
              >
                {ig.nombre || "Sin nombre"}
              </button>
            );
          })}
        </div>
      );
    }

    function renderTabsBar() {
      return (
        <div style={{ padding: "12px 14px 0" }}>
          <div style={{ display: "flex", gap: 6, background: bgTabs, borderRadius: 999, padding: 4 }}>
            {tabs.map(function (t) {
              const activa = t.id === tabActiva;
              return (
                <button
                  key={t.id}
                  type="button"
                  onClick={function () { setTabActiva(t.id); }}
                  style={{
                    flex: 1,
                    height: 34,
                    border: "none",
                    borderRadius: 999,
                    background: activa ? BRAND : "transparent",
                    color: activa ? "#FFFFFF" : colorSecundario,
                    fontSize: 12,
                    fontWeight: 800,
                    cursor: "pointer",
                  }}
                >
                  {t.label}
                </button>
              );
            })}
          </div>
        </div>
      );
    }

    function renderUsuarioRow(m) {
      return (
        <div
          key={m.uid}
          style={{
            display: "flex",
            alignItems: "center",
            gap: 12,
            padding: "12px 14px",
            borderBottom: "1px solid " + colorBorde,
          }}
        >
          {m.foto_url ? (
            <img
              src={m.foto_url}
              alt=""
              referrerPolicy="no-referrer"
              style={{
                width: 40, height: 40, borderRadius: "50%",
                objectFit: "cover", flexShrink: 0, background: bgPlaceholder,
              }}
            />
          ) : (
            <div
              aria-hidden
              style={{
                width: 40, height: 40, borderRadius: "50%",
                background: bgPlaceholder, flexShrink: 0,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 18, color: BRAND, fontWeight: 900,
              }}
            >
              {(m.nombre || m.email || "?").trim().charAt(0).toUpperCase()}
            </div>
          )}

          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontSize: 14, fontWeight: 800, color: colorTexto,
                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
              }}
            >
              {m.nombre || "Sin nombre"}
            </div>
            {m.email && (
              <div
                style={{
                  fontSize: 12, fontWeight: 600, color: colorSecundario,
                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                }}
              >
                {m.email}
              </div>
            )}
          </div>
        </div>
      );
    }

    function renderGenerarBoton(centrado) {
      const label = tabActiva === "amigos"
        ? "+ Generar enlace de amigo"
        : "+ Generar enlace de miembro";
      return (
        <button
          type="button"
          onClick={function () { setGenerandoAbierto(true); }}
          style={{
            marginTop: centrado ? 6 : 0,
            padding: "12px 18px",
            borderRadius: 14,
            border: "none",
            background: GREEN,
            color: "#FFFFFF",
            fontSize: 14,
            fontWeight: 900,
            cursor: "pointer",
            boxShadow: "0 4px 0 " + GREEN_SHADOW,
            letterSpacing: 0.2,
          }}
        >
          {label}
        </button>
      );
    }

    function renderUsuariosVacio() {
      const esAmigos = tabActiva === "amigos";
      return (
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            textAlign: "center",
            padding: "36px 20px",
            gap: 10,
          }}
        >
          <div style={{ fontSize: 48, lineHeight: 1 }} aria-hidden>
            {esAmigos ? "🤝" : "👥"}
          </div>
          <div style={{ fontSize: 15, fontWeight: 900, color: colorTexto }}>
            {esAmigos
              ? "Aún no tiene amigos vinculados"
              : "Aún no tiene miembros vinculados"}
          </div>
          <div
            style={{
              fontSize: 13, fontWeight: 600, color: colorSecundario,
              maxWidth: 320, lineHeight: 1.5,
            }}
          >
            {esAmigos
              ? "Genere un enlace de amigo para que personas interesadas sigan la actividad de la iglesia sin ser miembros."
              : "Genere un enlace de invitación y compártalo para que sus miembros se vinculen a esta iglesia."}
          </div>
          {renderGenerarBoton(true)}
        </div>
      );
    }

    function renderUsuarios() {
      if (!iglesiaActivaId) return null;

      const esAmigos = tabActiva === "amigos";

      if (cargandoUsuarios) {
        return (
          <div
            style={{
              display: "flex", flexDirection: "column",
              alignItems: "center", justifyContent: "center",
              padding: "36px 16px", gap: 12,
            }}
          >
            <div
              style={{
                width: 28, height: 28,
                border: "3px solid " + colorBorde,
                borderTopColor: BRAND,
                borderRadius: "50%",
                animation: "adminIglesiaSpin 0.9s linear infinite",
              }}
            />
            <div style={{ fontSize: 13, fontWeight: 700, color: colorSecundario }}>
              {esAmigos ? "Cargando amigos…" : "Cargando miembros…"}
            </div>
          </div>
        );
      }

      if (usuarios.length === 0) {
        return renderUsuariosVacio();
      }

      const etiquetaUno = esAmigos ? "amigo vinculado" : "miembro vinculado";
      const etiquetaVarios = esAmigos ? "amigos vinculados" : "miembros vinculados";

      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            {renderGenerarBoton(false)}
          </div>
          <div
            style={{
              background: bgCard,
              borderRadius: 14,
              boxShadow: shadowCard,
              overflow: "hidden",
            }}
          >
            <div
              style={{
                padding: "10px 14px",
                borderBottom: "1px solid " + colorBorde,
                fontSize: 11,
                fontWeight: 900,
                textTransform: "uppercase",
                letterSpacing: 0.6,
                color: colorSecundario,
              }}
            >
              {usuarios.length} {usuarios.length === 1 ? etiquetaUno : etiquetaVarios}
            </div>
            {usuarios.map(renderUsuarioRow)}
          </div>
        </div>
      );
    }

    function pillTiempoRol(item) {
      // Devuelve { bg, fg, label } para la píldora de tiempo restante.
      const UNA_HORA = 60 * 60 * 1000;
      const UN_DIA = 24 * UNA_HORA;
      if (item.expira_en == null) {
        return dark
          ? { bg: "#064E3B", fg: "#6EE7B7", label: "Indefinido" }
          : { bg: "#DCFCE7", fg: "#166534", label: "Indefinido" };
      }
      const ms = item.expira_en - ahora;
      const totalSeg = Math.max(0, Math.floor(ms / 1000));
      const totalMin = Math.floor(totalSeg / 60);
      const totalHr = Math.floor(totalMin / 60);
      const dias = Math.floor(totalHr / 24);
      let label;
      if (ms <= 0) label = "Expirado";
      else if (dias >= 1) label = dias + "d " + (totalHr % 24) + "h";
      else if (totalHr >= 1) label = totalHr + "h " + (totalMin % 60) + "m";
      else if (totalMin >= 1) label = totalMin + "m";
      else label = totalSeg + "s";

      if (ms <= 0) return { bg: "#FFE4E4", fg: "#B32020", label: label };
      if (ms < UNA_HORA) return { bg: "#FF4B4B", fg: "#FFFFFF", label: label };
      if (ms < UN_DIA) return { bg: "#FFC800", fg: "#3C3C3C", label: label };
      return dark
        ? { bg: "#064E3B", fg: "#6EE7B7", label: label }
        : { bg: "#DCFCE7", fg: "#166534", label: label };
    }

    function renderRolCard(r) {
      return (
        <div
          key={r.id}
          style={{
            display: "flex",
            alignItems: "flex-start",
            gap: 12,
            padding: 14,
            background: bgCard,
            border: "1px solid " + colorBorde,
            borderRadius: 14,
            boxShadow: shadowCard,
          }}
        >
          <div style={{ fontSize: 40, lineHeight: 1, flexShrink: 0 }} aria-hidden>
            {r.emoji}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 900, color: colorTexto, lineHeight: 1.2 }}>
              {r.nombre}
            </div>
            <div
              style={{
                fontSize: 12, fontWeight: 600, color: colorSecundario,
                lineHeight: 1.4, marginTop: 4,
              }}
            >
              {r.descripcion}
            </div>
            <button
              type="button"
              onClick={function () { setAsignandoRol(r); }}
              style={{
                marginTop: 10,
                padding: "8px 14px",
                borderRadius: 999,
                border: "none",
                background: GREEN,
                color: "#FFFFFF",
                fontSize: 12,
                fontWeight: 900,
                cursor: "pointer",
                boxShadow: "0 3px 0 " + GREEN_SHADOW,
                letterSpacing: 0.2,
              }}
            >
              Asignar
            </button>
          </div>
        </div>
      );
    }

    function renderRolAsignadoRow(item) {
      const pill = pillTiempoRol(item);
      const m = item.miembro || {};
      const rolNombre = item.rol ? item.rol.nombre : item.rol_id;
      const rolEmoji = item.rol ? item.rol.emoji : "⭐";
      return (
        <div
          key={item.clave}
          style={{
            display: "flex",
            alignItems: "center",
            gap: 12,
            padding: "12px 14px",
            borderBottom: "1px solid " + colorBorde,
          }}
        >
          {m.foto_url ? (
            <img
              src={m.foto_url}
              alt=""
              referrerPolicy="no-referrer"
              style={{
                width: 40, height: 40, borderRadius: "50%",
                objectFit: "cover", flexShrink: 0, background: bgPlaceholder,
              }}
            />
          ) : (
            <div
              aria-hidden
              style={{
                width: 40, height: 40, borderRadius: "50%",
                background: bgPlaceholder, flexShrink: 0,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 18, color: BRAND, fontWeight: 900,
              }}
            >
              {(m.nombre || m.email || "?").trim().charAt(0).toUpperCase()}
            </div>
          )}

          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                fontSize: 14, fontWeight: 800, color: colorTexto,
                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
              }}
            >
              {m.nombre || "Sin nombre"}
            </div>
            <div
              style={{
                fontSize: 11, fontWeight: 700, color: colorSecundario,
                marginTop: 2, display: "flex", alignItems: "center", gap: 6,
                flexWrap: "wrap",
              }}
            >
              <span aria-hidden>{rolEmoji}</span>
              <span>{rolNombre}</span>
              <span
                style={{
                  background: pill.bg, color: pill.fg,
                  padding: "2px 8px", borderRadius: 999,
                  fontSize: 10, fontWeight: 900, letterSpacing: 0.3,
                }}
              >
                {pill.label}
              </span>
            </div>
          </div>

          <button
            type="button"
            onClick={function () { setRevocandoRol(item); }}
            style={{
              flexShrink: 0,
              padding: "8px 12px",
              borderRadius: 999,
              border: "1px solid " + colorBorde,
              background: "transparent",
              color: "#FF4B4B",
              fontSize: 11,
              fontWeight: 900,
              cursor: "pointer",
              letterSpacing: 0.3,
            }}
          >
            Revocar
          </button>
        </div>
      );
    }

    function renderRoles() {
      if (!iglesiaActivaId) return null;
      const catalogo = Array.isArray(window.ROLES_CATALOGO) ? window.ROLES_CATALOGO : [];

      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div>
            <div
              style={{
                fontSize: 11, fontWeight: 900, textTransform: "uppercase",
                letterSpacing: 0.6, color: colorSecundario, marginBottom: 10,
              }}
            >
              Catálogo de roles
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {catalogo.map(renderRolCard)}
            </div>
          </div>

          <div>
            <div
              style={{
                fontSize: 11, fontWeight: 900, textTransform: "uppercase",
                letterSpacing: 0.6, color: colorSecundario, marginBottom: 10,
              }}
            >
              Roles activos {rolesAsignados.length > 0 ? "(" + rolesAsignados.length + ")" : ""}
            </div>
            {cargandoRoles && (
              <div
                style={{
                  display: "flex", flexDirection: "column",
                  alignItems: "center", padding: "24px 12px", gap: 10,
                }}
              >
                <div
                  style={{
                    width: 24, height: 24,
                    border: "3px solid " + colorBorde,
                    borderTopColor: BRAND,
                    borderRadius: "50%",
                    animation: "adminIglesiaSpin 0.9s linear infinite",
                  }}
                />
                <div style={{ fontSize: 12, fontWeight: 700, color: colorSecundario }}>
                  Cargando roles…
                </div>
              </div>
            )}
            {!cargandoRoles && rolesAsignados.length === 0 && (
              <div
                style={{
                  padding: "18px 14px",
                  background: bgCard,
                  border: "1px dashed " + colorBorde,
                  borderRadius: 12,
                  fontSize: 12, fontWeight: 600,
                  color: colorSecundario, textAlign: "center",
                }}
              >
                No hay roles asignados en esta iglesia todavía.
              </div>
            )}
            {!cargandoRoles && rolesAsignados.length > 0 && (
              <div
                style={{
                  background: bgCard,
                  borderRadius: 14,
                  boxShadow: shadowCard,
                  overflow: "hidden",
                }}
              >
                {rolesAsignados.map(renderRolAsignadoRow)}
              </div>
            )}
          </div>
        </div>
      );
    }

    function renderEmptySinIglesias() {
      return (
        <div
          style={{
            display: "flex", flexDirection: "column",
            alignItems: "center", textAlign: "center",
            padding: "48px 20px", gap: 10,
          }}
        >
          <div style={{ fontSize: 48, lineHeight: 1 }} aria-hidden>🕊️</div>
          <div style={{ fontSize: 16, fontWeight: 900, color: colorTexto }}>
            Aún no administra ninguna iglesia
          </div>
          <div
            style={{
              fontSize: 13, fontWeight: 600, color: colorSecundario,
              maxWidth: 320, lineHeight: 1.5,
            }}
          >
            Registre su iglesia desde "Mis iglesias" para activar el panel.
          </div>
        </div>
      );
    }

    // --- Render principal ---

    if (typeof document === "undefined") return null;

    return (
      <div
        className="fade-in"
        style={{
          background: bgPanel,
          color: colorTexto,
          paddingBottom: 84, // espacio para el BottomNav
          animation: "adminIglesiaFade 180ms ease-out",
        }}
      >
        <div
          style={{
            background: bgHeader,
            borderBottom: "1px solid " + colorBorde,
            padding: "12px 14px 14px",
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ fontSize: 22, lineHeight: 1 }} aria-hidden>🕊️</div>
            <div style={{ fontSize: 17, fontWeight: 900, color: colorTexto }}>
              Panel del Pastor
            </div>
          </div>

          {iglesiasPastor.length > 0 && (
            <React.Fragment>
              {renderSelectorIglesia()}
              {renderTabsBar()}
            </React.Fragment>
          )}
        </div>

        <div key={tabActiva + ":" + (iglesiaActivaId || "_")}
             style={{ padding: 14, animation: "adminIglesiaFade 180ms ease-out" }}>
          {iglesiasPastor.length === 0 && renderEmptySinIglesias()}
          {iglesiasPastor.length > 0 && iglesiaActivaId && (tabActiva === "miembros" || tabActiva === "amigos") && renderUsuarios()}
          {iglesiasPastor.length > 0 && iglesiaActivaId && tabActiva === "roles" && renderRoles()}
        </div>

        {generandoAbierto && iglesiaActiva && window.ModalGenerarInvitacion && (
          React.createElement(window.ModalGenerarInvitacion, {
            tipo: tipoInvitacion,
            user: user,
            iglesiaId: iglesiaActiva.id,
            iglesiaNombreForced: iglesiaActiva.nombre || "",
            onCerrar: function () { setGenerandoAbierto(false); },
            onCopiar: copiarAlClipboard,
            onCompartir: compartirLink,
            onToast: mostrarToast,
          })
        )}

        {asignandoRol && iglesiaActiva && window.AsignarRolModal && (
          React.createElement(window.AsignarRolModal, {
            rol: asignandoRol,
            iglesia: iglesiaActiva,
            dark: dark,
            onCerrar: function () { setAsignandoRol(null); },
            onAsignar: ejecutarAsignarRol,
          })
        )}

        {revocandoRol && window.ConfirmModal && React.createElement(window.ConfirmModal, {
          abierto: !!revocandoRol,
          titulo: "Revocar rol",
          mensaje: revocandoRol && revocandoRol.rol
            ? "¿Revocar el rol \"" + revocandoRol.rol.nombre + "\" de "
              + ((revocandoRol.miembro && revocandoRol.miembro.nombre) || "este miembro")
              + "?"
            : "",
          textoConfirmar: "Revocar",
          textoCancelar: "Cancelar",
          tono: "peligro",
          cargando: revocandoEnCurso,
          onConfirmar: ejecutarRevocarRol,
          onCancelar: function () { if (!revocandoEnCurso) setRevocandoRol(null); },
        })}

        {toast && (
          <div
            style={{
              position: "fixed",
              left: "50%",
              bottom: 96,
              transform: "translateX(-50%)",
              background: "#3C3C3C",
              color: "#FFFFFF",
              padding: "12px 18px",
              borderRadius: 999,
              fontSize: 14,
              fontWeight: 700,
              boxShadow: "0 6px 20px rgba(0,0,0,0.25)",
              zIndex: 40,
              animation: "adminIglesiaFade 180ms ease-out",
            }}
          >
            {toast}
          </div>
        )}

        <style>{`
          @keyframes adminIglesiaFade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
          @keyframes adminIglesiaSpin { to { transform: rotate(360deg); } }
        `}</style>
      </div>
    );
  }

  window.AdminIglesia = AdminIglesia;
})();
