import { onMounted, onUnmounted } from 'vue'

/**
 * Runs `refreshFn` on a recurring interval while the page is visible.
 * Safe to use in any component — timer is cleared on unmount.
 *
 * @param refreshFn   Called each tick. Should be silent (no loading state changes).
 * @param intervalMs  Polling interval in milliseconds.
 * @param canRun      Optional guard — refresh is skipped when this returns false.
 */
export function useBackgroundRefresh(
  refreshFn: () => void,
  intervalMs: number,
  canRun?: () => boolean,
): void {
  let timer: ReturnType<typeof setInterval> | null = null

  onMounted(() => {
    timer = setInterval(() => {
      if (document.hidden) return
      if (canRun && !canRun()) return
      refreshFn()
    }, intervalMs)
  })

  onUnmounted(() => {
    if (timer !== null) clearInterval(timer)
  })
}
