import React, { Fragment, useEffect, useMemo, useState } from "react"; import { BrowserRouter, Link, Navigate, Route, Routes, useLocation, useNavigate } from "react-router-dom"; import { FaArrowRightFromBracket, FaBars, FaHouse } from "react-icons/fa6"; import { getStoredAuthRole, getStoredAuthUser, hasAuthToken, apiUrl, clearAuth, persistAuth, buildProfileFromUser } from "../utils/auth"; import { SIDEBAR_LOGO_URL, iconMap, THEME_KEY } from "../utils/constants"; function AuthGate({ roles, children }) { const [status, setStatus] = useState("checking"); const localRole = getStoredAuthRole(); useEffect(() => { let mounted = true; async function verify() { const localRole = getStoredAuthRole(); const localTokenPresent = hasAuthToken(); const localAuthAllowed = localTokenPresent && localRole && roles.some(r => String(r).toLowerCase() === String(localRole).toLowerCase()); if (!localTokenPresent || !localRole) { if (mounted) setStatus("denied"); return; } try { const response = await fetch(apiUrl("/api/auth/whoami"), { method: "GET", credentials: "include", headers: { Accept: "application/json" }, }); const payload = await response.json().catch(() => ({})); if (response.ok && payload.authenticated) { const role = payload.role; const isAllowed = roles.some(r => String(r).toLowerCase() === String(role || "").toLowerCase()); if (!isAllowed) { console.warn(`AuthGate: Role "${role}" not in allowed list:`, roles); if (mounted) setStatus("denied"); return; } persistAuth({ token: "session", role, user: payload.user || getStoredAuthUser() || {} }); if (mounted) setStatus("allowed"); return; } console.warn("AuthGate: Authenticated check failed", payload); clearAuth(); if (mounted) setStatus("denied"); } catch (err) { if (localAuthAllowed) { console.warn("AuthGate: whoami request failed, using cached auth state", err); if (mounted) setStatus("allowed"); return; } console.error("AuthGate Exception:", err); clearAuth(); if (mounted) setStatus("denied"); } } verify(); return () => { mounted = false; }; }, [roles]); if (status === "checking") { const loadingVariant = String(localRole || "").toLowerCase() === "super_admin" ? "admin" : "faculty"; return ( ); } if (status === "denied") { return ; } return children; } function RequireFacultyAuth({ children }) { return {children}; } function RequireAdminAuth({ children }) { return {children}; } function PageShell({ variant, nav, title, subtitle, profile, actions, sidebarAction, children }) { const [sidebarOpen, setSidebarOpen] = useState(false); const [profileMenuOpen, setProfileMenuOpen] = useState(false); const [theme, setTheme] = useState(() => { if (typeof document !== "undefined") { if (document.body.classList.contains("dark")) return "dark"; if (document.body.classList.contains("light")) return "light"; } return localStorage.getItem(THEME_KEY) || "light"; }); const location = useLocation(); const storedUser = getStoredAuthUser(); const storedRole = getStoredAuthRole(); const authDrivenProfile = variant === "faculty" || variant === "admin" ? buildProfileFromUser(storedUser, variant === "admin" ? "admin" : "faculty") : profile; const effectiveProfile = { ...profile, ...authDrivenProfile, avatar: authDrivenProfile?.avatar || profile?.avatar || "U", name: authDrivenProfile?.name || profile?.name || "User", meta: authDrivenProfile?.meta || profile?.meta || "", photoPath: authDrivenProfile?.photoPath || profile?.photoPath || "", }; const effectiveNav = useMemo(() => { // Hide admin shortcut for non-admin faculty users to keep sidebar focused. if (variant === "faculty" && String(storedRole || "").toLowerCase() !== "super_admin") { return nav.filter((item) => item.to !== "/admin/dashboard"); } return nav; }, [nav, storedRole, variant]); const profileMenuItems = useMemo(() => { if (variant !== "faculty") return []; const items = [{ label: "Profile", to: "/faculty/profile" }]; items.push({ label: "Admin Dashboard", to: "/admin/dashboard" }); return items; }, [variant]); useEffect(() => { setProfileMenuOpen(false); }, [location.pathname]); useEffect(() => { document.body.classList.remove("light", "dark"); document.body.classList.add(theme); localStorage.setItem(THEME_KEY, theme); window.dispatchEvent(new CustomEvent("theme-change", { detail: { theme } })); }, [theme]); const toggleTheme = () => { setTheme((prev) => (prev === "dark" ? "light" : "dark")); }; const isNavItemActive = (targetPath) => { if (!targetPath) return false; if (location.pathname === targetPath) return true; return location.pathname.startsWith(`${targetPath}/`); }; return (
setSidebarOpen(false)} aria-hidden="true" />

{title}

{subtitle ?

{subtitle}

: null}
{actions ?
{actions}
: null}
{children}
); } function SectionCard({ title, action, children, className = "" }) { return (
{(title || action) && (

{title}

{action}
)} {children}
); } function StatGrid({ stats }) { return (
{stats.map((stat) => { const Icon = stat.icon; return (
{stat.value} {stat.label}
); })}
); } function SimpleTable({ columns, rows }) { return (
{columns.map((column) => ( ))} {rows.map((row, index) => ( {row.map((cell, cellIndex) => ( ))} ))}
{column}
{cell}
); } function ProfileFields({ items }) { return (
{items.map(([label, value]) => (
{label} {value}
))}
); } function FormGrid({ fields, action }) { return (
event.preventDefault()}>
{fields.map((field) => ( ))}
); } function SkeletonBlock({ className = "" }) { return
; } function TableSkeleton({ rows = 5, columns = 4, className = "" }) { const rowStyle = { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }; return (
{Array.from({ length: columns }, (_, index) => (
))}
{Array.from({ length: rows }, (_, rowIndex) => (
{Array.from({ length: columns }, (_, colIndex) => (
))}
))}
); } function FilterSkeleton({ fields = 6 }) { return (
{Array.from({ length: fields }, (_, index) => (
))}
); } function DashboardSkeleton({ variant = "faculty" }) { if (variant === "student") { return (
{Array.from({ length: 4 }, (_, index) => (
))}
); } return (
); } function FullScreenPortalSkeleton({ variant = "faculty" }) { return (
); } export { AuthGate, RequireFacultyAuth, RequireAdminAuth, PageShell, SectionCard, StatGrid, SimpleTable, ProfileFields, FormGrid, SkeletonBlock, TableSkeleton, FilterSkeleton, DashboardSkeleton, FullScreenPortalSkeleton };