"use client" import { useEffect, useRef } from "react" import { formatDistanceToNow } from "date-fns" import { toast } from "sonner" import { useNotificationStore, type StoredNotification, } from "@/lib/stores/notification-store" export function NotificationPanel({ onClose }: { onClose: () => void }) { const panelReference = useRef(null) const notifications = useNotificationStore((state) => state.notifications) const dismissNotification = useNotificationStore( (state) => state.dismissNotification ) const clearAllNotifications = useNotificationStore( (state) => state.clearAllNotifications ) const markAllAsViewed = useNotificationStore( (state) => state.markAllAsViewed ) useEffect(() => { markAllAsViewed() }, [markAllAsViewed]) useEffect(() => { function handleClickOutside(event: MouseEvent) { const target = event.target as Node if ( panelReference.current && !panelReference.current.contains(target) && !(target instanceof HTMLElement && target.closest("[data-notification-toggle]")) ) { onClose() } } document.addEventListener("mousedown", handleClickOutside) return () => document.removeEventListener("mousedown", handleClickOutside) }, [onClose]) function handleNotificationClick(notification: StoredNotification) { if (notification.actionUrl) { navigator.clipboard.writeText(notification.actionUrl) toast("link copied to clipboard") } } return (
notifications {notifications.length > 0 && ( )}
{notifications.length === 0 ? (

no notifications

) : ( notifications.map((notification: StoredNotification) => (
handleNotificationClick(notification) : undefined } >

{notification.message}

{notification.actionUrl && (

tap to copy link

)}

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

)) )}
) } export function useUnviewedNotificationCount(): number { const notifications = useNotificationStore((state) => state.notifications) const lastViewedAt = useNotificationStore((state) => state.lastViewedAt) if (!lastViewedAt) return notifications.length return notifications.filter( (notification) => notification.timestamp > lastViewedAt ).length }