// // ProtectedRoute.jsx
// import React from "react";
// import { Navigate } from "react-router-dom";

// const ProtectedRoute = ({ moduleName, children }) => {
//   const permissions = JSON.parse(localStorage.getItem("permissions") || "[]");
//   const module = permissions.find((p) => p.module === moduleName);

//   // ✅ Allow access if module is not permission-controlled
//   if (!module) {
//     return children;
//   }

//   // 🚫 Deny if module exists but no view access
//   if (!module.actions.view) {
//     return <Navigate to="/unauthorized" replace />;
//   }

//   return children;
// };

// export default ProtectedRoute;


import React from "react";
import { Navigate } from "react-router-dom";

interface ProtectedRouteProps {
  moduleName?: string; // 👈 make optional
  action?: string;
  children: React.ReactNode;
  isPublic?: boolean;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  moduleName,
  action = "view",
  children,
}) => {
  const isLoggedIn = localStorage.getItem("isLoggedIn");
  const permissions = JSON.parse(localStorage.getItem("permissions") || "[]");

  
 

  // 🔴 Not logged in → redirect to login
  if (!isLoggedIn) return <Navigate to="/" replace />;

  // Public routes or modules not managed by permissions should simply render
  if (!moduleName) {
    return children;
  }

  // 🔐 Protected route permission check
  const module = permissions.find((p: any) => p.module === moduleName);

  if (!module) {
    // Module isn't permission-controlled; allow access by default
    return children;
  }

  const actions = module.actions || {};
  if (!actions[action]) {
    return <Navigate to="/pages/error404" replace />;
  }

  return children;
};

export default ProtectedRoute;
