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

export const useDetectSticky = <Target extends HTMLElement>(
  observerSettings = { threshold: 1 }
) => {
  const [isSticky, setIsSticky] = useState(false);
  const ref = useRef<Target>(null);

  useEffect(() => {
    const cachedRef = ref.current;
    const observer = new IntersectionObserver(([e]) => {
      setIsSticky(e.intersectionRatio < 1);
    }, observerSettings);

    cachedRef && observer.observe(cachedRef);

    return () => {
      cachedRef && observer.unobserve(cachedRef);
    };
  }, [observerSettings]);

  return { isSticky, ref, setIsSticky };
};
