importScripts("workbox-v4.3.1/workbox-sw.js");
importScripts("https://www.gstatic.com/firebasejs/8.1.2/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.1.2/firebase-messaging.js");

firebase.initializeApp({
  apiKey: "AIzaSyCMZzl6TZViOFx3G3Wz7omxL56e_WnMAzQ",
  authDomain: "the-flood-team.firebaseapp.com",
  projectId: "the-flood-team",
  storageBucket: "the-flood-team.appspot.com",
  messagingSenderId: "1065444417180",
  appId: "1:1065444417180:web:cd5fd2a1a6b15cf2f0d759",
  measurementId: "G-8J4NCLDTBN",
});

const messaging = firebase.messaging();

self.addEventListener("message", ({ data }) => {
  if (data?.type === "skipWaiting") {
    self.skipWaiting();
  }
});

self.addEventListener("notificationclick", function (event) {
  if (
    event.action === "open" &&
    event?.notification?.data?.FCM_MSG?.data?.url
  ) {
    event.waitUntil(
      clients
        .matchAll({
          type: "window",
        })
        .then(function (clientList) {
          for (var i = 0; i < clientList.length; i++) {
            var client = clientList[i];
            if (
              client.url == event.notification.data.FCM_MSG.data.url &&
              "focus" in client
            ) {
              return client.focus();
            }
          }
          if (clients.openWindow)
            return clients.openWindow(event.notification.data.FCM_MSG.data.url);
        })
    );
  }

  event.notification.close();
});

self.workbox.precaching.precacheAndRoute([]);
