import Cookies from 'js-cookie';
import { Navigate, Outlet, useLocation } from 'react-router-dom';
import type { ReactNode } from 'react';
import { authStorage } from '../utils/auth-storage';

interface ProtectedRouteProps {
  children?: ReactNode;
  loginPath?: string;
}

export function ProtectedRoute({ children, loginPath = '/login' }: ProtectedRouteProps) {
  const location = useLocation();
  const token = authStorage.getToken() ?? Cookies.get('auth-token');

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

  return children ? <>{children}</> : <Outlet />;
}
