// sw-register.js — Core service worker registration
// Registers /service-worker.js at root scope with version-based cache busting.
// Replaces the registration previously in websocket_tool/static/scripts.js.

(function () {
    if (!('serviceWorker' in navigator)) {
        console.warn('[SW] Service workers not supported in this browser.');
        return;
    }

    function registerSW(version) {
        var versionSuffix = version ? '?v=' + version : '';
        var swPath = '/service-worker.js' + versionSuffix;

        navigator.serviceWorker.register(swPath, { scope: '/' })
            .then(function (registration) {
                console.log('[SW] Registered:', registration.scope);
            })
            .catch(function (error) {
                console.error('[SW] Registration failed:', error);
            });
    }

    // Listen for controller changes (new SW activated)
    navigator.serviceWorker.addEventListener('controllerchange', function () {
        console.log('[SW] Controller changed — new service worker active');
    });

    // Fetch version hash from sw_info.json for cache busting, then register
    fetch('/sw_info.json')
        .then(function (res) { return res.json(); })
        .then(function (data) {
            console.log('[SW] Version:', data.version);
            registerSW(data.version);
        })
        .catch(function (err) {
            console.warn('[SW] Failed to fetch version, registering without cache bust:', err);
            registerSW(null);
        });
})();
