'use client';

import { useEffect } from 'react';

export default function PWARegistration() {
    useEffect(() => {
        if ('serviceWorker' in navigator) {
            // Register immediately - the page is already loaded when this component mounts
            navigator.serviceWorker
                .register('/sw.js')
                .then((registration) => {
                    console.log('[PWA] SW registered:', registration.scope);

                    // Check for updates
                    registration.onupdatefound = () => {
                        const installingWorker = registration.installing;
                        if (installingWorker == null) return;
                        installingWorker.onstatechange = () => {
                            if (installingWorker.state === 'installed') {
                                if (navigator.serviceWorker.controller) {
                                    console.log('[PWA] New content available; please refresh.');
                                } else {
                                    console.log('[PWA] Content cached for offline use.');
                                }
                            }
                        };
                    };
                })
                .catch((registrationError) => {
                    console.error('[PWA] SW registration failed:', registrationError);
                });
        }
    }, []);

    return null;
}
