"use client" import { useState, useEffect, useRef } from "react" import Link from "next/link" import { usePathname, useRouter } from "next/navigation" import { Button } from "@/components/ui/button" import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar" import { Badge } from "@/components/ui/badge" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger, } from "@/components/ui/sheet" import { Cpu, Menu, Bell, X, User, Settings, LogOut, Wrench, Users, BookOpen, MessageSquare, BarChart3, Home, Heart, Eye, Plus, Search, LogIn, Shield, LayoutGrid, } from "lucide-react" import { useAuth } from "@/contexts/supabase-auth-context" import { useLoading } from "@/contexts/loading-context" import { supabase } from "@/lib/supabase" interface NavigationProps { variant?: "default" | "minimal" | "dashboard" } export function Navigation({ variant = "default" }: NavigationProps) { const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false) const { user, logout } = useAuth() const pathname = usePathname() const router = useRouter() const { startLoading, stopLoading } = useLoading() const [notifications, setNotifications] = useState([]) const [unreadCount, setUnreadCount] = useState(0) useEffect(() => { if (!user) return const fetchNotifications = async () => { const { data, error } = await supabase .from("notifications") .select(` notification_id, type, created_at, is_read, build_id, comment_id, actor:users!fk_notify_actor ( user_id, user_name, avatar_url ), builds!fk_notify_build ( build_name ) `) .eq("user_id", user.user_id) .order("created_at", { ascending: false }) .limit(10) if (!error && data) { setNotifications(data) setUnreadCount(data.filter(n => !n.is_read).length) } } fetchNotifications() }, [user]) const NotificationsDropdown = () => { const { user } = useAuth() const [isSheetOpen, setIsSheetOpen] = useState(false) const [notifications, setNotifications] = useState([]) const [unreadCount, setUnreadCount] = useState(0) const [loadingMore, setLoadingMore] = useState(false) const [hasMore, setHasMore] = useState(true) const PAGE_SIZE = 10 const containerRef = useRef(null) const formatTime = (dateString: string) => { const date = new Date(dateString) return new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "numeric", hour12: true, }).format(date) } const fetchNotifications = async (offset = 0) => { if (!user || !hasMore) return setLoadingMore(true) const { data, error } = await supabase .from("notifications") .select(` notification_id, type, created_at, is_read, build_id, comment_id, actor:users!fk_notify_actor ( user_id, user_name, avatar_url ), builds!fk_notify_build ( build_name ) `) .eq("user_id", user.user_id) .order("created_at", { ascending: false }) .range(offset, offset + PAGE_SIZE - 1) setLoadingMore(false) if (!error && data) { if (data.length < PAGE_SIZE) setHasMore(false) // append new batch setNotifications(prev => [...prev, ...data]) setUnreadCount(data.filter(n => !n.is_read).length + (offset === 0 ? 0 : unreadCount)) } } const handleScroll = () => { if (!containerRef.current || loadingMore || !hasMore) return const { scrollTop, scrollHeight, clientHeight } = containerRef.current if (scrollTop + clientHeight >= scrollHeight - 5) { fetchNotifications(notifications.length) } } // Reset when sheet opens useEffect(() => { if (!isSheetOpen) { // Reset everything when closing setNotifications([]) setUnreadCount(0) setHasMore(true) } else if (isSheetOpen && notifications.length === 0) { // Load first batch when opening if empty fetchNotifications(0) } }, [isSheetOpen]) const handleMarkAsRead = async (notifId: string) => { await supabase .from("notifications") .update({ is_read: true }) .eq("notification_id", notifId) setNotifications(prev => prev.map(n => (n.notification_id === notifId ? { ...n, is_read: true } : n)) ) setUnreadCount(notifications.filter(n => !n.is_read).length) } const markAllAsRead = async () => { const unreadIds = notifications.filter(n => !n.is_read).map(n => n.notification_id) if (unreadIds.length === 0) return await supabase .from("notifications") .update({ is_read: true }) .in("notification_id", unreadIds) setNotifications(prev => prev.map(n => ({ ...n, is_read: true }))) setUnreadCount(0) } const renderNotificationItem = (notif: any) => { const linkHref = notif.type === "comment" && notif.comment_id ? `/builds/${notif.build_id}#comment-${notif.comment_id}` : notif.type === "follow" ? `/profile/${notif.actor.user_id}` : notif.build_id ? `/builds/${notif.build_id}` : "#" return ( { await handleMarkAsRead(notif.notification_id) setIsSheetOpen(false) }} className={`flex gap-3 items-start cursor-pointer px-3 py-2 rounded-md transition-colors ${ !notif.is_read ? "bg-blue-50 dark:bg-blue-900/30 font-medium" : "hover:bg-slate-100 dark:hover:bg-slate-800" }`} > {notif.actor.user_name.charAt(0).toUpperCase()}

