import { usePage } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { usePushNotification } from '@/hooks/use-push-notification';

export function NotificationPermissionPrompt() {
    const { vapidPublicKey } = usePage().props as { vapidPublicKey?: string };
    const hasRequested = useRef(false);

    const { isSupported, requestPermission, subscribe } =
        usePushNotification();

    useEffect(() => {
        if (!isSupported || hasRequested.current) {
            return;
        }

        if (Notification.permission !== 'default') {
            return;
        }

        hasRequested.current = true;

        void requestPermission().then(async (result) => {
            if (result === 'granted' && vapidPublicKey) {
                await subscribe(vapidPublicKey);
            }
        });
    }, [isSupported, requestPermission, subscribe, vapidPublicKey]);

    return null;
}
