export function createVisibilityAwarePoller(options: {
  intervalMs: number
  task: () => void | Promise<void>
}): () => void {
  let cancelled = false
  let timeoutId: ReturnType<typeof setTimeout> | null = null

  const schedule = () => {
    if (cancelled) return
    if (timeoutId) clearTimeout(timeoutId)
    timeoutId = setTimeout(async () => {
      if (cancelled) return
      if (typeof document !== 'undefined' && document.visibilityState !== 'visible') {
        schedule()
        return
      }
      try {
        await options.task()
      } finally {
        schedule()
      }
    }, options.intervalMs)
  }

  const onVisibility = () => {
    if (!cancelled && typeof document !== 'undefined' && document.visibilityState === 'visible') {
      void options.task()
    }
  }

  schedule()
  if (typeof document !== 'undefined') {
    document.addEventListener('visibilitychange', onVisibility)
  }

  return () => {
    cancelled = true
    if (timeoutId) clearTimeout(timeoutId)
    if (typeof document !== 'undefined') {
      document.removeEventListener('visibilitychange', onVisibility)
    }
  }
}
