Files
SweetHome/app/components/NotificationHandler.js

66 lines
2.2 KiB
JavaScript
Raw Normal View History

"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 (
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 bg-white rounded-xl shadow-2xl border border-gray-200 p-4 z-[9999] animate-slide-up">
<div className="flex items-start gap-3">
<div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center flex-shrink-0">
<span className="text-xl">🏠</span>
</div>
<div className="flex-1 min-w-0">
<p className="font-bold text-gray-900 text-sm">{notification.title}</p>
<p className="text-gray-600 text-sm mt-0.5">{notification.body}</p>
</div>
<button
onClick={() => setNotification(null)}
className="text-gray-400 hover:text-gray-600 flex-shrink-0"
>
</button>
</div>
</div>
);
}