'use client'

import { useEffect } from 'react'
import { useRouter } from 'next/navigation'

/**
 * Invisible client component that periodically calls router.refresh()
 * to re-fetch server component data without a full page reload.
 * Pauses when the tab is hidden to avoid unnecessary requests.
 */
export function AutoRefresh({ intervalMs = 30_000 }: { intervalMs?: number }) {
  const router = useRouter()

  useEffect(() => {
    let timer: ReturnType<typeof setInterval>

    function start() {
      timer = setInterval(() => {
        router.refresh()
      }, intervalMs)
    }

    function handleVisibility() {
      clearInterval(timer)
      if (document.visibilityState === 'visible') {
        // Refresh immediately when tab becomes visible again
        router.refresh()
        start()
      }
    }

    start()
    document.addEventListener('visibilitychange', handleVisibility)

    return () => {
      clearInterval(timer)
      document.removeEventListener('visibilitychange', handleVisibility)
    }
  }, [router, intervalMs])

  return null
}
