'use client' import { useCallback, useEffect, useState } from 'react' import Link from 'next/link' import { Bell } from 'lucide-react' import { Drawer } from '@/components/ui/drawer' import { cx } from '@/components/ui/cx' type Notification = { id: string title: string | null link: string | null sent_at: string read_at: string | null } const POLL_MS = 60_000 function isToday(iso: string): boolean { return new Date(iso).toDateString() === new Date().toDateString() } export function NotificationBell() { const [notifications, setNotifications] = useState([]) const [unread, setUnread] = useState(0) const [open, setOpen] = useState(false) const [tab, setTab] = useState<'all' | 'unread'>('all') const load = useCallback(() => { fetch('/api/notifications') .then(r => (r.ok ? r.json() : Promise.reject())) .then((data: { notifications: Notification[]; unread: number }) => { setNotifications(data.notifications) setUnread(data.unread) }) .catch(() => {}) }, []) useEffect(() => { load() const id = setInterval(load, POLL_MS) return () => clearInterval(id) }, [load]) const markAllRead = () => { fetch('/api/notifications', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ all: true }), }) .then(() => { setUnread(0) setNotifications(prev => prev.map(n => ({ ...n, read_at: n.read_at ?? new Date().toISOString() }))) }) .catch(() => {}) } const shown = tab === 'unread' ? notifications.filter(n => !n.read_at) : notifications const groups: Array<{ label: string; items: Notification[] }> = [ { label: 'Today', items: shown.filter(n => isToday(n.sent_at)) }, { label: 'Earlier', items: shown.filter(n => !isToday(n.sent_at)) }, ].filter(g => g.items.length > 0) return ( <> setOpen(false)} title="Notifications" actions={ unread > 0 ? ( ) : undefined } >
{(['all', 'unread'] as const).map(t => ( ))}
{groups.length === 0 ? (

No notifications

) : ( groups.map(g => (

{g.label}

    {g.items.map(n => { const body = ( <>

    {n.title ?? 'Notification'}

    {new Date(n.sent_at).toLocaleString()}

    ) return (
  • {n.link ? ( setOpen(false)}> {body} ) : (
    {body}
    )}
  • ) })}
)) )}
) }