import { onMounted, watch, onUnmounted } from 'vue';
import { getScrollParent } from '../_util/utils';

function useScroll(targetRef, onScroll) {
  // scroll related
  let scrollableNodes = [];
  const ensureScrollListener = () => {
    let cursor = targetRef.value;
    while (true) {
      cursor = getScrollParent(cursor);
      if (cursor === null) {
        break;
      }
      scrollableNodes.push(cursor);
    }
    for (const el of scrollableNodes) {
      el.addEventListener('scroll', onScroll, true);
    }
  };
  const removeScrollListeners = () => {
    for (const el of scrollableNodes) {
      el.removeEventListener('scroll', onScroll, true);
    }
    scrollableNodes = [];
  };
  onMounted(() => {
    ensureScrollListener();
  });

  // 监听 targetRef 的变化
  watch(() => targetRef.value, () => {
    removeScrollListeners();
    ensureScrollListener();
  });
  onUnmounted(() => {
    removeScrollListeners();
  });
}

export { useScroll as default };
