'use strict';

self.addEventListener('push', function (event) {
    var payload = {
        title: 'PlusCash',
        body: 'You have a new notification.',
        icon: '/logo.png',
        badge: '/logo.png',
        tag: 'pluscash-notification',
        renotify: true,
        data: { url: '/dashboard', event: 'notification' }
    };

    if (event.data) {
        try {
            var incoming = event.data.json();
            if (incoming && typeof incoming === 'object') {
                payload = Object.assign(payload, incoming);
                payload.data = Object.assign({ url: payload.url || '/dashboard' }, incoming.data || {});
            }
        } catch (error) {
            payload.body = event.data.text() || payload.body;
        }
    }

    var options = {
        body: String(payload.body || 'You have a new notification.'),
        icon: payload.icon || '/logo.png',
        badge: payload.badge || '/logo.png',
        tag: payload.tag || 'pluscash-notification',
        renotify: payload.renotify !== false,
        data: payload.data || { url: payload.url || '/dashboard' }
    };

    event.waitUntil(self.registration.showNotification(String(payload.title || 'PlusCash'), options));
});

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

    var requestedUrl = event.notification && event.notification.data
        ? event.notification.data.url
        : '/dashboard';
    var targetUrl;

    try {
        targetUrl = new URL(requestedUrl || '/dashboard', self.location.origin);
        if (targetUrl.origin !== self.location.origin) {
            targetUrl = new URL('/dashboard', self.location.origin);
        }
    } catch (error) {
        targetUrl = new URL('/dashboard', self.location.origin);
    }

    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (windowClients) {
            for (var i = 0; i < windowClients.length; i++) {
                var client = windowClients[i];
                if (new URL(client.url).origin === self.location.origin) {
                    if ('navigate' in client && client.url !== targetUrl.href) {
                        return client.navigate(targetUrl.href).then(function (navigatedClient) {
                            return navigatedClient ? navigatedClient.focus() : client.focus();
                        });
                    }
                    return client.focus();
                }
            }

            if (clients.openWindow) {
                return clients.openWindow(targetUrl.href);
            }
            return null;
        })
    );
});
