/**
* Authenticated application layout for the Tloto web app.
* Renders responsive navigation, header actions, and nested route content.
*/
import {
AppBar,
Alert,
Box,
Button,
Chip,
Container,
Divider,
IconButton,
Stack,
Toolbar,
} from '@mui/material';
import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined';
import PeopleOutlineRoundedIcon from '@mui/icons-material/PeopleOutlineRounded';
import HomeRoundedIcon from '@mui/icons-material/HomeRounded';
import DashboardRoundedIcon from '@mui/icons-material/DashboardRounded';
import TuneRoundedIcon from '@mui/icons-material/TuneRounded';
import InsightsRoundedIcon from '@mui/icons-material/InsightsRounded';
import AccountBalanceWalletRoundedIcon from '@mui/icons-material/AccountBalanceWalletRounded';
import GroupAddRoundedIcon from '@mui/icons-material/GroupAddRounded';
import PersonRoundedIcon from '@mui/icons-material/PersonRounded';
import MenuRoundedIcon from '@mui/icons-material/MenuRounded';
import AssessmentRoundedIcon from '@mui/icons-material/AssessmentRounded';
import SecurityRoundedIcon from '@mui/icons-material/SecurityRounded';
import HeadsetMicRoundedIcon from '@mui/icons-material/HeadsetMicRounded';
import GavelRoundedIcon from '@mui/icons-material/GavelRounded';
import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded';
import { PrediqoLogo } from '../brand/PrediqoLogo';
import HelpOutlineRoundedIcon from '@mui/icons-material/HelpOutlineRounded';
import Badge from '@mui/material/Badge';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../services/api';
import {
Drawer,
List,
ListItemButton,
ListItemIcon,
ListItemText,
useMediaQuery,
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import { Link as RouterLink, Outlet, useLocation } from 'react-router-dom';
import { prefetchRoute } from '../../app/router/routePrefetch';
import { useAuth } from '../auth/AuthContext';
import { ADMIN_PAGE_PERMISSIONS } from '../auth/permissions';
import { useAppPresenceHeartbeat } from '../hooks/useAppPresenceHeartbeat';
import { useEffect, useMemo, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { LanguageSwitcher } from '../i18n/LanguageSwitcher';
import { useSecuritySocket } from '../../features/security/hooks/useSecuritySocket';
import type { SecurityWsServerMessage } from '../../features/security/ws/protocol';
import { apiErrorMessage, isAdmin2faRequiredError } from '../utils/apiError';
/**
* Main shell with sidebar navigation, top app bar, and outlet for protected pages.
* Shows admin-only nav items when the current user has the admin role.
*
* @returns The responsive admin layout wrapping child routes.
*/
export function AppShell() {
const { t } = useTranslation();
const { logout, isAdmin, hasAdminPanel, isStaff, auth, canApproveFundOps, can } = useAuth();
const theme = useTheme();
const isMdUp = useMediaQuery(theme.breakpoints.up('md'));
const [mobileOpen, setMobileOpen] = useState(false);
const location = useLocation();
const qc = useQueryClient();
const role = auth.roles?.length
? auth.roles.join(', ')
: (auth.role ?? 'unknown');
const userShort = auth.userId ? `${auth.userId.slice(0, 8)}…` : '—';
useAppPresenceHeartbeat();
const onSecurityBadgeEvent = useCallback(
(msg: SecurityWsServerMessage) => {
if (msg.type === 'security.notification.new' || msg.type === 'security.alert.raised') {
void qc.invalidateQueries({ queryKey: ['admin-notifications-unread'] });
}
},
[qc]
);
const { connected: securityWsConnected } = useSecuritySocket({
enabled: hasAdminPanel || isAdmin,
onEvent: onSecurityBadgeEvent,
});
const notificationsQ = useQuery({
queryKey: ['admin-notifications-unread'],
queryFn: async () => {
const res = await api.get<{ unreadCount: number }>('/api/v1/admin/notifications', {
params: { limit: '1' },
});
return res.data.unreadCount;
},
enabled: hasAdminPanel || isAdmin,
refetchInterval: securityWsConnected ? 120_000 : 30_000,
});
const adminAccessProbeQ = useQuery({
queryKey: ['admin-access-probe'],
queryFn: async () => {
await api.get('/api/v1/admin/overview');
return true;
},
enabled: hasAdminPanel || isAdmin,
retry: false,
staleTime: 60_000,
});
const admin2faRequired = isAdmin2faRequiredError(adminAccessProbeQ.error);
const supportUnreadQ = useQuery({
queryKey: ['admin-support-unread'],
queryFn: async () => {
const res = await api.get<{ unreadCount: number }>('/api/v1/admin/support/unread');
return res.data.unreadCount;
},
enabled: isStaff,
refetchInterval: 15_000,
});
// No polling: refresh on mount/focus and whenever a mutation invalidates ['admin-fund-requests'].
const pendingApprovalsQ = useQuery({
queryKey: ['admin-fund-requests', 'pending-count'],
queryFn: async () => {
const res = await api.get<{ total: number }>('/api/v1/admin/fund-requests', {
params: { status: 'pending_approval', limit: 1 },
});
return res.data.total;
},
enabled: canApproveFundOps,
staleTime: 30_000,
});
const unreadNotifications = notificationsQ.data ?? 0;
const unreadSupport = supportUnreadQ.data ?? 0;
const pendingApprovals = pendingApprovalsQ.data ?? 0;
useEffect(() => {
if (!isMdUp) {
setMobileOpen(false);
}
}, [isMdUp]);
useEffect(() => {
setMobileOpen(false);
}, [location.pathname]);
const adminNavItems = useMemo(
() =>
[
{ label: t('nav.overview'), to: '/dashboard', icon: },
{ label: t('nav.reports'), to: '/admin/reports', icon: },
{ label: t('nav.options'), to: '/options', icon: },
{ label: t('nav.marketing'), to: '/admin/marketing', icon: },
{ label: t('nav.users'), to: '/admin/users', icon: },
{
label: t('nav.security'),
to: '/admin/security',
icon: (
),
},
{ label: t('nav.settings'), to: '/admin/settings', icon: },
].filter((item) => {
const perm = ADMIN_PAGE_PERMISSIONS[item.to];
return !perm || can(perm);
}),
[t, can, unreadNotifications]
);
const navItems = useMemo(
() =>
[
{ label: t('nav.home'), to: '/home', icon: },
{ label: t('nav.wallet'), to: '/wallet', icon: },
{ label: t('nav.referrals'), to: '/referral', icon: },
{ label: t('nav.profile'), to: '/profile', icon: },
{ label: t('nav.faq'), to: '/help/faq', icon: },
...(isStaff
? [
{
label: t('nav.support'),
to: '/admin/support',
icon: (
),
},
]
: []),
...(canApproveFundOps
? [
{
label: t('nav.approvals'),
to: '/admin/approvals',
icon: (
),
},
{
label: t('nav.approvalPolicies'),
to: '/admin/approval-policies',
icon: ,
},
]
: []),
...(hasAdminPanel || isAdmin ? adminNavItems : []),
] as const,
[t, isAdmin, hasAdminPanel, isStaff, canApproveFundOps, unreadSupport, pendingApprovals, adminNavItems]
);
const drawer = (
{navItems.map((it) => {
const selected = location.pathname === it.to || location.pathname.startsWith(it.to + '/');
return (
setMobileOpen(false)}
onMouseEnter={() => prefetchRoute(it.to)}
onFocus={() => prefetchRoute(it.to)}
onTouchStart={() => prefetchRoute(it.to)}
sx={{ borderRadius: 2, mb: 0.5 }}
>
{it.icon}
);
})}
);
return (
{/* Sidebar */}
setMobileOpen(false)}
ModalProps={{ keepMounted: true }}
sx={{
'& .MuiDrawer-paper': {
width: 280,
boxSizing: 'border-box',
borderRight: '1px solid rgba(255,255,255,0.08)',
backgroundImage: 'none',
backgroundColor: 'rgba(18,23,36,0.92)',
backdropFilter: 'blur(12px)',
},
}}
>
{drawer}
{/* Main */}
{!isMdUp && (
setMobileOpen(true)}
sx={{ mr: 0.5 }}
>
)}
{admin2faRequired && (
{apiErrorMessage(adminAccessProbeQ.error, t('admin.admin2faRequired'))}{' '}
)}
);
}