import { useState } from 'react' import Link from 'next/link' import { usePathname, useRouter } from 'next/navigation' import { useQuery } from '@tanstack/react-query' import { settingsAPI } from '@/lib/api' import { cn } from '@/lib/utils' import { clearAuth } from '@/lib/auth' import { Badge } from '@/components/ui/badge' interface NavItem { label: string href: string icon: React.ReactNode } interface SidebarProps { isOpen?: boolean onClose?: () => void } const navItems: NavItem[] = [ { label: 'Dashboard', href: '/dashboard', icon: ( ), }, { label: 'Monitors', href: '/monitors', icon: ( ), }, { label: 'Incidents', href: '/incidents', icon: ( ), }, { label: 'Analytics', href: '/analytics', icon: ( ), }, { label: 'Settings', href: '/settings', icon: ( ), }, ] export function Sidebar({ isOpen, onClose }: SidebarProps = {}) { const pathname = usePathname() const router = useRouter() const [mobileOpen, setMobileOpen] = useState(false) // Fetch user settings to show current plan const { data: settingsData } = useQuery({ queryKey: ['settings'], queryFn: async () => { try { const response = await settingsAPI.get() return response.settings || {} } catch (e) { return {} } }, }) // Default to stored user plan from localStorage if API fails or is loading const getStoredPlan = () => { if (typeof window !== 'undefined') { try { const userStr = localStorage.getItem('user'); if (userStr) return JSON.parse(userStr).plan; } catch { return 'free'; } } return 'free'; } // Capitalize plan name const planName = (settingsData?.plan || getStoredPlan() || 'free').charAt(0).toUpperCase() + (settingsData?.plan || getStoredPlan() || 'free').slice(1); // Determine badge color const getBadgeVariant = (plan: string) => { switch (plan?.toLowerCase()) { case 'pro': return 'default'; // Primary color case 'business': return 'secondary'; case 'enterprise': return 'destructive'; // Or another prominent color default: return 'outline'; } }; // Use controlled state if provided, otherwise use internal state const sidebarOpen = isOpen !== undefined ? isOpen : mobileOpen const handleClose = onClose || (() => setMobileOpen(false)) const handleLogout = () => { clearAuth() router.push('/login') } const isActive = (href: string) => { if (href === '/dashboard') { return pathname === '/dashboard' } if (href === '/monitors') { return pathname === '/monitors' || pathname?.startsWith('/monitors/') } return pathname === href || pathname?.startsWith(href + '/') } const handleNavClick = () => { // Close mobile sidebar after navigation if (window.innerWidth < 1024) { handleClose() } } return ( <> {/* Mobile Hamburger Button */} {/* Mobile Overlay */} {sidebarOpen && (
)} {/* Sidebar */} > ) }