import { useEffect, useRef } from 'react'

/**
 * Call `fn` every `ms` milliseconds while `enabled` is true; clears the timer
 * when it flips false or the component unmounts. The latest `fn` is always
 * used without restarting the interval, so callers can pass a fresh closure
 * each render (e.g. `() => reload(true)`) without churning the timer.
 */
export function usePolling(fn: () => void, ms: number, enabled: boolean): void {
  const fnRef = useRef(fn)
  fnRef.current = fn

  useEffect(() => {
    if (!enabled) return
    const id = window.setInterval(() => fnRef.current(), ms)
    return () => window.clearInterval(id)
  }, [enabled, ms])
}
