import { useState, useEffect, useRef, RefObject } from 'react';

interface UseIntersectionObserverOptions {
  threshold?: number | number[];
  root?: Element | null;
  rootMargin?: string;
}

/**
 * Hook to detect when an element is visible in the viewport using IntersectionObserver
 * @param options - IntersectionObserver options (threshold, root, rootMargin)
 * @returns Object containing ref to attach to element and isIntersecting state
 */
export const useIntersectionObserver = <T extends HTMLElement = HTMLDivElement>(
  options: UseIntersectionObserverOptions = {}
): { ref: RefObject<T>; isIntersecting: boolean } => {
  const { threshold = 0.5, root = null, rootMargin = '0px' } = options;
  const [isIntersecting, setIsIntersecting] = useState<boolean>(false);
  const ref = useRef<T>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        setIsIntersecting(entry.isIntersecting);
      },
      {
        threshold,
        root,
        rootMargin,
      }
    );

    const element = ref.current;
    if (element) {
      observer.observe(element);
    }

    return () => {
      if (element) {
        observer.unobserve(element);
      }
      observer.disconnect();
    };
  }, [threshold, root, rootMargin]);

  return { ref, isIntersecting };
};
