/**
 * sw-push.js — Service Worker for Nexus POS push notifications
 */

self.addEventListener('push', function(event) {
    var data = { title: 'Nexus POS', body: '', url: '/pos', icon: '/pos/static/icons/icon-192.png' };

    if (event.data) {
        try {
            data = Object.assign(data, event.data.json());
        } catch(e) {
            data.body = event.data.text();
        }
    }

    var options = {
        body: data.body,
        icon: data.icon || '/pos/static/icons/icon-192.png',
        badge: data.badge || '/pos/static/icons/badge-72.png',
        vibrate: [200, 100, 200],
        data: { url: data.url || '/pos' },
        actions: [
            { action: 'open', title: 'Ver' },
            { action: 'dismiss', title: 'Cerrar' }
        ]
    };

    event.waitUntil(
        self.registration.showNotification(data.title, options)
    );
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();

    if (event.action === 'dismiss') return;

    var url = (event.notification.data && event.notification.data.url) || '/pos';

    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {
            // Focus existing window if open
            for (var i = 0; i < clientList.length; i++) {
                var client = clientList[i];
                if (client.url.indexOf('/pos') !== -1 && 'focus' in client) {
                    return client.focus();
                }
            }
            // Open new window
            if (clients.openWindow) {
                return clients.openWindow(url);
            }
        })
    );
});
