/* ListaAsistentes → window. Pantalla INLINE (no portal) que muestra
   quiénes marcaron "Asistiré" en una actividad. Se abre desde
   GestionarActividades con early-return, manteniendo Header y
   BottomNav de la app visibles.

   Props:
     - iglesia: { id, nombre, imagen_url }
     - actividad: objeto con { id, titulo, fecha_inicio, fecha_fin,
         hora, tipo, imagen_url }
     - onCerrar: () => void

   Permisos:
     - Las REGLAS RTDB permiten lectura a cualquier autenticado.
     - La UI se abre sólo desde GestionarActividades (pastor/super/rol
       actividades_espirituales), así que no volvemos a chequear acá.
*/
(function () {
  const { useState, useEffect, useMemo } = React;
  const { useTheme, BackIcon, TIPOS_ACTIVIDAD, tiempoRelativo } = window;

  const BRAND = "#2563EB";
  const BRAND_DARK = "#1E4ED8";
  const INK = "#3C3C3C";
  const MUTED = "#777";

  const DIAS = ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"];
  const MESES = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];

  function fmtFecha(ms) {
    if (typeof ms !== "number") return "";
    const d = new Date(ms);
    return DIAS[d.getDay()] + " " + d.getDate() + " " + MESES[d.getMonth()];
  }

  function fmtHora12(hhmm) {
    if (!hhmm || !/^\d{2}:\d{2}$/.test(hhmm)) return hhmm || "";
    const [h, m] = hhmm.split(":").map(Number);
    const period = h >= 12 ? "PM" : "AM";
    const hr = h % 12 || 12;
    return hr + ":" + String(m).padStart(2, "0") + " " + period;
  }

  function iniciales(s) {
    return String(s || "?").trim().charAt(0).toUpperCase();
  }

  function badgeTipoPerfil(tipo) {
    if (tipo === "pastor") return { emoji: "⛪", label: "Pastor" };
    if (tipo === "miembro") return { emoji: "👤", label: "Miembro" };
    return { emoji: "🤝", label: "Amigo" };
  }

  async function compartirActividad(iglesia, actividad) {
    // Enlace profundo al detalle de la iglesia. Cuando exista un
    // deep-link directo a la actividad, cambiar acá.
    const host = "https://cultord-397bc.web.app";
    const url = iglesia && iglesia.id ? host + "/?i=" + iglesia.id : host;
    const titulo = actividad && actividad.titulo ? actividad.titulo : "Actividad de CultoRD";
    const texto = "Te invito a " + titulo + " en " + (iglesia && iglesia.nombre ? iglesia.nombre : "nuestra iglesia");
    try {
      if (navigator.share) {
        await navigator.share({ title: titulo, text: texto, url: url });
        return "nativo";
      }
    } catch (e) {
      if (e && e.name === "AbortError") return "cancelado";
    }
    // Fallback: WhatsApp deeplink.
    const wa = "https://wa.me/?text=" + encodeURIComponent(texto + "\n\n" + url);
    try { window.open(wa, "_blank", "noopener,noreferrer"); return "whatsapp"; } catch (_) { return "error"; }
  }

  function ListaAsistentes({ iglesia, actividad, onCerrar }) {
    const { dark } = (typeof useTheme === "function" ? useTheme() : { dark: false }) || { dark: false };

    const colorTexto = dark ? "#F0F0F0" : INK;
    const colorSecundario = dark ? "#9CA3AF" : MUTED;
    const colorMuted = dark ? "#6B7280" : "#9CA3AF";
    const colorBorde = dark ? "#2A2A2A" : "#E5E7EB";
    const bgCard = dark ? "#1A1A1A" : "#FFFFFF";
    const bgSubtle = dark ? "#141415" : "#F9FAFB";
    const bgPlaceholder = dark ? "#1F2937" : "#E0EAFF";
    const bgSkeleton = dark ? "#262626" : "#EDEFF3";
    const bgGradHeader = dark
      ? "linear-gradient(180deg, #0B1B3D 0%, #0F0F10 100%)"
      : "linear-gradient(180deg, #EFF6FF 0%, #FFFFFF 100%)";

    const [asistentes, setAsistentes] = useState([]);
    const [cargando, setCargando] = useState(true);
    const [ahoraTick, setAhoraTick] = useState(Date.now());
    const [compartiendo, setCompartiendo] = useState(false);

    // ESC cierra.
    useEffect(function () {
      const onKey = function (e) { if (e.key === "Escape") onCerrar && onCerrar(); };
      document.addEventListener("keydown", onKey);
      return function () { document.removeEventListener("keydown", onKey); };
    }, [onCerrar]);

    // Refresh del tiempo relativo cada 60s.
    useEffect(function () {
      const id = setInterval(function () { setAhoraTick(Date.now()); }, 60000);
      return function () { clearInterval(id); };
    }, []);

    useEffect(function () {
      if (!iglesia || !iglesia.id || !actividad || !actividad.id) return;
      if (typeof window.suscribirAsistentesDeActividad !== "function") {
        setCargando(false);
        setAsistentes([]);
        return;
      }
      setCargando(true);
      const unsub = window.suscribirAsistentesDeActividad(iglesia.id, actividad.id, function (arr) {
        setAsistentes(Array.isArray(arr) ? arr : []);
        setCargando(false);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [iglesia && iglesia.id, actividad && actividad.id]);

    const resumen = useMemo(function () {
      let deIglesia = 0, visitantes = 0;
      asistentes.forEach(function (a) {
        if (a.es_de_iglesia) deIglesia++;
        else visitantes++;
      });
      return { total: asistentes.length, deIglesia: deIglesia, visitantes: visitantes };
    }, [asistentes]);

    const t = (TIPOS_ACTIVIDAD && actividad && TIPOS_ACTIVIDAD[actividad.tipo])
      || (TIPOS_ACTIVIDAD && TIPOS_ACTIVIDAD.otro)
      || { emoji: "✨", label: "Evento" };

    async function handleCompartir() {
      if (compartiendo) return;
      setCompartiendo(true);
      try { await compartirActividad(iglesia, actividad); }
      finally { setCompartiendo(false); }
    }

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

    return (
      <div className="fade-in" style={{ paddingBottom: 96 }}>
        {/* Header con gradient sutil */}
        <div
          style={{
            background: bgGradHeader,
            padding: "14px 14px 16px",
            borderBottom: "1px solid " + colorBorde,
          }}
        >
          <div style={{ display: "flex", alignItems: "flex-start", gap: 6 }}>
            <button
              type="button"
              onClick={onCerrar}
              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",
                flexShrink: 0, marginLeft: -6,
              }}
            >
              {BackIcon ? <BackIcon /> : <span style={{ fontSize: 20 }}>←</span>}
            </button>
            <div style={{ flex: 1, minWidth: 0, paddingTop: 2 }}>
              <div style={{ fontSize: 18, fontWeight: 900, color: colorTexto, lineHeight: 1.15 }}>
                Asistentes
              </div>
              {actividad && actividad.titulo && (
                <div
                  style={{
                    fontSize: 12, fontWeight: 700, color: colorSecundario,
                    marginTop: 2,
                    display: "-webkit-box",
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: "vertical",
                    overflow: "hidden",
                  }}
                >
                  <span aria-hidden style={{ marginRight: 4 }}>{t.emoji}</span>
                  {actividad.titulo}
                </div>
              )}
              {actividad && typeof actividad.fecha_inicio === "number" && (
                <div style={{ fontSize: 11, fontWeight: 700, color: colorMuted, marginTop: 3 }}>
                  📅 {fmtFecha(actividad.fecha_inicio)}
                  {actividad.hora ? "  ·  🕒 " + fmtHora12(actividad.hora) : ""}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Resumen en card */}
        <div style={{ padding: "14px 16px 6px" }}>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, minmax(0, 1fr))",
              gap: 8,
              padding: 12,
              background: bgCard,
              border: "1px solid " + colorBorde,
              borderRadius: 14,
            }}
          >
            <ResumenItem
              emoji="✋"
              etiqueta="Total"
              valor={resumen.total}
              colorTexto={colorTexto}
              colorSec={colorSecundario}
            />
            <ResumenItem
              emoji="⛪"
              etiqueta="De la iglesia"
              valor={resumen.deIglesia}
              colorTexto={colorTexto}
              colorSec={colorSecundario}
            />
            <ResumenItem
              emoji="🤝"
              etiqueta="Visitantes"
              valor={resumen.visitantes}
              colorTexto={colorTexto}
              colorSec={colorSecundario}
            />
          </div>
        </div>

        {/* Lista o empty state / skeleton */}
        <div style={{ padding: "10px 0 0" }}>
          {cargando && (
            <div style={{ display: "flex", flexDirection: "column" }}>
              {[0, 1, 2].map(function (i) { return (
                <div
                  key={i}
                  style={{
                    display: "flex", alignItems: "center", gap: 12,
                    padding: "12px 16px",
                    borderBottom: "1px solid " + colorBorde,
                  }}
                >
                  <div style={{ width: 48, height: 48, borderRadius: "50%", background: bgSkeleton }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ height: 12, width: "45%", borderRadius: 6, background: bgSkeleton, marginBottom: 6 }} />
                    <div style={{ height: 10, width: "30%", borderRadius: 6, background: bgSkeleton }} />
                  </div>
                </div>
              ); })}
              <style>{`
                @keyframes laskeletonPulse { 0%, 100% { opacity: 1 } 50% { opacity: 0.6 } }
              `}</style>
            </div>
          )}

          {!cargando && asistentes.length === 0 && (
            <div
              style={{
                display: "flex", flexDirection: "column",
                alignItems: "center", textAlign: "center",
                padding: "40px 24px", gap: 12,
              }}
            >
              <div style={{ fontSize: 48, lineHeight: 1 }} aria-hidden>✋</div>
              <div style={{ fontSize: 15, fontWeight: 900, color: colorTexto }}>
                Aún nadie ha marcado
              </div>
              <div
                style={{
                  fontSize: 13, fontWeight: 600, color: colorSecundario,
                  maxWidth: 320, lineHeight: 1.5,
                }}
              >
                Comparta esta actividad para que más personas la vean y marquen que asistirán.
              </div>
              <button
                type="button"
                onClick={handleCompartir}
                disabled={compartiendo}
                style={{
                  marginTop: 4,
                  padding: "12px 18px",
                  borderRadius: 999,
                  border: "none",
                  background: BRAND,
                  color: "#FFFFFF",
                  fontSize: 13, fontWeight: 900,
                  cursor: compartiendo ? "default" : "pointer",
                  boxShadow: "0 4px 0 " + BRAND_DARK,
                  opacity: compartiendo ? 0.7 : 1,
                  letterSpacing: 0.3,
                  display: "inline-flex", alignItems: "center", gap: 8,
                  fontFamily: "inherit",
                }}
              >
                <span aria-hidden>📤</span>
                <span>Compartir actividad</span>
              </button>
            </div>
          )}

          {!cargando && asistentes.length > 0 && (
            <div>
              {asistentes.map(function (a) {
                const badge = badgeTipoPerfil(a.perfil_tipo);
                return (
                  <div
                    key={a.uid}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 12,
                      padding: "12px 16px",
                      background: bgCard,
                      borderBottom: "1px solid " + colorBorde,
                    }}
                  >
                    {a.foto_url ? (
                      <img
                        src={a.foto_url}
                        alt=""
                        referrerPolicy="no-referrer"
                        style={{
                          width: 48, height: 48, borderRadius: "50%",
                          objectFit: "cover", flexShrink: 0, background: bgPlaceholder,
                        }}
                      />
                    ) : (
                      <div
                        aria-hidden
                        style={{
                          width: 48, height: 48, borderRadius: "50%",
                          background: bgPlaceholder, flexShrink: 0,
                          display: "flex", alignItems: "center", justifyContent: "center",
                          fontSize: 18, color: BRAND, fontWeight: 900,
                        }}
                      >
                        {iniciales(a.nombre)}
                      </div>
                    )}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div
                        style={{
                          fontSize: 14, fontWeight: 900, color: colorTexto,
                          lineHeight: 1.2,
                          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                        }}
                      >
                        {a.nombre || "Sin nombre"}
                      </div>
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 4 }}>
                        <span
                          style={{
                            display: "inline-flex", alignItems: "center", gap: 4,
                            fontSize: 10, fontWeight: 800, letterSpacing: 0.3,
                            padding: "2px 8px", borderRadius: 999,
                            background: dark ? "#1F2937" : "#EEF2FF",
                            color: dark ? "#C7D2FE" : BRAND_DARK,
                          }}
                        >
                          <span aria-hidden>{badge.emoji}</span>
                          <span>{badge.label}</span>
                        </span>
                        {a.es_de_iglesia ? (
                          <span
                            style={{
                              display: "inline-flex", alignItems: "center", gap: 4,
                              fontSize: 10, fontWeight: 800, letterSpacing: 0.3,
                              padding: "2px 8px", borderRadius: 999,
                              background: dark ? "#064E3B" : "#DCFCE7",
                              color: dark ? "#6EE7B7" : "#166534",
                            }}
                          >
                            <span aria-hidden>✓</span>
                            <span>De tu iglesia</span>
                          </span>
                        ) : (
                          <span
                            style={{
                              display: "inline-flex", alignItems: "center", gap: 4,
                              fontSize: 10, fontWeight: 800, letterSpacing: 0.3,
                              padding: "2px 8px", borderRadius: 999,
                              background: dark ? "#262626" : "#F3F4F6",
                              color: colorSecundario,
                            }}
                          >
                            Visitante
                          </span>
                        )}
                      </div>
                    </div>
                    <div
                      style={{
                        fontSize: 11, fontWeight: 700, color: colorMuted,
                        flexShrink: 0, whiteSpace: "nowrap",
                      }}
                      title={a.creado_en ? new Date(a.creado_en).toLocaleString() : ""}
                    >
                      {typeof tiempoRelativo === "function" && a.creado_en
                        ? "Marcó " + tiempoRelativo(a.creado_en)
                        : ""}
                      {/* `ahoraTick` fuerza re-render para refrescar el relativo */}
                      <span style={{ display: "none" }}>{ahoraTick}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Mini-footer con subtle hint para super / rol */}
        {!cargando && asistentes.length > 0 && (
          <div
            style={{
              padding: "16px 16px 0",
              textAlign: "center",
              fontSize: 11, fontWeight: 700,
              color: colorMuted,
              letterSpacing: 0.3,
            }}
          >
            Lista actualizada en tiempo real
          </div>
        )}
      </div>
    );
  }

  function ResumenItem({ emoji, etiqueta, valor, colorTexto, colorSec }) {
    return (
      <div
        style={{
          display: "flex", flexDirection: "column", alignItems: "center",
          textAlign: "center", gap: 4,
        }}
      >
        <div style={{ fontSize: 18, lineHeight: 1 }} aria-hidden>{emoji}</div>
        <div style={{ fontSize: 18, fontWeight: 900, color: colorTexto, lineHeight: 1 }}>
          {valor}
        </div>
        <div
          style={{
            fontSize: 10, fontWeight: 800, color: colorSec,
            textTransform: "uppercase", letterSpacing: 0.4,
          }}
        >
          {etiqueta}
        </div>
      </div>
    );
  }

  window.ListaAsistentes = ListaAsistentes;
})();
