importScripts('https://www.gstatic.com/firebasejs/9.22.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.22.2/firebase-messaging-compat.js');

firebase.initializeApp({
    apiKey: "AIzaSyB2QJpIOWR_aB4fozvSaitP9gb3O279K08",
  authDomain: "pwa-project-3f798.firebaseapp.com",
  projectId: "pwa-project-3f798",
  storageBucket: "pwa-project-3f798.firebasestorage.app",
  messagingSenderId: "152947952076",
  appId: "1:152947952076:web:f90fd151ec06558fddf569",
  measurementId: "G-4S7FWEW2BC"
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage(payload => {
  const title = payload.notification.title;
  const options = {
    body: payload.notification.body,
    icon: payload.notification.icon || '/icon.png',
    data: { url: payload.notification.click_action || '/' }
  };
  self.registration.showNotification(title, options);
});

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