"use client"

import { useState, useEffect } from "react"
import { WifiOff, Download, RefreshCw } from "lucide-react"
import { Button } from "@/components/ui/button"
import Link from "next/link"

export function OfflineIndicator() {
  const [isOffline, setIsOffline] = useState(false)
  const [showBanner, setShowBanner] = useState(false)
  const [wasOffline, setWasOffline] = useState(false)

  useEffect(() => {
    const updateStatus = () => {
      const offline = !navigator.onLine
      setIsOffline(offline)
      
      if (offline) {
        setShowBanner(true)
        setWasOffline(true)
      } else if (wasOffline) {
        // Coming back online - show sync message briefly
        setShowBanner(true)
        setTimeout(() => {
          setShowBanner(false)
          setWasOffline(false)
        }, 3000)
      }
    }

    updateStatus()
    window.addEventListener("online", updateStatus)
    window.addEventListener("offline", updateStatus)

    return () => {
      window.removeEventListener("online", updateStatus)
      window.removeEventListener("offline", updateStatus)
    }
  }, [wasOffline])

  if (!showBanner) return null

  if (isOffline) {
    return (
      <div className="fixed top-0 left-0 right-0 z-50 bg-orange-500 text-white px-4 py-2 shadow-lg">
        <div className="mx-auto max-w-md flex items-center justify-between gap-2">
          <div className="flex items-center gap-2">
            <WifiOff className="h-4 w-4" />
            <span className="text-sm font-medium">Mode hors ligne</span>
          </div>
          <Link href="/downloads">
            <Button size="sm" variant="secondary" className="h-7 gap-1 text-xs">
              <Download className="h-3 w-3" />
              Telechargements
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  // Just came back online
  return (
    <div className="fixed top-0 left-0 right-0 z-50 bg-green-500 text-white px-4 py-2 shadow-lg animate-in slide-in-from-top">
      <div className="mx-auto max-w-md flex items-center justify-center gap-2">
        <RefreshCw className="h-4 w-4 animate-spin" />
        <span className="text-sm font-medium">Connexion retablie - Synchronisation...</span>
      </div>
    </div>
  )
}
