import { RefObject, useState } from 'react';
import { useEventListener } from 'usehooks-ts';

export function useIsScrollTop<T extends HTMLElement>(
  ref: RefObject<T>,
): boolean {
  const [isTop, setIsTop] = useState(true);

  const onScroll = (event: Event) => {
    if (event.target !== ref.current) {
      return;
    }

    setIsTop(ref.current?.scrollTop === 0);
  };

  useEventListener('scroll', onScroll, ref);

  return isTop;
}
