// service-worker-base.js — FastPluggy core service worker skeleton
// Plugins extend this by registering handlers into self.swHandlers.

const SW_VERSION = (() => {
    const url = new URL(self.location);
    return url.searchParams.get("v") || "unknown";
})();

// --- Plugin handler dispatch map ---
// Plugins register message handlers by type:
//   self.swHandlers['MY_TYPE'] = function(event) { ... }
// The base message listener dispatches to the matching handler.
self.swHandlers = {};

// --- Lifecycle events ---

self.addEventListener('install', event => {
    console.log(`[SW base v${SW_VERSION}] Installed`);
    self.skipWaiting();
});

self.addEventListener('activate', event => {
    console.log(`[SW base v${SW_VERSION}] Activated`);
    event.waitUntil(self.clients.claim());
});

// --- Message dispatcher ---
// Delegates to plugin-registered handlers in self.swHandlers by e.data.type.

self.addEventListener('message', event => {
    const type = event.data && event.data.type;
    if (!type) return;

    const handler = self.swHandlers[type];
    if (handler) {
        handler(event);
    } else {
        console.warn(`[SW base] Unhandled message type: ${type}`);
    }
});

// --- Push notifications (minimal, works without any plugin) ---
// Plugins can override with richer behavior:
//   self.swPushHandler = function(event) { ... }
//   self.swNotificationClickHandler = function(event) { ... }

self.swPushHandler = null;
self.swNotificationClickHandler = null;

self.addEventListener('push', event => {
    if (self.swPushHandler) return self.swPushHandler(event);
    if (!event.data) return;
    let data;
    try {
        data = event.data.json();
    } catch (e) {
        data = { title: 'Notification', message: event.data.text() };
    }
    const options = {
        body: data.message || '',
        icon: '/static/favicon.svg',
        badge: '/static/favicon.svg',
        data: { url: data.url || '/' },
        tag: data.tag || 'fp-notification',
        renotify: true,
    };
    event.waitUntil(
        self.registration.showNotification(data.title || 'FastPluggy', options)
    );
});

// --- Notification click handler ---

self.addEventListener('notificationclick', event => {
    if (self.swNotificationClickHandler) return self.swNotificationClickHandler(event);
    event.notification.close();
    const url = event.notification.data?.url || '/';
    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(clientList => {
            for (const client of clientList) {
                if (client.url.includes(url) && 'focus' in client) {
                    return client.focus();
                }
            }
            if (clients.openWindow) {
                return clients.openWindow(url);
            }
        })
    );
});

// --- Utility: broadcast to all clients ---

self.notifyClients = function(message) {
    self.clients.matchAll().then(cls => {
        cls.forEach(c => c.postMessage(message));
    });
};
