/* AccionesMenu → window. Bottom sheet modal con opciones de "crear".
   Props: { abierto, onClose, onSeleccion, iglesiasCrearEvento }
     - iglesiasCrearEvento: array [{ id, nombre, imagen_url }] con las
       iglesias en las que el usuario puede crear actividades. Si viene
       vacío → la opción "Crear evento" queda deshabilitada. Si viene
       con ≥1 → habilita y, si hay varias, muestra un picker al tocar.
     - onSeleccion(id, iglesia?) — para "evento" incluye iglesia elegida.
   Se renderiza en un Portal al body para evitar conflictos con app-frame. */
(function () {
  const { useEffect, useState } = React;

  function AccionesMenu({ abierto, onClose, onSeleccion, iglesiasCrearEvento }) {
    const iglesiasEvento = Array.isArray(iglesiasCrearEvento) ? iglesiasCrearEvento : [];
    const puedeEvento = iglesiasEvento.length > 0;

    const OPCIONES = [
      { id: "evento",  emoji: "📅", tint: "#F3E8FF", titulo: "Crear evento",      desc: "Publica un evento especial",      disponible: puedeEvento },
      { id: "anuncio", emoji: "📢", tint: "#FEF3C7", titulo: "Publicar anuncio",  desc: "Comparte con tu comunidad",       disponible: false },
    ];

    // Vistas internas: "opciones" o "elegirIglesia" (picker de iglesia
    // cuando el usuario administra varias).
    const [vista, setVista] = useState("opciones");
    useEffect(function () {
      if (!abierto) setVista("opciones");
    }, [abierto]);
    useEffect(() => {
      if (!abierto) return;
      const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
      document.addEventListener("keydown", onKey);
      // bloquea scroll del body mientras está abierto
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => {
        document.removeEventListener("keydown", onKey);
        document.body.style.overflow = prev;
      };
    }, [abierto, onClose]);

    const handleTap = (op) => {
      if (!op.disponible) return;
      if (op.id === "evento") {
        if (iglesiasEvento.length === 1) {
          if (onSeleccion) onSeleccion("evento", iglesiasEvento[0]);
          if (onClose) onClose();
        } else {
          setVista("elegirIglesia");
        }
        return;
      }
      if (onSeleccion) onSeleccion(op.id);
      if (onClose) onClose();
    };

    const handleElegirIglesia = (ig) => {
      if (onSeleccion) onSeleccion("evento", ig);
      if (onClose) onClose();
    };

    // Detecta dark mode leyendo la clase del app-frame
    const dark = typeof document !== "undefined" &&
      document.querySelector(".app-frame")?.classList.contains("dark");

    const content = (
      <div aria-hidden={!abierto}>
        {/* Overlay */}
        <div
          onClick={onClose}
          style={{
            position: "fixed",
            inset: 0,
            background: "rgba(0,0,0,0.45)",
            zIndex: 60,
            opacity: abierto ? 1 : 0,
            pointerEvents: abierto ? "auto" : "none",
            transition: "opacity 150ms ease",
          }}
        />

        {/* Panel centrado con el mismo ancho que el app-frame */}
        <div
          role="dialog"
          aria-modal="true"
          aria-label="Menú de acciones"
          style={{
            position: "fixed",
            bottom: 0,
            left: "50%",
            width: "100%",
            maxWidth: 430,
            transform: abierto ? "translate(-50%, 0)" : "translate(-50%, 100%)",
            transition: "transform 240ms cubic-bezier(0.2, 0.9, 0.3, 1)",
            zIndex: 61,
            background: dark ? "#1A1A1A" : "#FFFFFF",
            color: dark ? "#F0F0F0" : "#3C3C3C",
            borderTopLeftRadius: 24,
            borderTopRightRadius: 24,
            boxShadow: "0 -8px 40px rgba(0,0,0,0.18)",
            paddingLeft: 20,
            paddingRight: 20,
            paddingTop: 12,
            paddingBottom: "calc(20px + env(safe-area-inset-bottom, 0px))",
          }}
        >
          {/* Handle */}
          <div
            style={{
              width: 40, height: 4, borderRadius: 999,
              background: dark ? "#3A3A3A" : "#E5E7EB",
              margin: "0 auto 16px",
            }}
          />

          {/* Header: título + cerrar */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              {vista === "elegirIglesia" && (
                <button
                  type="button"
                  onClick={() => setVista("opciones")}
                  aria-label="Atrás"
                  style={{
                    width: 28, height: 28, borderRadius: 999,
                    background: "transparent",
                    border: "none",
                    color: dark ? "#D0D0D0" : "#6B7280",
                    fontSize: 18, cursor: "pointer",
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}
                >
                  ←
                </button>
              )}
              <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800, color: dark ? "#F0F0F0" : "#3C3C3C" }}>
                {vista === "elegirIglesia" ? "Elige una iglesia" : "Crear"}
              </h3>
            </div>
            <button
              type="button"
              onClick={onClose}
              aria-label="Cerrar"
              style={{
                width: 32, height: 32, borderRadius: 999,
                background: dark ? "#2A2A2A" : "#F3F4F6",
                border: "none",
                display: "flex", alignItems: "center", justifyContent: "center",
                cursor: "pointer",
                color: dark ? "#D0D0D0" : "#6B7280",
                fontSize: 16,
              }}
            >
              ✕
            </button>
          </div>
          <p style={{
            margin: "0 0 14px", fontSize: 13, fontWeight: 500,
            color: dark ? "#9CA3AF" : "#6B7280",
          }}>
            {vista === "elegirIglesia"
              ? "¿Para cuál iglesia quiere crear el evento?"
              : "¿Qué quieres publicar?"}
          </p>

          {vista === "elegirIglesia" ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 2, maxHeight: "45vh", overflowY: "auto" }}>
              {iglesiasEvento.map((ig) => (
                <button
                  key={ig.id}
                  type="button"
                  onClick={() => handleElegirIglesia(ig)}
                  style={{
                    display: "flex", alignItems: "center", gap: 12,
                    width: "100%", textAlign: "left",
                    padding: "10px 10px",
                    borderRadius: 14,
                    border: "none",
                    background: "transparent",
                    cursor: "pointer",
                    fontFamily: "inherit",
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = dark ? "#262626" : "#F9FAFB"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
                >
                  {ig.imagen_url ? (
                    <img
                      src={ig.imagen_url}
                      alt=""
                      referrerPolicy="no-referrer"
                      style={{
                        width: 44, height: 44, borderRadius: 12,
                        objectFit: "cover", flexShrink: 0,
                        background: dark ? "#262626" : "#E0EAFF",
                      }}
                    />
                  ) : (
                    <div
                      aria-hidden
                      style={{
                        width: 44, height: 44, borderRadius: 12,
                        background: dark ? "#262626" : "#E0EAFF",
                        display: "flex", alignItems: "center", justifyContent: "center",
                        fontSize: 20, flexShrink: 0,
                      }}
                    >
                      🏠
                    </div>
                  )}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div
                      style={{
                        fontSize: 14, fontWeight: 800,
                        color: dark ? "#F0F0F0" : "#111827",
                        overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                      }}
                    >
                      {ig.nombre || "Sin nombre"}
                    </div>
                  </div>
                  <span
                    aria-hidden
                    style={{
                      fontSize: 14, color: dark ? "#9CA3AF" : "#6B7280",
                      flexShrink: 0, fontWeight: 900,
                    }}
                  >
                    →
                  </span>
                </button>
              ))}
            </div>
          ) : (
          /* Opciones */
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {OPCIONES.map((op) => {
              const deshab = !op.disponible;
              return (
                <button
                  key={op.id}
                  type="button"
                  disabled={deshab}
                  onClick={() => handleTap(op)}
                  aria-disabled={deshab}
                  style={{
                    display: "flex", alignItems: "center", gap: 14,
                    width: "100%", textAlign: "left",
                    padding: "12px 10px",
                    borderRadius: 14,
                    border: "none",
                    background: "transparent",
                    cursor: deshab ? "not-allowed" : "pointer",
                    opacity: deshab ? 0.5 : 1,
                    transition: "background 150ms ease",
                  }}
                  onMouseEnter={(e) => {
                    if (!deshab) e.currentTarget.style.background = dark ? "#262626" : "#F9FAFB";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.background = "transparent";
                  }}
                >
                  <div
                    style={{
                      width: 48, height: 48, borderRadius: 14,
                      background: dark ? "#262626" : op.tint,
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontSize: 22, flexShrink: 0,
                    }}
                    aria-hidden
                  >
                    {op.emoji}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 15, fontWeight: 700,
                      color: dark ? "#F0F0F0" : "#111827",
                      overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                    }}>
                      {op.titulo}
                    </div>
                    <div style={{
                      fontSize: 12, fontWeight: 500, marginTop: 2,
                      color: dark ? "#9CA3AF" : "#6B7280",
                      overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                    }}>
                      {op.desc}
                    </div>
                  </div>
                  {deshab && (
                    <span style={{
                      flexShrink: 0,
                      fontSize: 10, fontWeight: 800, textTransform: "uppercase", letterSpacing: 0.3,
                      background: dark ? "#333" : "#E5E7EB",
                      color: dark ? "#D0D0D0" : "#6B7280",
                      padding: "4px 8px", borderRadius: 999,
                    }}>
                      Pronto
                    </span>
                  )}
                </button>
              );
            })}
          </div>
          )}
        </div>
      </div>
    );

    // Portal al body — evita que app-frame (overflow:hidden) o transforms afecten la posición
    if (typeof document === "undefined") return null;
    return ReactDOM.createPortal(content, document.body);
  }

  window.AccionesMenu = AccionesMenu;
})();
