import React, { useEffect, useRef } from "react";

interface InfiniteScrollProps {
  children: React.ReactNode;
  hasMore: boolean;
  isLoading: boolean;
  onLoadMore: () => void;
  threshold?: number;
  className?: string;
}

const InfiniteScroll: React.FC<InfiniteScrollProps> = ({
  children,
  hasMore,
  isLoading,
  onLoadMore,
  threshold = 500,
  className = "",
}) => {
  const observerTargetRef = useRef<HTMLDivElement | null>(null);
  const onLoadMoreRef = useRef(onLoadMore);

  // Keep references to prevent stale closures in observer callback
  useEffect(() => {
    onLoadMoreRef.current = onLoadMore;
  }, [onLoadMore]);

  useEffect(() => {
    // If there is no more data or we are already loading, do not observe
    if (!hasMore || isLoading) {
      return;
    }

    const observer = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        if (entry.isIntersecting) {
          onLoadMoreRef.current();
        }
      },
      {
        // rootMargin bottom expands the viewport detection box downwards
        rootMargin: `0px 0px ${threshold}px 0px`,
      }
    );

    const currentTarget = observerTargetRef.current;
    if (currentTarget) {
      observer.observe(currentTarget);
    }

    return () => {
      if (currentTarget) {
        observer.unobserve(currentTarget);
      }
    };
  }, [hasMore, isLoading, threshold]);

  return (
    <div className={className}>
      {children}
      <div
        ref={observerTargetRef}
        style={{ height: "1px", width: "100%", clear: "both" }}
      />
    </div>
  );
};

export default InfiniteScroll;

