/* HorarioSheet → window. Bottom sheet que muestra el horario semanal
   de una iglesia. Se abre desde IglesiaCard al tocar el chip "Horario"
   o la zona del próximo culto. El tap sobre la card completa sigue
   abriendo DetalleIglesia (datos completos).

   Props:
     abierto: boolean.
     iglesia: objeto con { nombre, imagen_url, horario, proximo_culto }.
     onClose: () => void.
     onVerIglesia?: () => void.  Atajo opcional para abrir la ficha
       completa desde el sheet (si no se pasa, no se muestra el botón).

   Portal al body, mismo estilo que AccionesMenu. */
(function () {
  const { useEffect } = React;

  function HorarioSheet({ abierto, iglesia, onClose, onVerIglesia }) {
    useEffect(() => {
      if (!abierto) return;
      const onKey = (e) => { if (e.key === "Escape") onClose && onClose(); };
      document.addEventListener("keydown", onKey);
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => {
        document.removeEventListener("keydown", onKey);
        document.body.style.overflow = prev;
      };
    }, [abierto, onClose]);

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

    const ig = iglesia || {};
    const HorarioSemanal = window.HorarioSemanal;

    const content = (
      <div aria-hidden={!abierto}>
        <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",
          }}
        />

        <div
          role="dialog"
          aria-modal="true"
          aria-label={"Horario de " + (ig.nombre || "la iglesia")}
          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)",
            display: "flex",
            flexDirection: "column",
            maxHeight: "88vh",
          }}
        >
          <div
            style={{
              width: 40, height: 4, borderRadius: 999,
              background: dark ? "#3A3A3A" : "#E5E7EB",
              margin: "12px auto 12px",
              flexShrink: 0,
            }}
          />

          <div style={{
            display: "flex", alignItems: "center", gap: 12,
            padding: "0 20px 12px",
            flexShrink: 0,
          }}>
            {ig.imagen_url ? (
              <img
                src={ig.imagen_url}
                alt=""
                referrerPolicy="no-referrer"
                style={{
                  width: 40, height: 40, borderRadius: 999,
                  objectFit: "cover", flexShrink: 0,
                  background: dark ? "#262626" : "#E0EAFF",
                }}
              />
            ) : (
              <div aria-hidden style={{
                width: 40, height: 40, borderRadius: 999,
                background: dark ? "#262626" : "#E0EAFF",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 18, flexShrink: 0,
              }}>🏠</div>
            )}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontSize: 11, fontWeight: 900,
                letterSpacing: "0.2em", textTransform: "uppercase",
                color: dark ? "#9CA3AF" : "#6B7280",
              }}>
                Horario
              </div>
              <div style={{
                fontSize: 16, fontWeight: 900,
                color: dark ? "#F0F0F0" : "#111827",
                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                marginTop: 2,
              }}>
                {ig.nombre || "Iglesia"}
              </div>
            </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,
                flexShrink: 0,
              }}
            >
              ✕
            </button>
          </div>

          <div style={{
            flex: 1,
            overflowY: "auto",
            padding: "4px 20px 8px",
          }}>
            {HorarioSemanal ? (
              <HorarioSemanal
                horario={ig.horario || []}
                proximo_culto={ig.proximo_culto}
              />
            ) : (
              <div style={{
                padding: 24, textAlign: "center",
                color: dark ? "#9CA3AF" : "#6B7280",
                fontWeight: 600, fontSize: 14,
              }}>
                Sin horarios disponibles.
              </div>
            )}
          </div>

          {typeof onVerIglesia === "function" && (
            <div style={{
              padding: "12px 20px calc(16px + env(safe-area-inset-bottom, 0px))",
              borderTop: "1px solid " + (dark ? "#2A2A2A" : "#EEE"),
              flexShrink: 0,
            }}>
              <button
                type="button"
                onClick={() => { if (onClose) onClose(); onVerIglesia(); }}
                style={{
                  width: "100%",
                  padding: "12px 16px",
                  borderRadius: 999,
                  border: "none",
                  background: "#2563EB",
                  color: "#FFFFFF",
                  fontWeight: 900,
                  fontSize: 14,
                  letterSpacing: 0.2,
                  cursor: "pointer",
                  fontFamily: "inherit",
                }}
              >
                Ver iglesia completa
              </button>
            </div>
          )}
        </div>
      </div>
    );

    if (typeof document === "undefined") return null;
    return ReactDOM.createPortal(content, document.body);
  }

  window.HorarioSheet = HorarioSheet;
})();
