import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";

const PUBLIC_PATHS = ['login', '404','home'];

export const ProtectedRoute = ({ children }) => {
  const { user } = useAuth();
  const location = useLocation();
  const currentPath = location.pathname.replace(/^\//, '');

  // 如果是公共路径，直接显示
  if (PUBLIC_PATHS.includes(currentPath) || currentPath === '*') {
    return children;
  }

  // 如果用户未登录，重定向到登录页面，并携带当前路径
  if (!user?.id) {
    return <Navigate 
      to={`/login?redirectTo=${encodeURIComponent(location.pathname + location.search)}`} 
      replace 
    />;
  }

  // 如果用户已登录，检查权限
  if (user?.id) {
    const hasPermission = user.menukeys?.some(key => {
      return currentPath === key || currentPath.startsWith(`${key}/`);
    });

    if (!hasPermission) {
      return <Navigate to="/dashboard" replace />;
    }

    return children;
  }

  return <Navigate to="/login" state={{ from: location }} replace />;
};
