'use client'; import { useState, useEffect, useCallback } from 'react'; import { useRouter } from 'next/navigation'; import { useTheme } from 'next-themes'; import { logout } from '@/lib/auth'; import { useAuthStore } from '@/stores/auth.store'; import { api } from '@/lib/api'; function timeAgo(date: string) { const seconds = Math.floor((Date.now() - new Date(date).getTime()) / 1000); if (seconds < 60) return 'just now'; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `${minutes}m ago`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours}h ago`; const days = Math.floor(hours / 24); return `${days}d ago`; } interface Notification { id: string; title: string; message: string; isRead: boolean; createdAt: string; channel: string; } export function Header({ onSupportOpen }: { onSupportOpen: () => void }) { const router = useRouter(); const { theme, setTheme } = useTheme(); const logoutStore = useAuthStore((s) => s.logout); const [unread, setUnread] = useState(0); const [showNotifs, setShowNotifs] = useState(false); const [notifs, setNotifs] = useState([]); const fetchUnread = useCallback(() => { api.get('/notifications/unread-count').then((r) => setUnread(r.data.data.count)).catch(() => {}); }, []); // Auto-refresh unread count every 30s and on window focus useEffect(() => { fetchUnread(); const interval = setInterval(fetchUnread, 30_000); const onFocus = () => fetchUnread(); window.addEventListener('focus', onFocus); return () => { clearInterval(interval); window.removeEventListener('focus', onFocus); }; }, [fetchUnread]); async function toggleNotifs() { const next = !showNotifs; setShowNotifs(next); if (next) { const res = await api.get('/notifications'); setNotifs(res.data.data); } } async function markAllRead() { await api.patch('/notifications/read-all'); setUnread(0); setNotifs(notifs.map((n) => ({ ...n, isRead: true }))); } async function markOneRead(id: string) { await api.patch(`/notifications/${id}/read`); setNotifs(notifs.map((n) => n.id === id ? { ...n, isRead: true } : n)); setUnread((u) => Math.max(0, u - 1)); } function handleLogout() { logout(); logoutStore(); router.push('/login'); } return (
{/* Notification bell */}
{showNotifs && (
Notifications {unread > 0 && ( )}
{notifs.length > 0 ? notifs.map((n) => ( )) : (
No notifications
)}
)}
{/* Dark/Light mode toggle */} {/* Support icon */}
); }