"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import { BellIcon, CheckIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Switch } from "@/components/ui/switch"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { cn } from "@/lib/utils"; import { notificationLabel } from "@/lib/notifications"; import { NOTIFICATION_EVENT } from "@/hooks/useGameTick"; import { markAllNotificationsRead, markNotificationsRead, } from "@/app/(frontend)/notifications/actions"; interface NotificationItem { id: number; type?: string | null; title: string; message?: string | null; link?: string | null; read: boolean; createdAt: string; /** * Whether this notification belongs to the current user. When false the * current user (staff with read-all) is viewing someone else's notification; * it can be shown and opened but its read-state must never be changed. */ isMine?: boolean; /** Display name of the user this notification is actually meant for. Only set when `!isMine`. */ ownerName?: string | null; } function timeAgo(iso: string): string { const diff = Date.now() - new Date(iso).getTime(); const minutes = Math.floor(diff / 60000); if (minutes < 1) return "just now"; 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`; } const POLL_MS = 60_000; /** * Per-browser memory of whether a staff user wants the bell to show everyone's * notifications ("all") or only their own ("mine"). Non-staff are always * scoped to their own server-side, so the value is irrelevant to them. */ const SCOPE_KEY = "ptf:notifications:scope"; type Scope = "all" | "mine"; function readStoredScope(): Scope { if (typeof window === "undefined") return "all"; try { return window.localStorage.getItem(SCOPE_KEY) === "mine" ? "mine" : "all"; } catch { return "all"; } } export function NotificationsBell() { const router = useRouter(); const [notifications, setNotifications] = useState([]); const [open, setOpen] = useState(false); const [loading, setLoading] = useState(true); const [error, setError] = useState(false); const [actionError, setActionError] = useState(null); const [marking, setMarking] = useState(false); const [scope, setScope] = useState(readStoredScope); const [canViewOthers, setCanViewOthers] = useState(false); const intervalRef = useRef | null>(null); const unreadCount = notifications.filter((n) => !n.read).length; const fetchNotifications = useCallback(async () => { try { const res = await fetch(`/api/notifications/inbox?limit=12&sort=-createdAt&scope=${scope}`, { cache: "no-store", }); if (!res.ok) throw new Error("Failed to fetch"); const data = (await res.json()) as { notifications?: NotificationItem[]; canViewOthers?: boolean; }; setNotifications(data.notifications ?? []); setCanViewOthers(Boolean(data.canViewOthers)); setError(false); } catch { setError(true); } finally { setLoading(false); } }, [scope]); useEffect(() => { void fetchNotifications(); intervalRef.current = setInterval(() => void fetchNotifications(), POLL_MS); const onNotification = () => void fetchNotifications(); window.addEventListener(NOTIFICATION_EVENT, onNotification); return () => { if (intervalRef.current) clearInterval(intervalRef.current); window.removeEventListener(NOTIFICATION_EVENT, onNotification); }; }, [fetchNotifications]); // Read-state is personal to the recipient. Never let marking one change // another user's read flag — staff are viewing it as an oversight, not as // that user, so flipping it would hide the notification from them. async function handleMarkOne(item: NotificationItem) { if (item.read || marking || item.isMine === false) return; setMarking(true); setActionError(null); try { const result = await markNotificationsRead([item.id]); if (result.success) { setNotifications((prev) => prev.map((n) => (n.id === item.id ? { ...n, read: true } : n)), ); } else { setActionError(result.error ?? "Failed to update notifications."); } } catch (err) { setActionError(err instanceof Error ? err.message : "Failed to update notifications."); } finally { setMarking(false); } } async function handleItemClick(item: NotificationItem) { // Own notifications are marked read on open; others' are only opened, never // marked, so the real owner still sees them as unread. if (!item.read && item.isMine !== false) await handleMarkOne(item); if (item.link) { router.push(item.link); setOpen(false); } } async function handleMarkAll() { if (unreadCount === 0 || marking) return; setMarking(true); setActionError(null); try { const result = await markAllNotificationsRead(); if (result.success) { // Only own rows are guaranteed to have been flipped, so only optimistic- // update those. Staff viewing others' rows must not see them flip to read. setNotifications((prev) => prev.map((n) => (n.isMine === false ? n : { ...n, read: true })), ); } else { setActionError(result.error ?? "Failed to update notifications."); } } catch (err) { setActionError(err instanceof Error ? err.message : "Failed to update notifications."); } finally { setMarking(false); } } function handleScopeToggle(next: boolean) { const value: Scope = next ? "all" : "mine"; setScope(value); try { window.localStorage.setItem(SCOPE_KEY, value); } catch { // storage unavailable (private mode): the toggle still works this session } } return (
Notifications {unreadCount > 0 && ( )}
{canViewOthers && (
)}
{loading ? (

Loading...

) : error ? (

Could not load notifications.

) : notifications.length === 0 ? (

No notifications yet.

) : ( <> {actionError && (

{actionError}

)} {notifications.map((item) => { const isUnread = !item.read; const isForeign = item.isMine === false; return ( void handleItemClick(item)} > {!isForeign && isUnread && ( )} {item.title} {!isForeign && item.read && ( )} {timeAgo(item.createdAt)} {isForeign && item.ownerName && ( meant for {item.ownerName} )} {item.message && ( {item.message} )} {notificationLabel(item.type)} ); })} )}
View all
); }