import { useEffect, useRef } from "react";
import { useInView } from "react-intersection-observer";

export const useTriggerScroll = ({
  isLoading,
  isError,
  fetchNextPage,
  hasNextPage = true,
  threshold = 0,
  rootMargin = "100px",
}) => {
  const attemptRef = useRef(0); // Track the number of failed attempts
  const MAX_ATTEMPTS = 100;

  // Using useInView from react-intersection-observer
  const { ref: lastElementRef, inView } = useInView({
    threshold,
    rootMargin,
  });

  useEffect(() => {
    if (inView && !isLoading && hasNextPage) {
      // Stop fetching if max attempts is reached
      if (attemptRef.current >= MAX_ATTEMPTS) {
        return;
      }
      // Attempt to fetch the next page
      fetchNextPage();
      if (isError) {
        // Increment the failed attempts on error
        attemptRef.current += 1;
      } else {
        // Reset the attempts on successful fetch
        attemptRef.current = 0;
      }
    }
  }, [inView, isLoading, fetchNextPage, hasNextPage, isError]);

  return {
    lastElementRef,
  };
};
