import { onUnmounted } from 'vue'

// Polling with a visibility pause: tab hidden → stop; visible again →
// immediate tick, then continue if isActive(). Stops itself as soon as
// isActive() returns false after a tick.
export function usePolling(tick, isActive, interval = 3000) {
  let timer = null

  function stop() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  function start() {
    stop()
    timer = setInterval(async () => {
      await tick()
      if (!isActive()) stop()
    }, interval)
  }

  function running() {
    return !!timer
  }

  async function onVisibility() {
    if (document.hidden) {
      stop()
    } else {
      await tick()
      if (isActive()) start()
    }
  }

  document.addEventListener('visibilitychange', onVisibility)
  onUnmounted(() => {
    stop()
    document.removeEventListener('visibilitychange', onVisibility)
  })

  return { start, stop, running }
}
