/* AsignarRolModal → window. Bottom sheet para asignar un rol del
   catálogo a un miembro existente de una iglesia, con duración.
   Se abre desde AdminIglesia (panel del pastor).

   Props:
     rol      objeto del ROLES_CATALOGO (id, nombre, emoji, descripcion)
     iglesia  { id, nombre }
     dark     boolean (tema activo — el padre lo pasa para evitar doble lookup)
     onCerrar ()
     onAsignar(miembroUid, duracionHoras) → Promise<boolean>
*/
(function () {
  const { useState, useEffect, useMemo } = React;

  const BRAND = "#2563EB";
  const GREEN = "#58CC02";
  const GREEN_SHADOW = "#46A302";
  const INK = "#3C3C3C";

  const OPCIONES_DURACION = [
    { id: "24h", label: "24 horas",  horas: 24 },
    { id: "7d",  label: "7 días",    horas: 7 * 24 },
    { id: "30d", label: "30 días",   horas: 30 * 24 },
    { id: "inf", label: "Indefinido", horas: null },
  ];

  function AsignarRolModal({ rol, iglesia, dark, onCerrar, onAsignar }) {
    const colorTexto = dark ? "#F0F0F0" : INK;
    const colorSecundario = dark ? "#9CA3AF" : "#777";
    const colorBorde = dark ? "#2A2A2A" : "#DDD";
    const bgSheet = dark ? "#1A1A1A" : "#FFFFFF";
    const bgInput = dark ? "#141415" : "#FFFFFF";
    const bgHandle = dark ? "#2A2A2A" : "#E5E5E5";
    const bgCardItem = dark ? "#141415" : "#F9FAFB";
    const bgPlaceholder = dark ? "#1F2937" : "#E0EAFF";
    const bgCheckSelected = dark ? "#064E3B" : "#DCFCE7";
    const colorCheck = dark ? "#6EE7B7" : "#166534";

    const [miembros, setMiembros] = useState([]);
    const [cargando, setCargando] = useState(true);
    const [miembroSeleccionado, setMiembroSeleccionado] = useState(null);
    const [duracionId, setDuracionId] = useState("7d");
    const [guardando, setGuardando] = useState(false);
    const [error, setError] = useState("");

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

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

    const duracionSeleccionada = useMemo(function () {
      return OPCIONES_DURACION.find(function (o) { return o.id === duracionId; }) || OPCIONES_DURACION[1];
    }, [duracionId]);

    async function handleAsignar() {
      if (guardando) return;
      setError("");
      if (!miembroSeleccionado) {
        setError("Seleccione un miembro para asignar el rol.");
        return;
      }
      setGuardando(true);
      try {
        const ok = await onAsignar(miembroSeleccionado.uid, duracionSeleccionada.horas);
        if (!ok) {
          setError("No pudimos asignar el rol. Intente de nuevo.");
        }
      } finally {
        setGuardando(false);
      }
    }

    if (typeof document === "undefined" || !rol) return null;

    const content = (
      <div
        style={{
          position: "fixed", inset: 0, zIndex: 72,
          background: "rgba(0,0,0,0.45)",
          display: "flex", alignItems: "flex-end", justifyContent: "center",
          animation: "asgnRolFade 180ms ease-out",
        }}
        onClick={function () { if (!guardando) onCerrar && onCerrar(); }}
      >
        <div
          onClick={function (e) { e.stopPropagation(); }}
          style={{
            width: "100%", maxWidth: 430,
            background: bgSheet,
            borderTopLeftRadius: 20, borderTopRightRadius: 20,
            padding: "18px 18px 22px",
            maxHeight: "92vh",
            display: "flex", flexDirection: "column",
            animation: "asgnRolSlideUp 260ms cubic-bezier(.2,.9,.3,1.2)",
          }}
        >
          <div
            style={{
              width: 44, height: 4, borderRadius: 999,
              background: bgHandle, margin: "0 auto 14px",
            }}
            aria-hidden
          />

          <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: 14 }}>
            <div style={{ fontSize: 32, lineHeight: 1 }} aria-hidden>{rol.emoji}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: colorSecundario, textTransform: "uppercase", letterSpacing: 0.4 }}>
                Asignar rol
              </div>
              <div style={{ fontSize: 17, fontWeight: 900, color: colorTexto, lineHeight: 1.2, marginTop: 2 }}>
                {rol.nombre}
              </div>
              {iglesia && iglesia.nombre && (
                <div style={{ fontSize: 11, fontWeight: 700, color: colorSecundario, marginTop: 4 }}>
                  🏠 {iglesia.nombre}
                </div>
              )}
            </div>
          </div>

          {/* Selector de miembro */}
          <div style={{ fontSize: 12, fontWeight: 800, color: colorTexto, textTransform: "uppercase", letterSpacing: 0.3, marginBottom: 8 }}>
            Miembro
          </div>
          <div
            style={{
              flex: 1,
              minHeight: 120,
              maxHeight: 260,
              overflowY: "auto",
              WebkitOverflowScrolling: "touch",
              border: "1px solid " + colorBorde,
              borderRadius: 12,
              marginBottom: 14,
              background: bgInput,
            }}
          >
            {cargando && (
              <div
                style={{
                  display: "flex", flexDirection: "column",
                  alignItems: "center", padding: 24, gap: 8,
                }}
              >
                <div
                  style={{
                    width: 22, height: 22,
                    border: "3px solid " + colorBorde,
                    borderTopColor: BRAND,
                    borderRadius: "50%",
                    animation: "asgnRolSpin 0.9s linear infinite",
                  }}
                />
                <div style={{ fontSize: 12, fontWeight: 700, color: colorSecundario }}>
                  Cargando miembros…
                </div>
              </div>
            )}

            {!cargando && miembros.length === 0 && (
              <div
                style={{
                  padding: 20, textAlign: "center",
                  fontSize: 13, fontWeight: 600, color: colorSecundario,
                }}
              >
                Primero invite miembros a su iglesia.
              </div>
            )}

            {!cargando && miembros.map(function (m) {
              const seleccionado = miembroSeleccionado && miembroSeleccionado.uid === m.uid;
              return (
                <button
                  key={m.uid}
                  type="button"
                  onClick={function () { setMiembroSeleccionado(m); }}
                  style={{
                    display: "flex",
                    width: "100%",
                    alignItems: "center",
                    gap: 10,
                    padding: "10px 12px",
                    background: seleccionado ? bgCheckSelected : bgCardItem,
                    border: "none",
                    borderBottom: "1px solid " + colorBorde,
                    cursor: "pointer",
                    textAlign: "left",
                    fontFamily: "inherit",
                  }}
                >
                  {m.foto_url ? (
                    <img
                      src={m.foto_url}
                      alt=""
                      referrerPolicy="no-referrer"
                      style={{
                        width: 32, height: 32, borderRadius: "50%",
                        objectFit: "cover", flexShrink: 0, background: bgPlaceholder,
                      }}
                    />
                  ) : (
                    <div
                      aria-hidden
                      style={{
                        width: 32, height: 32, borderRadius: "50%",
                        background: bgPlaceholder, flexShrink: 0,
                        display: "flex", alignItems: "center", justifyContent: "center",
                        fontSize: 14, color: BRAND, fontWeight: 900,
                      }}
                    >
                      {(m.nombre || m.email || "?").trim().charAt(0).toUpperCase()}
                    </div>
                  )}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div
                      style={{
                        fontSize: 13, fontWeight: 800, color: colorTexto,
                        overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                      }}
                    >
                      {m.nombre || "Sin nombre"}
                    </div>
                    {m.email && (
                      <div
                        style={{
                          fontSize: 11, fontWeight: 600, color: colorSecundario,
                          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                        }}
                      >
                        {m.email}
                      </div>
                    )}
                  </div>
                  {seleccionado && (
                    <div
                      aria-hidden
                      style={{
                        flexShrink: 0, fontSize: 16, fontWeight: 900,
                        color: colorCheck,
                      }}
                    >
                      ✓
                    </div>
                  )}
                </button>
              );
            })}
          </div>

          {/* Selector de duración */}
          <div style={{ fontSize: 12, fontWeight: 800, color: colorTexto, textTransform: "uppercase", letterSpacing: 0.3, marginBottom: 8 }}>
            Duración
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 14 }}>
            {OPCIONES_DURACION.map(function (o) {
              const active = duracionId === o.id;
              return (
                <button
                  key={o.id}
                  type="button"
                  onClick={function () { setDuracionId(o.id); }}
                  style={{
                    border: "1px solid " + (active ? BRAND : colorBorde),
                    background: active ? BRAND : bgInput,
                    color: active ? "#FFFFFF" : colorTexto,
                    fontSize: 13, fontWeight: 700,
                    padding: "8px 12px", borderRadius: 999, cursor: "pointer",
                  }}
                >
                  {o.label}
                </button>
              );
            })}
          </div>

          {error && (
            <div style={{ fontSize: 13, color: "#FF4B4B", fontWeight: 700, marginBottom: 10 }}>
              {error}
            </div>
          )}

          <div style={{ display: "flex", gap: 8 }}>
            <button
              type="button"
              onClick={onCerrar}
              disabled={guardando}
              style={{
                flex: 1, height: 50, border: "1px solid " + colorBorde, background: bgInput, color: colorTexto,
                fontSize: 15, fontWeight: 800, borderRadius: 12,
                cursor: guardando ? "default" : "pointer",
                opacity: guardando ? 0.6 : 1,
              }}
            >
              Cancelar
            </button>
            <button
              type="button"
              onClick={handleAsignar}
              disabled={guardando || cargando || miembros.length === 0}
              style={{
                flex: 2, height: 50, border: "none",
                background: GREEN, color: "#FFFFFF",
                fontSize: 16, fontWeight: 800, borderRadius: 12,
                cursor: (guardando || cargando || miembros.length === 0) ? "default" : "pointer",
                boxShadow: "0 4px 0 " + GREEN_SHADOW,
                opacity: (guardando || cargando || miembros.length === 0) ? 0.6 : 1,
              }}
            >
              {guardando ? "Asignando..." : "Asignar rol"}
            </button>
          </div>
        </div>

        <style>{`
          @keyframes asgnRolFade { from { opacity: 0 } to { opacity: 1 } }
          @keyframes asgnRolSlideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
          @keyframes asgnRolSpin { to { transform: rotate(360deg); } }
        `}</style>
      </div>
    );

    return ReactDOM.createPortal(content, document.body);
  }

  window.AsignarRolModal = AsignarRolModal;
})();
