// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
// Replace 10.13.2 with latest version of the Firebase JS SDK.
// eslint-disable-next-line no-undef
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
// eslint-disable-next-line no-undef
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');

// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
// eslint-disable-next-line no-undef
firebase.initializeApp({
  apiKey: ' AIzaSyACBg8oyAR2DWMu4xW85gx5thpRgxnvI_0',
  authDomain: 'nearle-gear.firebaseapp.com',
  databaseURL: 'https://nearle-gear-default-rtdb.firebaseio.com',
  projectId: 'nearle-gear',
  storageBucket: 'nearle-gear.appspot.com',
  messagingSenderId: '140444764229',
  appId: '1:140444764229:web:e5ed6259a92d0532283b2c',
  measurementId: 'G-3YQ4DNMXE5'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
// eslint-disable-next-line no-undef
const messaging = firebase.messaging();

// why here

// When your web app is in the background or closed, the browser shuts down your React app’s JS context (like your firebase.js, App.js, etc.). At this point:
// Only a Service Worker (like firebase-messaging-sw.js) is allowed to run.
// It listens for messages even when your app is not active.
// Firebase automatically routes background messages to that service worker.
// So you must use onBackgroundMessage() in the service worker.
// 🔁 Think of the service worker like a "headless background listener" running outside your React app.

// ========================== || temporarily add for mobile correct notification ========================== ||
self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const targetUrl = '/'; // TODO: route where you want to land the user

  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for (const client of clientList) {
        // Reuse an existing tab
        if ('focus' in client) return client.focus();
      }
      if (clients.openWindow) return clients.openWindow(targetUrl);
    })
  );
});
// ========================== || temporarily add for mobile correct notification ========================== ||

messaging.onBackgroundMessage((payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: payload.notification.image
  };

  // eslint-disable-next-line no-restricted-globals
  self.registration.showNotification(notificationTitle, notificationOptions);
});
