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

/**
 * 用于保护需要登录才能访问的页面
 * 未登录时自动跳转到 /login，并记录原始跳转路径
 */
const PrivateRoute = ({ children }) => {
  const location = useLocation();
  const user = localStorage.getItem('user');
  if (!user) {
    // 记录跳转前的路径，登录后可重定向回来
    sessionStorage.setItem('redirectAfterLogin', location.pathname + location.search);
    return <Navigate to="/login" replace />;
  }
  return children;
};

export default PrivateRoute;
