import type { RefObject } from "react";
import { useEffect } from "react";

interface UseAutoUpdateArgs {
  referenceRef: RefObject<HTMLElement | null>;
  floatingRef: RefObject<HTMLDivElement | null>;
  onUpdate: () => void;
  enabled: boolean;
}

export const useAutoUpdate = ({
  referenceRef,
  floatingRef,
  onUpdate,
  enabled,
}: UseAutoUpdateArgs): void => {
  useEffect(() => {
    if (!enabled) return;

    const reference = referenceRef.current;
    const floating = floatingRef.current;

    const scrollOpts: AddEventListenerOptions = {
      capture: true,
      passive: true,
    };
    window.addEventListener("scroll", onUpdate, scrollOpts);
    window.addEventListener("resize", onUpdate, { passive: true });

    const observer =
      typeof ResizeObserver === "function"
        ? new ResizeObserver(onUpdate)
        : null;
    if (observer && reference) observer.observe(reference);
    if (observer && floating) observer.observe(floating);

    return () => {
      window.removeEventListener("scroll", onUpdate, scrollOpts);
      window.removeEventListener("resize", onUpdate);
      observer?.disconnect();
    };
  }, [enabled, onUpdate, referenceRef, floatingRef]);
};
