import { useEffect, useMemo, useRef } from "react";
import createRegistry from "./create-registry";

export default function useRegistry() {
  const registry = useMemo(createRegistry, []);
  const cleanupScheduledRef = useRef(false);

  useEffect(() => {
    // Cancel any scheduled cleanup when component mounts
    // This handles React StrictMode double-mounting
    cleanupScheduledRef.current = false;

    return function unmount() {
      // Mark cleanup as scheduled
      cleanupScheduledRef.current = true;

      // clean up the registry to avoid any leaks
      // doing it after an animation frame so that other things unmounting
      // can continue to interact with the registry
      requestAnimationFrame(() => {
        // Only clean if still scheduled (not cancelled by remount)
        if (cleanupScheduledRef.current) {
          registry.clean();
        }
      });
    };
  }, [registry]);
  return registry;
}
