import { useState, useEffect } from 'react'
import { WifiOff, RefreshCw } from '../../lib/icons'
import { motion, AnimatePresence } from 'framer-motion'

export default function OfflineBanner() {
  const [offline, setOffline] = useState(!navigator.onLine)

  useEffect(() => {
    const goOffline = () => setOffline(true)
    const goOnline = () => setOffline(false)
    window.addEventListener('offline', goOffline)
    window.addEventListener('online', goOnline)
    return () => {
      window.removeEventListener('offline', goOffline)
      window.removeEventListener('online', goOnline)
    }
  }, [])

  return (
    <AnimatePresence>
      {offline && (
        <motion.div
          initial={{ height: 0, opacity: 0 }}
          animate={{ height: 'auto', opacity: 1 }}
          exit={{ height: 0, opacity: 0 }}
          transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
          className="overflow-hidden border-b border-error/15 bg-error/5"
        >
          <div className="px-7 py-2.5 flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <span className="relative flex h-2 w-2">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-error/60" />
                <span className="relative inline-flex h-2 w-2 rounded-full bg-error" />
              </span>
              <WifiOff size={14} className="text-error/90" />
              <span className="text-[13px] text-error/95 font-medium">Cannot reach server</span>
              <span className="text-[12px] text-error/60">- check your connection</span>
            </div>
            <button
              onClick={() => window.location.reload()}
              className="group flex items-center gap-1.5 text-[12px] text-error/80 hover:text-error transition-colors px-2 py-1 rounded-md hover:bg-error/10"
            >
              <RefreshCw size={12} className="transition-transform duration-500 group-hover:rotate-180" />
              Retry
            </button>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
