'use client' import Link from 'next/link' import { usePathname, useRouter } from 'next/navigation' import { useEffect, useState } from 'react' import { LayoutDashboard, Car, Calendar, Globe, Users, Tag, UserPlus, BarChart2, CreditCard, Bell, Settings, LogOut, FileText, ChevronLeft, ChevronRight, Star, AlertTriangle, } from 'lucide-react' import { DashboardLanguageSwitcher, DashboardThemeSwitcher, useDashboardI18n } from '@/components/I18nProvider' import { marketplaceUrl } from '@/lib/urls' import { EMPLOYEE_PROFILE_KEY, EMPLOYEE_TOKEN_KEY, apiFetch } from '@/lib/api' import { toDashboardAppPath } from '@/lib/dashboardPaths' import { SHARED_LANGUAGE_KEY, readCurrentUserScopedPreference } from '@/lib/preferences' interface BrandSettings { displayName: string logoUrl: string | null } interface SidebarUser { displayName: string subtitle: string initials: string } interface EmployeeProfile { email: string firstName: string lastName: string role: string preferredLanguage?: string } function computeInitials(name: string): string { const parts = name.trim().split(/\s+/).filter(Boolean) if (parts.length === 0) return 'U' if (parts.length === 1) return parts[0].slice(0, 1).toUpperCase() return `${parts[0].slice(0, 1)}${parts[1].slice(0, 1)}`.toUpperCase() } function toSidebarUser(profile: Partial, fallbackName: string, fallbackSubtitle: string): SidebarUser { const fullName = `${profile.firstName ?? ''} ${profile.lastName ?? ''}`.trim() const email = profile.email ?? '' const role = profile.role ?? '' const displayName = fullName || (email ? email.split('@')[0] : fallbackName) const subtitle = email || role || fallbackSubtitle const initials = computeInitials(fullName || email || fallbackName) return { displayName, subtitle, initials } } const NAV_ITEMS = [ { href: '/', key: 'dashboard', icon: LayoutDashboard, exact: true, minRole: 'AGENT' }, { href: '/fleet', key: 'fleet', icon: Car, minRole: 'AGENT' }, { href: '/reservations', key: 'reservations', icon: Calendar, minRole: 'AGENT' }, { href: '/online-reservations', key: 'onlineReservations', icon: Globe, minRole: 'AGENT' }, { href: '/customers', key: 'customers', icon: Users, minRole: 'AGENT' }, { href: '/offers', key: 'offers', icon: Tag, minRole: 'MANAGER' }, { href: '/team', key: 'team', icon: UserPlus, minRole: 'AGENT' }, { href: '/reports', key: 'reports', icon: BarChart2, minRole: 'MANAGER' }, { href: '/subscription', key: 'subscription', icon: CreditCard, minRole: 'OWNER' }, { href: '/billing', key: 'billing', icon: CreditCard, minRole: 'MANAGER' }, { href: '/contracts', key: 'contracts', icon: FileText, minRole: 'AGENT' }, { href: '/reviews', key: 'reviews', icon: Star, minRole: 'AGENT' }, { href: '/complaints', key: 'complaints', icon: AlertTriangle, minRole: 'AGENT' }, { href: '/notifications', key: 'notifications', icon: Bell, minRole: 'AGENT' }, { href: '/settings', key: 'settings', icon: Settings, minRole: 'OWNER' }, ] as const const ROLE_RANK: Record = { OWNER: 3, MANAGER: 2, AGENT: 1 } function hasMinRole(employeeRole: string, minRole: string): boolean { return (ROLE_RANK[employeeRole] ?? 0) >= (ROLE_RANK[minRole] ?? 0) } function notifyParent(message: Record) { if (typeof window === 'undefined' || window.parent === window) return window.parent.postMessage(message, '*') } export default function Sidebar() { const { dict, language, setLanguage } = useDashboardI18n() const isRtl = language === 'ar' const pathname = usePathname() const appPath = toDashboardAppPath(pathname) const router = useRouter() const [brand, setBrand] = useState(null) const [user, setUser] = useState({ displayName: dict.workspaceUser, subtitle: dict.localAuth, initials: 'W', }) const [role, setRole] = useState('AGENT') const [open, setOpen] = useState(false) const [mounted, setMounted] = useState(false) useEffect(() => { setMounted(true) }, []) useEffect(() => { apiFetch('/companies/me/brand').then(setBrand).catch(() => {}) }, []) useEffect(() => { const token = window.localStorage.getItem(EMPLOYEE_TOKEN_KEY) if (!token) { setUser({ displayName: dict.workspaceUser, subtitle: dict.localAuth, initials: 'W', }) return } const cached = window.localStorage.getItem(EMPLOYEE_PROFILE_KEY) if (cached) { try { const profile = JSON.parse(cached) as Partial setUser(toSidebarUser(profile, dict.workspaceUser, dict.localAuth)) if (profile.role) setRole(profile.role) } catch {} } let cancelled = false apiFetch<{ employee: EmployeeProfile }>('/auth/employee/me') .then(({ employee }) => { if (cancelled) return window.localStorage.setItem(EMPLOYEE_PROFILE_KEY, JSON.stringify(employee)) setUser(toSidebarUser(employee, dict.workspaceUser, dict.localAuth)) if (employee.role) setRole(employee.role) if (employee.preferredLanguage === 'en' || employee.preferredLanguage === 'fr' || employee.preferredLanguage === 'ar') { // Only apply the server-side preference when the employee has no local preference // stored yet — avoids overriding a language the user manually switched to. const existingPref = readCurrentUserScopedPreference(SHARED_LANGUAGE_KEY) if (!existingPref) { setLanguage(employee.preferredLanguage) document.cookie = `rentaldrivego-language=${employee.preferredLanguage}; path=/; max-age=31536000; samesite=lax` } } }) .catch(() => { if (cancelled) return if (!cached) setUser(toSidebarUser({}, dict.workspaceUser, dict.localAuth)) }) return () => { cancelled = true } }, [dict.localAuth, dict.workspaceUser]) // Close sidebar when navigating on mobile useEffect(() => { setOpen(false) }, [pathname]) const isActive = (item: typeof NAV_ITEMS[number]) => { if ('exact' in item && item.exact) return appPath === item.href return appPath.startsWith(item.href) } function signOut() { localStorage.removeItem(EMPLOYEE_TOKEN_KEY) localStorage.removeItem(EMPLOYEE_PROFILE_KEY) document.cookie = 'employee_token=; path=/; max-age=0; samesite=lax' window.dispatchEvent(new CustomEvent('rentaldrivego:auth-changed')) notifyParent({ type: 'rentaldrivego:employee-logout' }) window.location.href = marketplaceUrl } return ( <> {/* Mobile backdrop */} {open && (
setOpen(false)} /> )} {/* Tab to open sidebar — only visible when sidebar is closed on mobile */} {!open && ( )} ) }