"use client";

import { useEffect, useRef, type DependencyList } from "react";

/**
 * 在依赖变化时执行异步副作用；factory 始终用最新闭包，但不必把 `t` 等不稳定引用放进 deps。
 */
export function useAsyncEffect(
  factory: () => void | (() => void) | Promise<void>,
  deps: DependencyList,
): void {
  const factoryRef = useRef(factory);
  factoryRef.current = factory;

  useEffect(() => {
    let cleanup: void | (() => void);
    queueMicrotask(() => {
      void Promise.resolve(factoryRef.current()).then((result) => {
        cleanup = result;
      });
    });

    return () => {
      cleanup?.();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);
}
