import { Navigate, Outlet } from "react-router-dom";

export default function ProtectedRoute({ children, allowedRoles = [] }) {
  const token = localStorage.getItem("token");
  const role = localStorage.getItem("role");

  const redirectByRole = () => {
    if (role === "admin") return "/admin";
    if (role === "masyarakat") return "/masyarakat";
    if (role === "sppg") return "/sppg";
    if (role === "validator") return "/validator";
    if (role === "pemerintah") return "/pemerintah";

    return "/login";
  };

  // Kalau belum login, arahkan ke halaman login
  if (!token || !role) {
    return <Navigate to="/login" replace />;
  }

  // Kalau role tidak sesuai, arahkan ke halaman role masing-masing
  if (allowedRoles.length > 0 && !allowedRoles.includes(role)) {
    return <Navigate to={redirectByRole()} replace />;
  }

  // Jika dipakai membungkus component
  if (children) {
    return children;
  }

  // Jika dipakai sebagai parent route
  return <Outlet />;
}