import { Navigate, useLocation } from 'react-router-dom'

const ADMIN_PATHS = ['/api-keys', '/config', '/users']

export function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const token = sessionStorage.getItem('gm_token')
  const location = useLocation()
  const user = (() => { try { return JSON.parse(sessionStorage.getItem('gm_user') ?? 'null') } catch { return null } })()

  if (!token) return <Navigate to="/login" state={{ from: location }} replace />

  if (ADMIN_PATHS.some(p => location.pathname.startsWith(p)) && user?.role !== 'admin') {
    return (
      <div style={{ padding: 48, textAlign: 'center' }}>
        <div style={{ fontSize: 48, marginBottom: 16 }}>🔒</div>
        <div style={{ fontSize: 16, fontWeight: 600, color: '#1e293b', marginBottom: 8 }}>접근 권한이 없습니다</div>
        <div style={{ color: '#64748b', fontSize: 13 }}>이 페이지는 관리자(admin) 권한이 필요합니다.</div>
      </div>
    )
  }

  return <>{children}</>
}
