"use client";

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

type Options = {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number;
};

const defaultOptions: Options = {
  root: null,
  rootMargin: "0px",
  threshold: 0,
};

const useObserver = <T extends HTMLElement = HTMLElement>(
  options: Options = defaultOptions,
) => {
  const ref = useRef<T | null>(null);
  const [isVisible, setIsVisible] = useState(false);

  const { root, rootMargin, threshold } = { ...defaultOptions, ...options };

  useEffect(() => {
    if (isVisible) return;

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

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

    observer.observe(element);

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

  return [ref, isVisible] as const;
};

export default useObserver;
