import { Navigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { Loader2 } from 'lucide-react'
import { api } from '@/lib/api'

function getStoredRole(): string | null {
  try { return localStorage.getItem('access_role') } catch { return null }
}

export function AdminGuard({ children }: { children: React.ReactNode }) {
  const { data: status, isLoading } = useQuery({
    queryKey: ['access-auth-status'],
    queryFn: () => api.accessAuthStatus(),
    enabled: true,
    staleTime: 5 * 60 * 1000,
  })

  if (isLoading) {
    return (
      <div className="h-screen w-full flex items-center justify-center bg-base text-foreground">
        <Loader2 className="h-6 w-6 animate-spin text-accent" />
      </div>
    )
  }

  // 未启用门控或本地角色为 admin,均放行
  const localRole = getStoredRole()
  if (!status?.enabled || localRole === 'admin' || status.role === 'admin') {
    return <>{children}</>
  }

  return <Navigate to="/" replace />
}
