'use client'

import { useEffect } from 'react'

export function ServiceWorkerRegister() {
  useEffect(() => {
    if (!('serviceWorker' in navigator)) return

    navigator.serviceWorker
      .register('/sw.js')
      .then((reg) => {
        // Check for updates periodically (every 60s, matching version poll)
        setInterval(() => reg.update().catch(() => {}), 60_000)

        // Also check on visibility change
        document.addEventListener('visibilitychange', () => {
          if (document.visibilityState === 'visible') {
            reg.update().catch(() => {})
          }
        })
      })
      .catch((err) => {
        console.warn('SW registration failed:', err)
      })
  }, [])

  return null
}
