// src/hooks/useInfiniteScroll.ts
import { onMounted, onBeforeUnmount, Ref } from 'vue';

interface UseInfiniteScrollOptions {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number;
}

export function useInfiniteScroll(
  target: Ref<HTMLElement | null | undefined>,
  callback: () => void,
  options: UseInfiniteScrollOptions = {},
) {
  let observer: IntersectionObserver | null = null;

  onMounted(() => {
    const { root, rootMargin = '0px', threshold = 0.1 } = options;

    if (!target.value) return;

    observer = new IntersectionObserver(
      (entries) => {
        const [entry] = entries;
        if (entry.isIntersecting) {
          callback();
        }
      },
      {
        root,
        rootMargin,
        threshold,
      },
    );

    observer.observe(target.value);
  });

  onBeforeUnmount(() => {
    if (observer) {
      observer.disconnect();
      observer = null;
    }
  });
}
