"use client"; import { useEffect, useState, useRef } from "react"; import { requestNotificationPermission, onForegroundMessage } from "../utils/firebase"; import AuthService from "../services/AuthService"; export default function NotificationHandler() { const [notification, setNotification] = useState(null); const initialized = useRef(false); useEffect(() => { // Wait for hydration to complete const timer = setTimeout(() => { if (initialized.current) return; initialized.current = true; const token = AuthService.getToken(); if (!token) { console.log("[Notifications] Not signed in, skipping"); return; } console.log("[Notifications] Signed in, requesting permission..."); requestNotificationPermission().then((fcmToken) => { if (fcmToken) { console.log("[Notifications] FCM token obtained:", fcmToken.substring(0, 20) + "..."); } }); const unsub = onForegroundMessage((payload) => { const title = payload.notification?.title || payload.data?.title || "Sweet Home"; const body = payload.notification?.body || payload.data?.body || ""; setNotification({ title, body }); setTimeout(() => setNotification(null), 5000); }); // Cleanup on unmount return () => unsub(); }, 1000); // Wait 1s for hydration return () => clearTimeout(timer); }, []); if (!notification) return null; return (
🏠

{notification.title}

{notification.body}

); }