// Import Firebase scripts
importScripts(
  "https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js",
);
importScripts(
  "https://www.gstatic.com/firebasejs/9.22.0/firebase-messaging-compat.js",
);

// Firebase configuration (should match your project)
firebase.initializeApp({
  apiKey: "AIzaSyASFXCaLCHNFf8j8hCAFsAZKZWzRp_GfX0",
  authDomain: "ringsideproduction.firebaseapp.com",
  projectId: "ringsideproduction",
  storageBucket: "ringsideproduction.firebasestorage.app",
  messagingSenderId: "131634452982",
  appId: "1:131634452982:web:1155f4e5a61db6fd664fd7",
});

const messaging = firebase.messaging();

// Handle background messages
messaging.onBackgroundMessage((payload) => {
  const title = payload.notification?.title || "New Message";
  const body = payload.notification?.body || "";
  const link = payload.fcmOptions?.link || "/admin/messages";
  const icon =
    payload.notification?.icon ||
    "/public/admin_assets/images/favicon-96x96.png";

  // Customize notification
  const notificationOptions = {
    body: body,
    icon: icon,
    badge: icon,
    tag: payload.notification?.tag || "admin-notification",
    data: {
      url: link,
      click_action: link,
    },
  };

  return self.registration.showNotification(title, notificationOptions);
});

// Handle notification click
self.addEventListener("notificationclick", (event) => {
  event.notification.close();

  const link = event.notification.data?.url || "/admin/messages";

  event.waitUntil(
    clients
      .matchAll({
        type: "window",
        includeUncontrolled: true,
      })
      .then((clientList) => {
        // Check if there's already a window/tab open with the target URL
        for (const client of clientList) {
          if (client.url.includes("/admin") && "focus" in client) {
            return client.focus();
          }
        }

        // If not, open a new window/tab
        if (clients.openWindow) {
          return clients.openWindow(link);
        }
      }),
  );
});
