'use client'; import { Bell } from 'lucide-react'; import { useRouter } from 'next/navigation'; import { useEffect, useRef } from 'react'; import { Button } from '@/components/ui/button'; import { useAuthStore } from '@/lib/auth-store'; import type { NotificationDto } from '@/lib/notifications-api'; import { useNotificationsStore } from '@/lib/notifications-store'; import { cn } from '@/lib/utils'; export function NotificationBell() { const { notifications, unreadCount, isOpen, isLoading, setOpen, markAsRead, markAllAsRead, fetchUnreadCount, } = useNotificationsStore(); const isAuthenticated = useAuthStore((s) => s.isAuthenticated); const router = useRouter(); const dropdownRef = useRef(null); // Fetch unread count only when the user is actually signed in — otherwise // the request returns 401 and floods the dev console with ApiError. useEffect(() => { if (!isAuthenticated) return; fetchUnreadCount(); }, [fetchUnreadCount, isAuthenticated]); // Close on click outside useEffect(() => { if (!isOpen) return; const handleClick = (e: MouseEvent) => { if ( dropdownRef.current && !dropdownRef.current.contains(e.target as Node) ) { setOpen(false); } }; document.addEventListener('mousedown', handleClick); return () => document.removeEventListener('mousedown', handleClick); }, [isOpen, setOpen]); const handleNotificationClick = async (notification: NotificationDto) => { if (!notification.isRead) { await markAsRead(notification.id); } if (notification.link) { router.push(notification.link); } setOpen(false); }; return (
{isOpen && (
{/* Header */}

Thông báo

{unreadCount > 0 && ( )}
{/* List */}
{isLoading ? (
) : notifications.length === 0 ? (
Chưa có thông báo
) : ( notifications.map((notification) => ( )) )}
{/* Footer */} {notifications.length > 0 && (
)}
)}
); } function formatTimeAgo(dateStr: string): string { const now = Date.now(); const date = new Date(dateStr).getTime(); const diffMs = now - date; const diffMin = Math.floor(diffMs / 60000); if (diffMin < 1) return 'Vừa xong'; if (diffMin < 60) return `${diffMin} phút trước`; const diffHours = Math.floor(diffMin / 60); if (diffHours < 24) return `${diffHours} giờ trước`; const diffDays = Math.floor(diffHours / 24); if (diffDays < 7) return `${diffDays} ngày trước`; return new Date(dateStr).toLocaleDateString('vi-VN'); }