/* Firebase Cloud Messaging service worker (web push).
 *
 * The app registers this worker with the Firebase web config passed as URL
 * query params (?apiKey=...&projectId=...&messagingSenderId=...&appId=...),
 * because a service worker cannot read the page's runtime state. The config
 * itself is NOT secret — it ships in every Firebase web app.
 *
 * Handles background push (when the tab is not focused): shows the OS
 * notification and focuses/opens the app on click.
 */
/* eslint-disable no-undef */
importScripts('https://www.gstatic.com/firebasejs/10.12.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.12.2/firebase-messaging-compat.js');

const params = new URL(self.location).searchParams;
const firebaseConfig = {
  apiKey: params.get('apiKey') || '',
  authDomain: params.get('authDomain') || '',
  projectId: params.get('projectId') || '',
  messagingSenderId: params.get('messagingSenderId') || '',
  appId: params.get('appId') || '',
};

if (firebaseConfig.projectId) {
  firebase.initializeApp(firebaseConfig);
  const messaging = firebase.messaging();

  messaging.onBackgroundMessage((payload) => {
    const title = (payload.notification && payload.notification.title) || 'Notification';
    const options = {
      body: (payload.notification && payload.notification.body) || '',
      icon: (payload.notification && payload.notification.icon) || '/brand/icon-192.png',
      data: payload.data || {},
    };
    self.registration.showNotification(title, options);
  });
}

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