"use client"

import { useEffect, useState } from "react"
import { useRouter, usePathname } from "next/navigation"
import { isAuthenticated } from "@/lib/auth"

export default function AuthGuard({ children }: { children: React.ReactNode }) {
  const router = useRouter()
  const pathname = usePathname()
  const [isChecking, setIsChecking] = useState(true)

  useEffect(() => {
    // Skip auth check for login page
    if (pathname === "/login") {
      setIsChecking(false)
      return
    }

    // Check if user is authenticated
    if (!isAuthenticated()) {
      router.push("/login")
    } else {
      setIsChecking(false)
    }
  }, [pathname, router])

  // Show loading while checking auth
  if (isChecking && pathname !== "/login") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-900">
        <div className="text-white">Loading...</div>
      </div>
    )
  }

  return <>{children}</>
}
