import { useRef } from "react";

/**
 * Hook to lock the primary page's scrolling capabilities.
 *
 * Primarily designed to work in conjunction with isDialogVisible flags.
 * @param deps list of boolean variables to monitor. If any of these are true, scroll will be locked
 * @returns Is page scroll currently locked due to this hook.
 */
export const useScrollLock = (deps: boolean[]) => {
  const isScrollLocked = useRef(false);

  //If any is true, try locking scroll
  const shouldLock = deps.find((x) => x) ?? false;

  //Stop if no state change needed
  if (isScrollLocked.current == shouldLock) return;

  //Stop if page isn't loaded
  if (typeof document === "undefined") return;

  const { body, documentElement } = document;

  //Stop if page isn't rendered
  if (!body?.style) return;

  //Handle DOM elements to enable/disable scrolling
  documentElement.style.position = body.style.position = shouldLock
    ? "relative"
    : "";
  documentElement.style.overflow = body.style.overflow = shouldLock
    ? "hidden"
    : "";

  //Store new state
  isScrollLocked.current = shouldLock;
  return isScrollLocked.current;
};
