/* MisIglesias → window. Pantalla INLINE dentro del body de la app.
   Props: { onClose, onSeleccionar, onRegistrarIglesia }.
   - Se renderiza dentro de <AppFrame> en lugar de Perfil, de modo que
     header / bottom-nav / ancho de la app se respetan.
   - Suscribe a window.suscribirMisIglesias(uid, cb).
   - ESC dispara onClose para quien quiera atrás por teclado. */
(function () {
  const { useState, useEffect } = React;
  const { useAuth, BackIcon } = window;
  const getGestionarIglesia = () => window.GestionarIglesia;

  const BRAND = "#2563EB";

  function contarHorarios(horario) {
    if (!horario || typeof horario !== "object") return 0;
    return Object.keys(horario).length;
  }

  function MisIglesias({ onClose, onSeleccionar, onRegistrarIglesia }) {
    const { user } = useAuth();
    const [iglesias, setIglesias] = useState([]);
    const [cargando, setCargando] = useState(true);
    const [iglesiaGestionando, setIglesiaGestionando] = useState(null);

    const dark =
      typeof document !== "undefined" &&
      document.querySelector(".app-frame")?.classList.contains("dark");

    // ESC = atrás (teclado). Sin scroll-lock: ahora es un tab inline.
    useEffect(() => {
      const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
      document.addEventListener("keydown", onKey);
      return () => document.removeEventListener("keydown", onKey);
    }, [onClose]);

    // Suscripción a mis iglesias
    useEffect(() => {
      if (!user || !user.uid || typeof window.suscribirMisIglesias !== "function") {
        setCargando(false);
        return;
      }
      let activo = true;
      setCargando(true);
      const unsub = window.suscribirMisIglesias(user.uid, (arr) => {
        if (!activo) return;
        setIglesias(Array.isArray(arr) ? arr : []);
        setCargando(false);
      });
      return () => {
        activo = false;
        if (typeof unsub === "function") unsub();
      };
    }, [user && user.uid]);

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

    // Si el usuario eligió una iglesia, renderizamos GestionarIglesia en
    // lugar de la lista, aprovechando el mismo body de la app (no overlay).
    if (iglesiaGestionando && getGestionarIglesia()) {
      return React.createElement(getGestionarIglesia(), {
        iglesia: iglesiaGestionando,
        onClose: () => setIglesiaGestionando(null),
      });
    }

    const colorTexto = dark ? "#F0F0F0" : "#111827";
    const colorSecundario = dark ? "#9CA3AF" : "#6B7280";
    const colorMuted = dark ? "#6B7280" : "#9CA3AF";
    const colorBorde = dark ? "#2A2A2A" : "#E5E7EB";
    const bgPanel = dark ? "#0F0F10" : "#FFFFFF";
    const bgCard = dark ? "#1A1A1A" : "#FFFFFF";
    const bgPlaceholder = dark ? "#1F2937" : "#E0EAFF";

    const handleSeleccionar = (ig) => {
      setIglesiaGestionando(ig);
      if (typeof onSeleccionar === "function") onSeleccionar(ig);
    };

    const handleRegistrar = () => {
      if (typeof onRegistrarIglesia === "function") onRegistrarIglesia();
      else if (typeof onClose === "function") onClose();
    };

    return (
      <div className="fade-in" style={{ paddingBottom: 96 }}>
        {/* Encabezado inline dentro del body, sin bar propia.
            El header "CultoRD" y la BottomNav de la app siguen siendo el chrome. */}
        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "16px 16px 8px" }}>
          <button
            type="button"
            onClick={onClose}
            aria-label="Atrás"
            style={{
              width: 32,
              height: 32,
              borderRadius: 999,
              border: "none",
              background: "transparent",
              color: colorTexto,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              marginLeft: -6,
            }}
          >
            {BackIcon ? <BackIcon /> : <span style={{ fontSize: 20 }}>←</span>}
          </button>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 900, color: colorTexto }}>
            Mis iglesias
          </h2>
        </div>

        {/* Body */}
        <div style={{ padding: "4px 16px 32px" }}>
            {cargando && (
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  padding: "48px 16px",
                  gap: 12,
                }}
              >
                <div
                  style={{
                    width: 28,
                    height: 28,
                    border: "3px solid " + colorBorde,
                    borderTopColor: BRAND,
                    borderRadius: "50%",
                    animation: "spin 0.9s linear infinite",
                  }}
                />
                <div style={{ fontSize: 13, fontWeight: 700, color: colorSecundario }}>
                  Cargando tus iglesias…
                </div>
                <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
              </div>
            )}

            {!cargando && iglesias.length === 0 && (
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  textAlign: "center",
                  padding: "40px 20px",
                  gap: 10,
                }}
              >
                <div style={{ fontSize: 56, lineHeight: 1 }} aria-hidden>✉️</div>
                <div style={{ fontSize: 17, fontWeight: 900, color: colorTexto }}>
                  Aún no administras iglesias
                </div>
                <div
                  style={{
                    fontSize: 13,
                    fontWeight: 600,
                    color: colorSecundario,
                    maxWidth: 300,
                    lineHeight: 1.5,
                  }}
                >
                  El registro de iglesias en CultoRD es <strong>por invitación
                  del equipo</strong>. Si usted es pastor y desea registrar
                  su congregación, por favor contacte al equipo CultoRD para
                  recibir su enlace de invitación.
                </div>
              </div>
            )}

            {!cargando && iglesias.length > 0 && (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {iglesias.map((ig) => {
                  const activa = ig.activa !== false;
                  const cntHor = contarHorarios(ig.horario);
                  return (
                    <div
                      key={ig.id}
                      style={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 0,
                        width: "100%",
                        borderRadius: 18,
                        border: "1px solid " + colorBorde,
                        background: bgCard,
                        boxShadow: dark
                          ? "0 1px 2px rgba(0,0,0,0.3)"
                          : "0 1px 2px rgba(16,24,40,0.06)",
                        overflow: "hidden",
                        fontFamily: "inherit",
                      }}
                    >
                    <button
                      type="button"
                      onClick={() => handleSeleccionar(ig)}
                      style={{
                        display: "flex",
                        gap: 12,
                        alignItems: "stretch",
                        width: "100%",
                        padding: 12,
                        border: "none",
                        background: "transparent",
                        cursor: "pointer",
                        textAlign: "left",
                        fontFamily: "inherit",
                      }}
                    >
                      {ig.imagen_url ? (
                        <img
                          src={ig.imagen_url}
                          alt=""
                          referrerPolicy="no-referrer"
                          style={{
                            width: 56,
                            height: 56,
                            borderRadius: 14,
                            objectFit: "cover",
                            flexShrink: 0,
                            background: bgPlaceholder,
                          }}
                        />
                      ) : (
                        <div
                          style={{
                            width: 56,
                            height: 56,
                            borderRadius: 14,
                            background: bgPlaceholder,
                            flexShrink: 0,
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            fontSize: 26,
                          }}
                          aria-hidden
                        >
                          🏠
                        </div>
                      )}

                      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 4 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                          <span
                            style={{
                              fontSize: 15,
                              fontWeight: 900,
                              color: colorTexto,
                              lineHeight: 1.2,
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                              whiteSpace: "nowrap",
                              maxWidth: "100%",
                            }}
                          >
                            {ig.nombre || "Sin nombre"}
                          </span>
                          <span
                            style={{
                              fontSize: 10,
                              fontWeight: 800,
                              padding: "2px 8px",
                              borderRadius: 999,
                              background: activa
                                ? (dark ? "#064E3B" : "#DCFCE7")
                                : (dark ? "#374151" : "#E5E7EB"),
                              color: activa
                                ? (dark ? "#6EE7B7" : "#166534")
                                : (dark ? "#9CA3AF" : "#6B7280"),
                              textTransform: "uppercase",
                              letterSpacing: 0.4,
                              whiteSpace: "nowrap",
                            }}
                          >
                            {activa ? "✓ Activa" : "Pausada"}
                          </span>
                        </div>

                        {ig.direccion_texto && (
                          <div
                            style={{
                              fontSize: 12,
                              fontWeight: 600,
                              color: colorSecundario,
                              overflow: "hidden",
                              textOverflow: "ellipsis",
                              whiteSpace: "nowrap",
                            }}
                          >
                            {ig.direccion_texto}
                          </div>
                        )}

                        <div
                          style={{
                            fontSize: 11,
                            fontWeight: 700,
                            color: colorMuted,
                          }}
                        >
                          {cntHor === 0
                            ? "Sin horarios"
                            : cntHor === 1
                            ? "1 horario publicado"
                            : cntHor + " horarios publicados"}
                        </div>
                      </div>

                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          flexShrink: 0,
                          paddingLeft: 4,
                        }}
                      >
                        <span
                          style={{
                            fontSize: 12,
                            fontWeight: 800,
                            color: BRAND,
                            letterSpacing: 0.3,
                            whiteSpace: "nowrap",
                          }}
                        >
                          Gestionar →
                        </span>
                      </div>
                    </button>

                    </div>
                  );
                })}

                {/* Registrar otra — solo visible para pastores ya establecidos
                    (tienen ≥ 1 iglesia). El perfil se gana al aceptar la
                    invitación inicial y registrar la primera iglesia. */}
                <button
                  type="button"
                  onClick={handleRegistrar}
                  style={{
                    width: "100%",
                    padding: "14px 16px",
                    borderRadius: 18,
                    border: "1.5px dashed " + (dark ? "#374151" : "#CBD5E1"),
                    background: "transparent",
                    color: BRAND,
                    fontSize: 13,
                    fontWeight: 800,
                    cursor: "pointer",
                    letterSpacing: 0.2,
                  }}
                >
                  + Registrar otra iglesia
                </button>
              </div>
            )}
        </div>

      </div>
    );
  }

  window.MisIglesias = MisIglesias;
})();
