diff --git a/app/components/NotificationHandler.js b/app/components/NotificationHandler.js index 0dd3068..a426374 100644 --- a/app/components/NotificationHandler.js +++ b/app/components/NotificationHandler.js @@ -6,60 +6,102 @@ import AuthService from "../services/AuthService"; export default function NotificationHandler() { const [notification, setNotification] = useState(null); + const [showPrompt, setShowPrompt] = useState(false); 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; - } + if (!token) return; - console.log("[Notifications] Signed in, requesting permission..."); - requestNotificationPermission().then((fcmToken) => { - if (fcmToken) { - console.log("[Notifications] FCM token obtained:", fcmToken.substring(0, 20) + "..."); + // Check current permission status + if ("Notification" in window) { + if (Notification.permission === "default") { + // Not yet asked — show prompt button + setShowPrompt(true); + } else if (Notification.permission === "granted") { + // Already allowed — get token silently + initFCM(); } - }); - - 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 + // "denied" — do nothing, user must change in browser settings + } + }, 1000); return () => clearTimeout(timer); }, []); - if (!notification) return null; + async function initFCM() { + const fcmToken = await requestNotificationPermission(); + if (fcmToken) { + console.log("[Notifications] FCM token obtained:", fcmToken.substring(0, 20) + "..."); + } + 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); + }); + } + + async function handleEnableNotifications() { + setShowPrompt(false); + await initFCM(); + } return ( -
تفعيل الإشعارات
+اسمح بالإشعارات للبقاء على اطلاع بحجوزاتك وعروضنا.
+{notification.title}
-{notification.body}
+ )} + + {/* Foreground notification toast */} + {notification && ( +{notification.title}
+{notification.body}
+