import { useEffect, useRef } from 'react';

export function usePolling(
  callback: () => Promise<boolean | void>,
  intervalMs: number,
  enabled: boolean
) {
  const savedCallback = useRef(callback);
  savedCallback.current = callback;

  useEffect(() => {
    if (!enabled) return;

    let active = true;
    const poll = async () => {
      if (!active) return;
      const shouldStop = await savedCallback.current();
      if (shouldStop || !active) return;
      setTimeout(poll, intervalMs);
    };
    poll();

    return () => { active = false; };
  }, [intervalMs, enabled]);
}
