'use client'

import { useEffect, useRef } from 'react'
import { toast } from 'sonner'

const CLIENT_BUILD_ID = process.env.NEXT_PUBLIC_BUILD_ID

export function VersionGuard() {
  const notified = useRef(false)

  useEffect(() => {
    async function checkVersion() {
      if (notified.current) return
      try {
        const res = await fetch('/api/version', { cache: 'no-store' })
        if (!res.ok) return
        const { buildId } = await res.json()
        if (buildId && CLIENT_BUILD_ID && buildId !== CLIENT_BUILD_ID) {
          notified.current = true
          toast('A new version is available', {
            description: 'Refresh to get the latest updates.',
            duration: Infinity,
            action: {
              label: 'Refresh',
              onClick: () => window.location.reload(),
            },
          })
        }
      } catch {
        // Network error — ignore
      }
    }

    // Check on tab focus (covers users returning to stale tabs)
    window.addEventListener('focus', checkVersion)

    // Also check every 5 minutes for long-lived tabs
    const interval = setInterval(checkVersion, 5 * 60 * 1000)

    return () => {
      window.removeEventListener('focus', checkVersion)
      clearInterval(interval)
    }
  }, [])

  return null
}