{notif.actor.user_name}{" "} {notif.type === "like" && "liked your build"} {notif.type === "comment" && "commented on your build"} {notif.type === "follow" && "started following you"} {notif.builds?.build_name && {notif.builds.build_name}}

{formatTime(notif.created_at)}

{notif.type === "like" && } {notif.type === "comment" && } {notif.type === "follow" && } ) } return ( <> { setIsSheetOpen(open) if (!open) markAllAsRead() }} > All Notifications Recent activity on your account
{notifications.length === 0 ? (

No notifications

) : ( notifications.map(renderNotificationItem) )} {loadingMore && (

Loading more...

)}
) } const isActive = (path: string) => pathname === path const handleLinkClick = (href: string, label: string) => { if (pathname !== href) { startLoading(`Loading ${label.toLowerCase()}...`) // Navigation will be handled by Next.js Link component // Loading will be managed by LoadingProvider based on pathname change } } const mainNavItems = [ { href: "/builder", label: "PC Builder", icon: Wrench }, { href: "/builds", label: "Community Builds", icon: Users }, { href: "/guides", label: "Build Guides", icon: BookOpen }, { href: "/services", label: "Our Services", icon: LayoutGrid }, { href: "/support", label: "Support", icon: MessageSquare }, ] const userNavItems = [ { href: "/dashboard", label: "Dashboard", icon: Home }, { href: "/profile", label: "Profile", icon: User }, { href: "/mybuilds", label: "My Builds", icon: Wrench }, { href: "/likedbuilds", label: "Liked Builds", icon: Heart }, { href: "/settings", label: "Settings", icon: Settings }, ...(user?.user_type === 'admin' ? [{ href: "/admin", label: "Admin Dashboard", icon: Shield }] : []), ] const handleLogout = async () => { await logout() setIsMobileMenuOpen(false) router.push("/") router.refresh() } if (variant === "minimal") { return (

BuildMate

{user ? (

{user.user_name || user.email?.split('@')[0] || "User"}

{user.email}

handleLinkClick("/dashboard", "Dashboard")}> Dashboard handleLinkClick("/profile", "Profile")}> Profile handleLinkClick("/settings", "Settings")}> Settings Log out
) : ( handleLinkClick("/login", "Login")}> Login handleLinkClick("/register", "Sign Up")}> Sign Up )}
) } // Default variant return (

BuildMate

{/* Desktop Navigation */}
{user ? (

{user.user_name || user.email?.split('@')[0] || "User"}

{user.email}

{userNavItems.map((item) => ( handleLinkClick(item.href, item.label)}> {item.label} ))} Log out
) : ( handleLinkClick("/login", "Login")}> Login handleLinkClick("/register", "Sign Up")}> Sign Up )} {/* Mobile Menu */} BuildMate Navigate through the application
{/* Main Navigation */}

Main Menu

{mainNavItems.map((item) => ( { handleLinkClick(item.href, item.label) setIsMobileMenuOpen(false) }} > {item.label} ))}
{/* User Navigation */} {user && (

Account

{userNavItems.map((item) => ( { handleLinkClick(item.href, item.label) setIsMobileMenuOpen(false) }} > {item.label} ))}
)} {/* Guest Navigation */} {!user && (

Account

setIsMobileMenuOpen(false)} > Login setIsMobileMenuOpen(false)} > Sign Up
)}
) }