"use client"

import type React from "react"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { getUser, isAuthenticated } from "@/lib/auth"
import { Loader2 } from "lucide-react"

interface AuthGuardProps {
  children: React.ReactNode
  allowedRoles?: ("admin" | "observer")[]
}

export function AuthGuard({ children, allowedRoles }: AuthGuardProps) {
  const router = useRouter()
  const [isAuthorized, setIsAuthorized] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const checkAuth = () => {
      if (!isAuthenticated()) {
        router.push("/login")
        return
      }

      const user = getUser()
      if (!user) {
        router.push("/login")
        return
      }

      // Check role-based access
      if (allowedRoles && !allowedRoles.includes(user.role)) {
        // Redirect to appropriate page based on role
        if (user.role === "admin") {
          router.push("/dashboard")
        } else {
          router.push("/attendance")
        }
        return
      }

      setIsAuthorized(true)
      setIsLoading(false)
    }

    checkAuth()
  }, [router, allowedRoles])

  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center">
      <div className="flex items-center gap-2">
        <Loader2 className="h-5 w-5 animate-spin text-primary" />
        <span className="text-sm font-medium">Chargement...</span>
      </div>
    </div>
    )
  }

  if (!isAuthorized) {
    return null
  }

  return <>{children}</>
}
