import { useEffect, useRef } from "react";

interface Options {
  enabled?: boolean;
  rootMargin?: string;
  threshold?: number;
}

/**
 * Calls `onIntersect` once whenever the returned ref scrolls into view.
 * Drives infinite scrolling — attach the ref to a sentinel `<div>` at the
 * bottom of a list.
 */
export function useIntersectionLoader<T extends HTMLElement = HTMLDivElement>(
  onIntersect: () => void,
  { enabled = true, rootMargin = "200px", threshold = 0 }: Options = {},
) {
  const sentinelRef = useRef<T | null>(null);

  useEffect(() => {
    if (!enabled) return;
    const node = sentinelRef.current;
    if (!node) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) {
          onIntersect();
        }
      },
      { rootMargin, threshold },
    );

    observer.observe(node);
    return () => observer.disconnect();
  }, [enabled, rootMargin, threshold, onIntersect]);

  return sentinelRef;
}
