'use client'; import React, { useState, useEffect } from 'react'; import { useAuth } from '../contexts/AuthContext'; import { isPushNotificationSupported, getNotificationPermission, subscribeToPush, unsubscribeFromPush, isPushSubscribed, sendTestPushNotification, } from '../lib/push-notifications'; export default function PushNotificationToggle() { const { user, token } = useAuth(); const [isSupported, setIsSupported] = useState(false); const [isSubscribed, setIsSubscribed] = useState(false); const [permission, setPermission] = useState('default'); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { checkPushSupport(); checkSubscriptionStatus(); }, []); const checkPushSupport = () => { const supported = isPushNotificationSupported(); setIsSupported(supported); if (supported) { setPermission(getNotificationPermission()); } }; const checkSubscriptionStatus = async () => { try { const subscribed = await isPushSubscribed(); setIsSubscribed(subscribed); } catch (error) { console.error('Error checking subscription status:', error); } }; const handleToggle = async () => { if (!token) { setError('You must be logged in to enable notifications'); return; } setIsLoading(true); setError(null); try { if (isSubscribed) { // Unsubscribe await unsubscribeFromPush(token); setIsSubscribed(false); setPermission(getNotificationPermission()); // Update user preferences to disable push await savePreference(token, false); } else { // Subscribe await subscribeToPush(token); setIsSubscribed(true); setPermission('granted'); // Update user preferences to enable push await savePreference(token, true); } } catch (err: any) { console.error('Error toggling push notifications:', err); setError(err.message || 'Failed to update notification settings'); } finally { setIsLoading(false); } }; const savePreference = async (authToken: string, enabled: boolean) => { try { const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://maternal-api.noru1.ro'; const response = await fetch(`${apiUrl}/api/v1/preferences/notifications`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, }, body: JSON.stringify({ pushEnabled: enabled, }), }); if (!response.ok) { throw new Error('Failed to save preference'); } console.log('[Push] Preference saved:', enabled); } catch (error) { console.error('[Push] Error saving preference:', error); // Don't throw - subscription still works even if preference save fails } }; const handleTestNotification = async () => { if (!token) { setError('You must be logged in to send test notifications'); return; } setIsLoading(true); setError(null); try { await sendTestPushNotification(token); // Show success message (you could use a toast/snackbar here) alert('Test notification sent! Check your notifications.'); } catch (err: any) { console.error('Error sending test notification:', err); setError(err.message || 'Failed to send test notification'); } finally { setIsLoading(false); } }; if (!isSupported) { return (

Push notifications are not supported in your browser. Please use a modern browser like Chrome, Firefox, Edge, or Safari.

); } return (

Push Notifications

Get notified about feeding times, diaper changes, and more

{error && (

{error}

)} {permission === 'denied' && (

Notifications are blocked. Please enable them in your browser settings and reload the page.

)} {isSubscribed && (

✓ You're subscribed to push notifications

)} {isLoading && (
Processing...
)}
); }