'use client' import { useEffect, useRef, useState } from 'react' import { useRouter } from 'next/navigation' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import api from '@/services/api' import { useRealtime } from '@/hooks/useRealtime' import type { Notification as RealtimeNotification } from '@/services/realtimeService' // ─── Types ──────────────────────────────────────────────────────────────────── type NotificationType = 'like' | 'comment' | 'follow' | 'mention' | 'repo_star' interface NotificationActor { id: string username: string avatar: string | null } interface NotificationPost { id: string content: string mediaUrl: string | null } interface NotificationRepo { id: string name: string fullName: string } interface Notification { id: string type: NotificationType read: boolean createdAt: string actor: NotificationActor | null post: NotificationPost | null repo: NotificationRepo | null } interface NotificationsResponse { data: { notifications: Notification[] total: number unreadCount: number } } // ─── Helpers ────────────────────────────────────────────────────────────────── const TYPE_ICON: Record = { like: '❤️', comment: '💬', follow: '👤', mention: '@', repo_star: '⭐', } const TYPE_ACTION: Record = { like: 'liked your post', comment: 'commented on your post', follow: 'started following you', mention: 'mentioned you', repo_star: 'starred your repository', } function relativeTime(iso: string): string { const diffMs = Date.now() - new Date(iso).getTime() const diffSec = Math.floor(diffMs / 1000) if (diffSec < 60) return `${diffSec}s` const diffMin = Math.floor(diffSec / 60) if (diffMin < 60) return `${diffMin}m` const diffHr = Math.floor(diffMin / 60) if (diffHr < 24) return `${diffHr}h` const diffDay = Math.floor(diffHr / 24) if (diffDay < 7) return `${diffDay}d` return new Date(iso).toLocaleDateString() } function notificationTarget(n: Notification): string { if (n.type === 'follow') return '' if (n.repo) return n.repo.fullName || n.repo.name if (n.post) { const preview = n.post.content?.trim() ?? '' return preview.length > 40 ? `${preview.slice(0, 40)}…` : preview } return '' } function notificationHref(n: Notification): string { if (n.type === 'follow' && n.actor) return `/${n.actor.username}` if (n.post) return `/posts/${n.post.id}` if (n.actor) return `/${n.actor.username}` return '/' } const KNOWN_TYPES: ReadonlySet = new Set([ 'like', 'comment', 'follow', 'mention', 'repo_star', ]) function isKnownType(type: string): type is NotificationType { return KNOWN_TYPES.has(type as NotificationType) } /** * Adapts a notification pushed over SSE into the richer shape this dropdown * renders. The realtime payload is intentionally thin, so unknown/missing * fields fall back to `null` and the optimistic row is later reconciled by the * polling refetch. */ function fromRealtime(n: RealtimeNotification): Notification { return { id: n.id, type: isKnownType(n.type) ? n.type : 'mention', read: false, createdAt: n.createdAt ?? new Date().toISOString(), actor: n.actorUsername ? { id: n.actorId ?? '', username: n.actorUsername, avatar: null } : null, post: n.postId ? { id: n.postId, content: '', mediaUrl: null } : null, repo: null, } } // ─── Fetch / mutate ─────────────────────────────────────────────────────────── async function fetchNotifications(): Promise { const response = await api.get('/v1/notifications', { params: { limit: 10 }, }) return response.data } async function markAllRead(): Promise { await api.post('/v1/notifications/read-all') } // ─── Component ──────────────────────────────────────────────────────────────── export default function NotificationBell() { const [open, setOpen] = useState(false) const containerRef = useRef(null) const router = useRouter() const queryClient = useQueryClient() // SSE-pushed notifications prepended optimistically, newest first. These are // reconciled away (deduped by id) once the polling refetch returns them. const [optimistic, setOptimistic] = useState([]) // Drives a one-shot pulse animation on the bell when a live event lands. const [pulse, setPulse] = useState(false) const { lastNotification } = useRealtime() const { data, isLoading } = useQuery({ queryKey: ['notifications-bell'], queryFn: fetchNotifications, refetchInterval: 30_000, // polling fallback when SSE is unavailable }) const markAllMutation = useMutation({ mutationFn: markAllRead, onSuccess: () => { setOptimistic([]) queryClient.invalidateQueries({ queryKey: ['notifications-bell'] }) }, }) // Resolve nested shape — API may return { data: { notifications, unreadCount } } // or flat { notifications, unreadCount } depending on envelope. const payload = (data as unknown as { notifications?: Notification[]; unreadCount?: number }) ?? {} const nestedPayload = (data as unknown as NotificationsResponse)?.data ?? {} const fetched: Notification[] = nestedPayload.notifications ?? payload.notifications ?? [] const fetchedUnread: number = nestedPayload.unreadCount ?? payload.unreadCount ?? 0 // Merge optimistic SSE notifications ahead of fetched ones, dropping any that // the server has since returned (the fetched copy is authoritative). const fetchedIds = new Set(fetched.map((n) => n.id)) const pendingOptimistic = optimistic.filter((n) => !fetchedIds.has(n.id)) const notifications: Notification[] = [...pendingOptimistic, ...fetched] const unreadCount: number = fetchedUnread + pendingOptimistic.length // On each new SSE notification: prepend optimistically + fire the pulse. useEffect(() => { if (!lastNotification) return const mapped = fromRealtime(lastNotification) setOptimistic((prev) => { if (prev.some((n) => n.id === mapped.id)) return prev return [mapped, ...prev].slice(0, 10) }) setPulse(true) const timer = setTimeout(() => setPulse(false), 600) return () => clearTimeout(timer) }, [lastNotification]) // Close on outside click useEffect(() => { function handleMouseDown(event: MouseEvent) { if (containerRef.current && !containerRef.current.contains(event.target as Node)) { setOpen(false) } } document.addEventListener('mousedown', handleMouseDown) return () => document.removeEventListener('mousedown', handleMouseDown) }, []) function handleNotificationClick(n: Notification) { setOpen(false) router.push(notificationHref(n)) } function handleMarkAllRead() { markAllMutation.mutate() } return (
{/* Subtle pulse keyframes for live notification arrival. */} {/* Bell button */} {/* Dropdown */} {open && (
{/* Header */}
Notifications
{/* List */}
    {isLoading && (
  • Loading…
  • )} {!isLoading && notifications.length === 0 && (
  • No notifications yet
  • )} {notifications.map((n) => { const icon = TYPE_ICON[n.type] ?? '🔔' const action = TYPE_ACTION[n.type] ?? 'interacted with you' const target = notificationTarget(n) const timestamp = relativeTime(n.createdAt) return (
  • ) })}
)}
) }