import React, { memo, useState, useEffect } from 'react'; import Link from 'next/link'; import { Bell, Check, ExternalLink, AlertCircle } from 'lucide-react'; import { Badge } from '@/components/ui/badge'; import { useNotifications } from '@/hooks/use-notifications'; import { Button } from '@/components/ui/button'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator, } from '@/components/ui/dropdown-menu'; import { formatDistanceToNow } from 'date-fns'; interface NotificationBadgeProps { className?: string; } // Use React.memo to prevent unnecessary re-renders export const NotificationBadge = memo(function NotificationBadge({ className }: NotificationBadgeProps) { const { notifications, notificationCount, markAsRead, markAllAsRead, fetchNotifications, loading, error } = useNotifications(); const hasUnread = notificationCount.unread > 0; const [isOpen, setIsOpen] = useState(false); console.log('[NOTIFICATION_BADGE] Current notification count:', notificationCount); console.log('[NOTIFICATION_BADGE] Current notifications:', notifications.length > 0 ? `${notifications.length} loaded` : 'none loaded'); console.log('[NOTIFICATION_BADGE] Loading state:', loading); console.log('[NOTIFICATION_BADGE] Error state:', error); // Fetch notifications when dropdown is opened useEffect(() => { if (isOpen) { console.log('[NOTIFICATION_BADGE] Dropdown opened, fetching notifications'); fetchNotifications(1, 10); } }, [isOpen, fetchNotifications]); const handleMarkAsRead = async (notificationId: string) => { await markAsRead(notificationId); }; const handleMarkAllAsRead = async () => { await markAllAsRead(); setIsOpen(false); }; // Force fetch when component mounts useEffect(() => { console.log('[NOTIFICATION_BADGE] Component mounted, fetching initial notifications'); fetchNotifications(1, 10); }, [fetchNotifications]); // Take the latest 10 notifications for the dropdown const recentNotifications = notifications.slice(0, 10); const handleOpenChange = (open: boolean) => { setIsOpen(open); if (open) { // Fetch fresh notifications when dropdown opens console.log('[NOTIFICATION_BADGE] Dropdown opened via handleOpenChange, fetching notifications'); fetchNotifications(1, 10); } }; return (

Notifications

{notificationCount.unread > 0 && ( )}
{loading ? (

Loading notifications...

) : error ? (

{error}

) : notifications.length === 0 ? (

No notifications

) : ( <> {recentNotifications.map((notification) => (

{notification.title} {!notification.isRead && ( New )}

{formatDistanceToNow(new Date(notification.timestamp), { addSuffix: true })}

{!notification.isRead && ( )} {notification.link && ( )}

{notification.message}

))} )}
); });