import { CircularProgress, Box } from '@mui/material';
import React, { useEffect, useRef, useCallback } from 'react';

const TanstackInfiniteScrollWrapper = ({ children, hasNextPage, fetchNextPage, isFetchingNextPage, scrollContainerRef }) => {
  const loaderRef = useRef(null);

  const handleObserver = useCallback(
    (entries) => {
      const target = entries[0];
      if (target.isIntersecting && hasNextPage && !isFetchingNextPage) {
        fetchNextPage();
      }
    },
    [hasNextPage, isFetchingNextPage, fetchNextPage]
  );

  useEffect(() => {
    const options = {
      root: scrollContainerRef?.current || null, // container or window
      rootMargin: '200px', // fetch a bit earlier
      threshold: 0
    };

    const observer = new IntersectionObserver(handleObserver, options);
    if (loaderRef.current) observer.observe(loaderRef.current);

    return () => {
      if (loaderRef.current) observer.unobserve(loaderRef.current);
    };
  }, [handleObserver, scrollContainerRef]);

  return (
    <Box>
      {children}
      {/* 👇 sentinel */}
      <div ref={loaderRef} />
      {/* {isFetchingNextPage && ( //its common use it in pade it seld as needed
        <Box display="flex" justifyContent="center" py={2}>
          <CircularProgress />
        </Box>
      )} */}
    </Box>
  );
};

export default TanstackInfiniteScrollWrapper;
