"use client";

import { useEffect, useRef, useState } from "react";

interface UseIntersectionObserverOptions {
  threshold?: number;
  root?: Element | null;
  rootMargin?: string;
  triggerOnce?: boolean;
}

/**
 * Custom hook that wraps IntersectionObserver for detecting when elements enter the viewport.
 * Useful for triggering animations when sections scroll into view.
 *
 * @param options - Configuration options for the IntersectionObserver
 * @returns A tuple containing [ref to attach to element, boolean indicating visibility]
 */
export function useIntersectionObserver<T extends HTMLElement = HTMLElement>({
  threshold = 0.1,
  root = null,
  rootMargin = "0px",
  triggerOnce = true,
}: UseIntersectionObserverOptions = {}) {
  const [isVisible, setIsVisible] = useState(false);
  const ref = useRef<T>(null);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          if (triggerOnce) {
            observer.disconnect();
          }
        } else if (!triggerOnce) {
          setIsVisible(false);
        }
      },
      { threshold, root, rootMargin }
    );

    observer.observe(element);

    return () => observer.disconnect();
  }, [threshold, root, rootMargin, triggerOnce]);

  return [ref, isVisible] as const;
}

/**
 * Simplified version that accepts an element ID instead of a ref.
 * Useful for sections that already have IDs.
 */
export function useSectionVisibility(
  sectionId: string,
  options: Omit<UseIntersectionObserverOptions, "triggerOnce"> = {}
) {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const section = document.getElementById(sectionId);
    if (!section) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { threshold: options.threshold ?? 0.1, root: options.root, rootMargin: options.rootMargin }
    );

    observer.observe(section);

    return () => observer.disconnect();
  }, [sectionId, options.threshold, options.root, options.rootMargin]);

  return isVisible;
}


