/* ActividadCard → window. Card de feed estilo Instagram/Facebook para
   una actividad publicada por una iglesia. Se renderiza en Home con
   un listado ordenado por publicado_en desc (las nuevas empujan a las
   viejas hacia abajo).

   Props:
     - actividad: objeto con { id, titulo, tipo, tipo_otro, fecha_inicio,
         fecha_fin, hora, ubicacion, descripcion, imagen_url,
         publicado_en, iglesia: { id, nombre, imagen_url } }
     - onTapIglesia(iglesiaLite) → abre DetalleIglesia de esa iglesia.
*/
(function () {
  const { useState, useEffect, useRef } = React;
  const { useAuth, useTheme, TIPOS_ACTIVIDAD, tiempoRelativo } = window;

  const BRAND = "#2563EB";
  const INK = "#3C3C3C";

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

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

  function fmtRango(ini, fin) {
    if (typeof ini !== "number") return "";
    const a = new Date(ini);
    const b = typeof fin === "number" ? new Date(fin) : a;
    const mismoDia = a.getFullYear() === b.getFullYear()
      && a.getMonth() === b.getMonth()
      && a.getDate() === b.getDate();
    if (mismoDia) return fmtFechaCorta(ini);
    return fmtFechaCorta(ini) + " → " + fmtFechaCorta(fin);
  }

  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();
  }

  // Fila tipo reacción de FB: contador a la izquierda y botón pill a
  // la derecha. Al marcar muestra un badge flotante "Asistiré" con
  // fade+slide hacia arriba; al desmarcar no dice nada.
  function RsvpRow({ dark, yoAsistire, total, bouncing, mostrandoBadge, onToggle, colorTexto, colorSecundario, colorBorde }) {
    const bgMarcado = dark ? "rgba(88,204,2,0.15)" : "#E8F5E9";
    const colorMarcado = dark ? "#9CE57A" : "#2E7D32";
    const bgBadgeFlotante = dark ? "#064E3B" : "#DCFCE7";
    const colorBadgeFlotante = dark ? "#6EE7B7" : "#166534";
    const borderBadgeFlotante = dark ? "#065F46" : "#86EFAC";

    const labelTotal = total > 0
      ? total + (total === 1 ? " persona asistirá" : " personas asistirán")
      : "Sé el primero en marcar";

    return (
      <div
        style={{
          position: "relative",
          borderTop: "1px solid " + colorBorde,
          padding: "10px 16px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 12,
        }}
      >
        <div
          style={{
            fontSize: 12,
            fontWeight: 600,
            color: total > 0 ? colorTexto : colorSecundario,
            minWidth: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {labelTotal}
        </div>

        <button
          type="button"
          onClick={onToggle}
          className={bouncing ? "rsvp-bounce" : ""}
          aria-label={yoAsistire ? "Quitar que asistirá" : "Marcar que asistiré"}
          aria-pressed={yoAsistire}
          style={{
            flexShrink: 0,
            width: 40,
            height: 40,
            padding: 0,
            borderRadius: 999,
            border: "1px solid " + (yoAsistire ? (dark ? "#065F46" : "#A7F3D0") : colorBorde),
            background: yoAsistire ? bgMarcado : "transparent",
            color: yoAsistire ? colorMarcado : colorTexto,
            cursor: "pointer",
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            fontFamily: "inherit",
            fontSize: 20,
            lineHeight: 1,
            transition: "background 180ms ease, color 180ms ease, border-color 180ms ease",
          }}
        >
          <span aria-hidden>✋</span>
        </button>

        {/* Badge flotante de confirmación — solo al marcar. */}
        {mostrandoBadge && (
          <div
            aria-hidden
            className="rsvp-badge"
            style={{
              position: "absolute",
              right: 16,
              top: -6,
              padding: "5px 11px",
              borderRadius: 999,
              background: bgBadgeFlotante,
              color: colorBadgeFlotante,
              fontSize: 11,
              fontWeight: 900,
              letterSpacing: 0.3,
              border: "1px solid " + borderBadgeFlotante,
              boxShadow: "0 6px 20px rgba(22,101,52,0.25)",
              pointerEvents: "none",
              whiteSpace: "nowrap",
            }}
          >
            Asistiré ✨
          </div>
        )}

        <style>{`
          @keyframes rsvpBadgeIn {
            0%   { opacity: 0; transform: translateY(6px) scale(0.85); }
            18%  { opacity: 1; transform: translateY(-18px) scale(1.06); }
            55%  { opacity: 1; transform: translateY(-22px) scale(1); }
            100% { opacity: 0; transform: translateY(-40px) scale(0.95); }
          }
          .rsvp-badge { animation: rsvpBadgeIn 1.6s cubic-bezier(.2,.9,.3,1.2) forwards; }

          @keyframes rsvpBounce {
            0%, 100% { transform: scale(1); }
            40%      { transform: scale(1.09); }
            70%      { transform: scale(0.96); }
          }
          .rsvp-bounce { animation: rsvpBounce 420ms cubic-bezier(.2,.9,.3,1.2); }
        `}</style>
      </div>
    );
  }

  function ActividadCard({ actividad, onTapIglesia, ahoraTick }) {
    // ahoraTick no se usa directamente; le pasamos el tick desde el
    // padre para forzar re-render del "hace X" cada 60s.
    void ahoraTick;

    const { dark } = (typeof useTheme === "function" ? useTheme() : { dark: false }) || { dark: false };

    const colorTexto = dark ? "#F0F0F0" : "#111827";
    const colorSecundario = dark ? "#9CA3AF" : "#6B7280";
    const colorMuted = dark ? "#6B7280" : "#9CA3AF";
    const colorBorde = dark ? "#2A2A2A" : "#E5E7EB";
    const bgCard = dark ? "#1A1A1A" : "#FFFFFF";
    const bgPlaceholder = dark ? "#1F2937" : "#E0EAFF";
    const bgBadge = dark ? "#1F2937" : "#EEF2FF";
    const colorBadge = dark ? "#C7D2FE" : "#1E4ED8";
    const bgFlyer = dark ? "#0F0F10" : "#F3F4F6";

    if (!actividad) return null;
    const ig = actividad.iglesia || { id: "", nombre: "", imagen_url: "" };
    const t = (TIPOS_ACTIVIDAD && TIPOS_ACTIVIDAD[actividad.tipo]) || (TIPOS_ACTIVIDAD && TIPOS_ACTIVIDAD.otro) || { label: "Evento", emoji: "✨" };
    const tipoLabel = actividad.tipo === "otro" && actividad.tipo_otro
      ? actividad.tipo_otro
      : t.label;

    const hace = typeof tiempoRelativo === "function"
      ? tiempoRelativo(actividad.publicado_en)
      : "";

    const [lightboxOpen, setLightboxOpen] = useState(false);

    // --- RSVP "Asistiré" ---
    const { user } = (typeof useAuth === "function" ? useAuth() : {}) || {};
    const [yoAsistire, setYoAsistire] = useState(false);
    const [totalAsistire, setTotalAsistire] = useState(0);
    const [mostrandoBadge, setMostrandoBadge] = useState(false);
    const [bouncing, setBouncing] = useState(false);
    const guardandoRef = useRef(false);

    const iglesiaId = ig.id;
    const actividadId = actividad.id;

    useEffect(function () {
      if (!iglesiaId || !actividadId || typeof window.suscribirContadorAsistencia !== "function") return;
      const unsub = window.suscribirContadorAsistencia(iglesiaId, actividadId, function (n) {
        setTotalAsistire(n);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [iglesiaId, actividadId]);

    useEffect(function () {
      if (!user || !user.uid || !iglesiaId || !actividadId
          || typeof window.suscribirYoAsistire !== "function") {
        setYoAsistire(false);
        return;
      }
      const unsub = window.suscribirYoAsistire(iglesiaId, actividadId, user.uid, function (v) {
        setYoAsistire(!!v);
      });
      return function () { if (typeof unsub === "function") unsub(); };
    }, [user && user.uid, iglesiaId, actividadId]);

    async function toggleAsistire() {
      if (!user || !user.uid || !iglesiaId || !actividadId) return;
      if (guardandoRef.current) return;
      guardandoRef.current = true;
      try {
        if (yoAsistire) {
          // Desmarcar — sin animación ni mensaje.
          if (typeof window.desmarcarAsistire === "function") {
            await window.desmarcarAsistire(iglesiaId, actividadId, user.uid);
          }
        } else {
          // Marcar — dispara animación de confirmación.
          if (typeof window.marcarAsistire === "function") {
            await window.marcarAsistire(iglesiaId, actividadId, user, null);
          }
          setBouncing(true);
          setMostrandoBadge(true);
          setTimeout(function () { setBouncing(false); }, 420);
          setTimeout(function () { setMostrandoBadge(false); }, 1600);
        }
      } catch (e) {
        console.warn("[ActividadCard] toggle asistire falló:", e);
      } finally {
        guardandoRef.current = false;
      }
    }

    const handleIglesia = function () {
      if (typeof onTapIglesia === "function") {
        onTapIglesia({
          id: ig.id,
          nombre: ig.nombre || "",
          imagen_url: ig.imagen_url || "",
        });
      }
    };

    const handleFoto = function () {
      if (!actividad.imagen_url) return;
      setLightboxOpen(true);
    };

    return (
      <div
        style={{
          background: bgCard,
          borderBottom: "1px solid " + colorBorde,
          overflow: "hidden",
        }}
      >
        {/* Header: avatar iglesia + nombre + hace X */}
        <button
          type="button"
          onClick={handleIglesia}
          style={{
            display: "flex",
            alignItems: "center",
            gap: 10,
            padding: "12px 12px 10px",
            width: "100%",
            background: "transparent",
            border: "none",
            textAlign: "left",
            cursor: "pointer",
            fontFamily: "inherit",
          }}
        >
          {ig.imagen_url ? (
            <img
              src={ig.imagen_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: 16, color: BRAND, fontWeight: 900,
              }}
            >
              {iniciales(ig.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",
              }}
            >
              {ig.nombre || "Iglesia"}
            </div>
            <div style={{ fontSize: 11, fontWeight: 600, color: colorMuted, marginTop: 2 }}>
              {hace}
            </div>
          </div>
        </button>

        {/* Info superior: badge tipo + título + fecha/hora + ubicación.
            Va ANTES de la imagen (estilo evento en FB). */}
        <div style={{ padding: "0 14px 12px" }}>
          <div
            style={{
              display: "inline-flex", alignItems: "center", gap: 6,
              background: bgBadge, color: colorBadge,
              padding: "3px 10px", borderRadius: 999,
              fontSize: 10, fontWeight: 900, letterSpacing: 0.3,
              marginBottom: 8,
            }}
          >
            <span aria-hidden>{t.emoji}</span>
            <span>{tipoLabel}</span>
          </div>

          <div
            style={{
              fontSize: 16, fontWeight: 900, color: colorTexto,
              lineHeight: 1.25, marginBottom: 6,
            }}
          >
            {actividad.titulo || "Actividad"}
          </div>

          <div
            style={{
              fontSize: 12, fontWeight: 700, color: colorSecundario,
              display: "flex", flexWrap: "wrap", gap: 10,
            }}
          >
            <span>📅 {fmtRango(actividad.fecha_inicio, actividad.fecha_fin)}</span>
            {actividad.hora && <span>🕒 {fmtHora12(actividad.hora)}</span>}
          </div>

          {actividad.ubicacion && (
            <div
              style={{
                fontSize: 12, fontWeight: 600, color: colorSecundario, marginTop: 4,
                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
              }}
            >
              📍 {actividad.ubicacion}
            </div>
          )}
        </div>

        {/* Flyer (si existe) — aspect 3:4, ancho completo del card.
            Tap aquí abre el Lightbox (NO la iglesia). */}
        {actividad.imagen_url ? (
          <button
            type="button"
            onClick={handleFoto}
            aria-label="Ver foto"
            style={{
              width: "100%",
              aspectRatio: "3 / 4",
              maxHeight: "70vh",
              background: bgFlyer,
              overflow: "hidden",
              display: "flex", alignItems: "center", justifyContent: "center",
              border: "none",
              padding: 0,
              cursor: "zoom-in",
              fontFamily: "inherit",
            }}
          >
            <img
              src={actividad.imagen_url}
              alt={actividad.titulo || "Flyer"}
              referrerPolicy="no-referrer"
              style={{ width: "100%", height: "100%", objectFit: "cover", pointerEvents: "none" }}
            />
          </button>
        ) : (
          <div
            style={{
              width: "100%",
              aspectRatio: "3 / 4",
              maxHeight: "50vh",
              background: bgPlaceholder,
              display: "flex", alignItems: "center", justifyContent: "center",
              flexDirection: "column", gap: 6,
              color: dark ? "#9CA3AF" : "#6B7280",
            }}
          >
            <div style={{ fontSize: 56, lineHeight: 1 }} aria-hidden>{t.emoji}</div>
            <div style={{ fontSize: 13, fontWeight: 800 }}>{tipoLabel}</div>
          </div>
        )}

        {/* Fila RSVP — va entre imagen y descripción cuando hay imagen;
            si no hay imagen, va después de la descripción (más abajo). */}
        {actividad.imagen_url && user && (
          <RsvpRow
            dark={dark}
            yoAsistire={yoAsistire}
            total={totalAsistire}
            bouncing={bouncing}
            mostrandoBadge={mostrandoBadge}
            onToggle={toggleAsistire}
            colorTexto={colorTexto}
            colorSecundario={colorSecundario}
            colorBorde={colorBorde}
          />
        )}

        {/* Descripción (si existe) — DESPUÉS de la imagen. */}
        {actividad.descripcion && (
          <div style={{ padding: "12px 14px 14px" }}>
            <div
              style={{
                fontSize: 13, fontWeight: 500, color: colorTexto,
                lineHeight: 1.5,
                display: "-webkit-box",
                WebkitLineClamp: 4,
                WebkitBoxOrient: "vertical",
                overflow: "hidden",
                whiteSpace: "pre-wrap",
              }}
            >
              {actividad.descripcion}
            </div>
          </div>
        )}

        {/* Fila RSVP cuando NO hay imagen — queda al final del card. */}
        {!actividad.imagen_url && user && (
          <RsvpRow
            dark={dark}
            yoAsistire={yoAsistire}
            total={totalAsistire}
            bouncing={bouncing}
            mostrandoBadge={mostrandoBadge}
            onToggle={toggleAsistire}
            colorTexto={colorTexto}
            colorSecundario={colorSecundario}
            colorBorde={colorBorde}
          />
        )}

        {lightboxOpen && actividad.imagen_url && window.LightboxFoto && (
          React.createElement(window.LightboxFoto, {
            src: actividad.imagen_url,
            alt: actividad.titulo || "",
            onClose: function () { setLightboxOpen(false); },
          })
        )}
      </div>
    );
  }

  window.ActividadCard = ActividadCard;
})();
