/* eslint-disable no-undef */
// Firebase Cloud Messaging Service Worker
// Handles background push notifications when the app is not focused

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

// Firebase config (public values - safe to expose)
firebase.initializeApp({
  apiKey: 'AIzaSyAZZt56_bDMhY_dQb0R9-yUPpDgXP4sDLs',
  authDomain: 'real-estate-2d71e.firebaseapp.com',
  projectId: 'real-estate-2d71e',
  storageBucket: 'real-estate-2d71e.firebasestorage.app',
  messagingSenderId: '703616926518',
  appId: '1:703616926518:web:9d1291a2410b18c7fca997',
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  const notificationTitle = payload.notification?.title || 'New Notification';
  const notificationOptions = {
    body: payload.notification?.body || '',
    icon: '/assets/icons/notification-bell-icon.svg',
    badge: '/assets/icons/notification-bell-icon.svg',
    data: payload.data || {},
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

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

  const link = event.notification.data?.link || '/';

  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      // Focus existing window if available
      for (const client of clientList) {
        if (client.url.includes(self.location.origin) && 'focus' in client) {
          client.navigate(link);
          return client.focus();
        }
      }
      // Open new window
      return clients.openWindow(link);
    })
  );
});
