"use client"; import { useEffect, useRef, useState, useCallback } from "react"; import { useSession } from "next-auth/react"; import { notificationService } from "@/services/notification.service"; interface ToastNotification { id: number; title: string; body: string; } let toastId = 0; export function NotificationProvider() { const { status } = useSession(); const initialized = useRef(false); const [toasts, setToasts] = useState([]); const addToast = useCallback( (payload: { title: string; body: string }) => { const id = ++toastId; setToasts((prev) => [...prev, { id, title: payload.title, body: payload.body }]); setTimeout(() => { setToasts((prev) => prev.filter((t) => t.id !== id)); }, 5000); }, [] ); const removeToast = useCallback((id: number) => { setToasts((prev) => prev.filter((t) => t.id !== id)); }, []); useEffect(() => { if (status !== "authenticated" || initialized.current) return; initialized.current = true; let unsubscribe: (() => void) | null = null; const init = async () => { const registered = await notificationService.requestPermissionAndRegister(); if (registered) { unsubscribe = notificationService.setupForegroundHandler(addToast); } }; init(); return () => { if (unsubscribe) unsubscribe(); }; }, [status, addToast]); // Reset on logout useEffect(() => { if (status === "unauthenticated") { initialized.current = false; } }, [status]); if (toasts.length === 0) return null; return (
{toasts.map((toast) => (
removeToast(toast.id)} style={{ background: "#fff", borderRadius: 10, padding: "12px 16px", boxShadow: "0 4px 12px rgba(0,0,0,0.15)", borderLeft: "4px solid #e58625", cursor: "pointer", animation: "slideIn 0.3s ease-out", }} >
{toast.title}
{toast.body}
))}
); }