'use client'

import { useState, useEffect, useCallback } from 'react'
import { RefreshCw } from 'lucide-react'

const CHECK_INTERVAL = 60_000 // check every 60s

export function UpdateBanner() {
  const [updateAvailable, setUpdateAvailable] = useState(false)
  const [initialVersion, setInitialVersion] = useState<string | null>(null)

  const checkVersion = useCallback(async () => {
    try {
      const res = await fetch('/api/version', { cache: 'no-store' })
      const { version } = await res.json()
      if (!version) return

      if (initialVersion === null) {
        setInitialVersion(version)
      } else if (version !== initialVersion) {
        setUpdateAvailable(true)
      }
    } catch {
      // network error, skip
    }
  }, [initialVersion])

  useEffect(() => {
    checkVersion()
    const id = setInterval(checkVersion, CHECK_INTERVAL)
    return () => clearInterval(id)
  }, [checkVersion])

  // Also check on visibility change (user returns to tab)
  useEffect(() => {
    const onVisible = () => {
      if (document.visibilityState === 'visible') checkVersion()
    }
    document.addEventListener('visibilitychange', onVisible)
    return () => document.removeEventListener('visibilitychange', onVisible)
  }, [checkVersion])

  if (!updateAvailable) return null

  return (
    <button
      onClick={() => window.location.reload()}
      className="fixed top-0 left-0 right-0 z-[100] bg-purple-600 text-white text-sm font-medium py-2.5 px-4 flex items-center justify-center gap-2 shadow-lg hover:bg-purple-700 transition-colors cursor-pointer"
    >
      <RefreshCw className="h-4 w-4" />
      A new version is available — tap to update
    </button>
  )
}
