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

type RevealOptions = {
  rootMargin?: string;
  threshold?: number;
};

/**
 * Lightweight IntersectionObserver hook. Sets `inView` to true the first time
 * the element enters the viewport, then stops observing (fires once). Falls
 * back to immediately visible when IntersectionObserver is unavailable (SSR /
 * very old browsers) so content is never hidden.
 */
export function useRevealOnScroll<T extends HTMLElement = HTMLDivElement>(
  options?: RevealOptions,
) {
  const ref = useRef<T>(null);
  const [inView, setInView] = useState(false);

  const rootMargin = options?.rootMargin ?? "0px 0px -10% 0px";
  const threshold = options?.threshold ?? 0.1;

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

    if (typeof IntersectionObserver === "undefined") {
      setInView(true);
      return;
    }

    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            setInView(true);
            observer.disconnect();
            break;
          }
        }
      },
      { rootMargin, threshold },
    );

    observer.observe(el);
    return () => observer.disconnect();
  }, [rootMargin, threshold]);

  return { ref, inView };
}
