import { useEffect, useState } from 'react';

export function useServiceWorker() {
    const [isReady, setIsReady] = useState(false);
    const [hasUpdate, setHasUpdate] = useState(false);
    const [registration, setRegistration] = useState<ServiceWorkerRegistration | null>(null);

    useEffect(() => {
        if (!('serviceWorker' in navigator)) {
            console.log('[SW] Service Worker not supported');
            return;
        }

        const registerSW = async () => {
            try {
                const reg = await navigator.serviceWorker.register('/sw.js');
                setRegistration(reg);
                setIsReady(true);
                console.log('[SW] Service Worker registered');

                // Check for updates
                reg.addEventListener('updatefound', () => {
                    const newWorker = reg.installing;
                    if (!newWorker) return;

                    newWorker.addEventListener('statechange', () => {
                        if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                            // New version available
                            setHasUpdate(true);
                            console.log('[SW] New version available');
                        }
                    });
                });
            } catch (error) {
                console.error('[SW] Registration failed:', error);
            }
        };

        registerSW();

        // Check for updates periodically
        const interval = setInterval(() => {
            registration?.update();
        }, 60 * 60 * 1000); // Every hour

        return () => clearInterval(interval);
    }, []);

    const update = () => {
        if (registration?.waiting) {
            registration.waiting.postMessage({ type: 'SKIP_WAITING' });
            window.location.reload();
        }
    };

    return { isReady, hasUpdate, update };
}

// Register SW on app load
export function registerServiceWorker() {
    if ('serviceWorker' in navigator && import.meta.env.PROD) {
        window.addEventListener('load', () => {
            navigator.serviceWorker.register('/sw.js')
                .then((reg) => console.log('[SW] Registered:', reg.scope))
                .catch((err) => console.error('[SW] Registration failed:', err));
        });
    }
}
