import { ReactNode } from 'react'
import { Navigate } from 'react-router-dom'

interface RoleRouteProps {
  roles: string[]
  children: ReactNode
  fallback?: string
}

export function RoleRoute({ roles, children, fallback }: RoleRouteProps) {
  const userStr = localStorage.getItem('user')
  const user = userStr ? JSON.parse(userStr) : null
  const role = user?.role

  if (!role || !roles.includes(role)) {
    const redirect = fallback || (role === 'store' ? '/store' : role === 'regional' ? '/regional' : role === 'platform_admin' ? '/tenant-management' : '/')
    return <Navigate to={redirect} replace />
  }

  return <>{children}</>
}
