import React, { useEffect, useRef } from "react";

export interface ScrollDetectorProps {
  container: HTMLElement | null;
  onScroll: (isScrolled: boolean) => void;
}

/**
 * A 0px div at the top that detects when it's out of view.
 *
 * Used to determine whether the scroll is at the start or not.
 */
export const ScrollDetector = ({
  onScroll,
  container,
}: ScrollDetectorProps) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!ref.current || !container) {
      return;
    }

    const observer = new IntersectionObserver(
      ([entry]) => {
        onScroll(!entry.isIntersecting);
      },
      { root: container }
    );

    observer.observe(ref.current);

    return () => {
      observer.disconnect();
    };
  }, [container, onScroll, ref]);

  return <div ref={ref} />;
};
