import { onUnmounted, watch } from "vue";

let lockCount = 0;
let savedOverflow = "";
let savedPaddingRight = "";

function lockBody() {
  if (typeof window === "undefined") {
    return;
  }

  if (lockCount === 0) {
    savedOverflow = document.body.style.overflow;
    savedPaddingRight = document.body.style.paddingRight;

    const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
    document.body.style.overflow = "hidden";
    if (scrollbarWidth > 0) {
      document.body.style.paddingRight = `${scrollbarWidth}px`;
    }
  }

  lockCount += 1;
}

function unlockBody() {
  if (typeof window === "undefined" || lockCount <= 0) {
    return;
  }

  lockCount -= 1;
  if (lockCount === 0) {
    document.body.style.overflow = savedOverflow;
    document.body.style.paddingRight = savedPaddingRight;
  }
}

export function useBodyScrollLock(source) {
  let active = false;

  const stop = watch(
    source,
    (locked) => {
      if (locked && !active) {
        lockBody();
        active = true;
      }
      if (!locked && active) {
        unlockBody();
        active = false;
      }
    },
    { immediate: true }
  );

  onUnmounted(() => {
    stop();
    if (active) {
      unlockBody();
      active = false;
    }
  });
}
