import React, { useEffect, useMemo, useState } from "react"; import { AppBar, Avatar, Badge, Box, Breadcrumbs, Button, ButtonGroup, Chip, Divider, Drawer, IconButton, List, ListItem, ListItemButton, ListItemIcon, ListItemText, Menu, MenuItem, Toolbar, Tooltip, Typography, } from "@mui/material"; import useMediaQuery from "@mui/material/useMediaQuery"; import MenuIcon from "@mui/icons-material/Menu"; import MenuOpenIcon from "@mui/icons-material/MenuOpen"; import NotificationsNoneIcon from "@mui/icons-material/NotificationsNone"; import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined"; import JobbjaktMark from "../assets/JobbjaktMark"; import { useI18n } from "../i18n/I18nProvider"; export type NavItem = { to: string; label: string; icon: React.ReactNode; hidden?: boolean; section?: string; badgeCount?: number; }; function initialsFrom(s?: string) { const v = (s ?? "").trim(); if (!v) return "?"; const parts = v.split(/[\s@._-]+/).filter(Boolean); if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase(); return (parts[0][0] + parts[1][0]).toUpperCase(); } const DESKTOP_SIDEBAR_KEY = "appShellDesktopSidebarCollapsed"; // Which single nav item owns the current path. A child route must not light up its parent: // /career/builder/5 belongs to "CV Builder" (/career/builder), not "Career Workspace" (/career), // even though the old `pathname.startsWith(to + "/")` test matched both. Explicit ownership = // the LONGEST `to` that the path is at or under wins; everything else is inactive. Exported so the // rule is unit-testable without rendering the shell. export function activeNavTo(pathname: string, tos: string[]): string | null { let best: string | null = null; for (const to of tos) { const owns = pathname === to || pathname.startsWith(to + "/"); if (owns && (best === null || to.length > best.length)) best = to; } return best; } // The nav rail stays a fixed dark navy regardless of the app's light/dark theme toggle -- // a deliberate signature element, not derived from theme tokens. const SIDEBAR_BG = "#0f172a"; const SIDEBAR_BORDER = "rgba(255,255,255,0.08)"; const SIDEBAR_TEXT_MUTED = "#94a3b8"; const SIDEBAR_TEXT = "#e2e8f0"; const SIDEBAR_SELECTED_BG = "rgba(99,102,241,0.18)"; const SIDEBAR_SELECTED_TEXT = "#ffffff"; const SIDEBAR_SELECTED_ICON = "#a5b4fc"; export default function AppShell({ pageTitle, pageSubtitle, breadcrumbs, pathname, nav, navBottom, onNavigate, onToggleDrawer, drawerOpen, user, buildMetadata, notificationsCount, onOpenNotifications, onOpenSettings, onOpenProfile, onSignOut, rightActions, children, }: { pageTitle: string; pageSubtitle?: string; breadcrumbs: string[]; pathname: string; nav: NavItem[]; navBottom: NavItem[]; onNavigate: (to: string) => void; onToggleDrawer: (open: boolean) => void; drawerOpen: boolean; user?: { email?: string; userName?: string; displayName?: string; avatarImageDataUrl?: string; roleLabel?: string }; buildMetadata?: { version: string; commitSha?: string }; notificationsCount?: number; onOpenNotifications?: (anchorEl: HTMLElement) => void; onOpenSettings?: () => void; onOpenProfile?: () => void; onSignOut?: () => void; rightActions?: React.ReactNode; children: React.ReactNode; }) { const { language, setLanguage, t } = useI18n(); const isMobile = useMediaQuery("(max-width:767.95px)"); const [desktopNavCollapsed, setDesktopNavCollapsed] = useState(() => { try { return window.localStorage.getItem(DESKTOP_SIDEBAR_KEY) === "1"; } catch { return false; } }); const drawerWidth = isMobile ? 254 : desktopNavCollapsed ? 84 : 254; useEffect(() => { try { window.localStorage.setItem(DESKTOP_SIDEBAR_KEY, desktopNavCollapsed ? "1" : "0"); } catch { // ignore storage failures } }, [desktopNavCollapsed]); const grouped = useMemo(() => { const groupItems = (items: NavItem[]) => { const map = new Map(); for (const it of items.filter((x) => !x.hidden)) { const key = it.section || ""; map.set(key, [...(map.get(key) ?? []), it]); } return Array.from(map.entries()); }; return { top: groupItems(nav), bottom: groupItems(navBottom), }; }, [nav, navBottom]); // Compute the one active destination across BOTH nav lists, so the most specific route wins. const activeTo = useMemo( () => activeNavTo(pathname, [...nav, ...navBottom].map((i) => i.to)), [pathname, nav, navBottom], ); const renderNavList = (groups: Array<[string, NavItem[]]>) => ( {groups.map(([section, rows]) => ( {section && !desktopNavCollapsed ? ( {section} ) : null} {rows.map((item) => { const selected = item.to === activeTo; return ( onNavigate(item.to)} title={desktopNavCollapsed ? item.label : undefined} sx={{ borderRadius: 2, minHeight: 44, px: desktopNavCollapsed ? 1 : 1.5, justifyContent: desktopNavCollapsed ? "center" : "flex-start", border: "1px solid transparent", color: SIDEBAR_TEXT_MUTED, "&:hover": { backgroundColor: "rgba(255,255,255,0.06)", color: SIDEBAR_TEXT }, "&.Mui-selected": { backgroundColor: SIDEBAR_SELECTED_BG, color: SIDEBAR_SELECTED_TEXT, }, "&.Mui-selected:hover": { backgroundColor: SIDEBAR_SELECTED_BG, }, }} > {item.badgeCount && item.badgeCount > 0 ? ( 99 ? "99+" : item.badgeCount}> {item.icon} ) : item.icon} {!desktopNavCollapsed ? : null} ); })} ))} ); const drawerContent = ( {!desktopNavCollapsed ? ( Jobbjakt {t("appTagline")} ) : null} {renderNavList(grouped.top)} {renderNavList(grouped.bottom)} ); const nameForAvatar = user?.userName || user?.displayName || user?.email; const initials = initialsFrom(nameForAvatar); const buildVersion = buildMetadata?.version.trim(); const buildCommit = buildMetadata?.commitSha?.trim(); const buildBadge = buildVersion ? ( ) : null; const [userMenuAnchor, setUserMenuAnchor] = useState(null); const userMenuOpen = Boolean(userMenuAnchor); return ( ({ borderBottom: `1px solid ${muiTheme.vars.palette.grey[300]}`, backgroundColor: muiTheme.vars.palette.background.default, backgroundImage: "none", zIndex: muiTheme.zIndex.drawer + 1, })} > {isMobile ? ( <> onToggleDrawer(true)} sx={{ border: "1px solid", borderColor: "divider", borderRadius: 2.5, width: 42, height: 42 }} > Jobbjakt {buildBadge} {user ? ( setUserMenuAnchor(e.currentTarget)} sx={{ borderRadius: 2.5, border: "1px solid", borderColor: "divider", width: 42, height: 42, flex: "0 0 auto" }} > {initials} ) : } onOpenNotifications?.(event.currentTarget)} sx={{ border: "1px solid", borderColor: "divider", borderRadius: 2.5, width: 42, height: 42 }} > *': { minWidth: 0 }, }} > {rightActions} ) : ( <> setDesktopNavCollapsed((value) => !value)} title={desktopNavCollapsed ? t("expandSidebar") : t("collapseSidebar")} aria-label={desktopNavCollapsed ? t("expandSidebar") : t("collapseSidebar")} sx={{ border: "1px solid", borderColor: "divider", borderRadius: 2, width: 40, height: 40 }} > {buildBadge} onOpenNotifications?.(event.currentTarget)} sx={{ border: "1px solid", borderColor: "divider", borderRadius: 2 }} > {rightActions} {user ? ( setUserMenuAnchor(e.currentTarget)} sx={{ borderRadius: 2, border: "1px solid", borderColor: "divider" }} > {initials} {user.userName || user.displayName || user.email || t("user")} {user.roleLabel || ""} ) : null} )} setUserMenuAnchor(null)} anchorOrigin={{ vertical: "bottom", horizontal: "right" }} transformOrigin={{ vertical: "top", horizontal: "right" }} > { setUserMenuAnchor(null); onOpenProfile?.(); }} > {t("profileMenu")} { setUserMenuAnchor(null); onOpenSettings?.(); }} > {t("settingsMenu")} { setUserMenuAnchor(null); onSignOut?.(); }} > {t("signOut")} {drawerContent} onToggleDrawer(false)} ModalProps={{ keepMounted: true }} sx={{ display: { xs: "block", md: "none" }, [`& .MuiDrawer-paper`]: { width: drawerWidth, borderRight: `1px solid ${SIDEBAR_BORDER}`, backgroundColor: SIDEBAR_BG, backgroundImage: "none", }, }} > {drawerContent} {breadcrumbs.map((c) => ( {c} ))} {pageTitle} {pageSubtitle ? ( {pageSubtitle} ) : null} {children} ); } export function StackLanguageToggle({ language, setLanguage, onDark = false }: { language: "en" | "nb"; setLanguage: (language: "en" | "nb") => void; onDark?: boolean }) { const { t } = useI18n(); return ( ); }