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

const firebaseConfig = {
  apiKey: "AIzaSyB_wcxBXiOr2rkrBdL0VHw2KRREpq50rMI",
  authDomain: "easyerp-6d03d.firebaseapp.com",
  projectId: "easyerp-6d03d",
  storageBucket: "easyerp-6d03d.firebasestorage.app",
  messagingSenderId: "616839436850",
  appId: "1:616839436850:web:9296bd07e10c1eb352fa2b"
};

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  const notificationTitle = payload.notification?.title || 'إشعار جديد';
  const notificationOptions = {
    body: payload.notification?.body || 'يوجد إشعار جديد',
    icon: 'icon-192.png',
    data: payload.data
  };
  self.registration.showNotification(notificationTitle, notificationOptions);
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  let clickAction = '/easyerp/index.html';
  if (event.notification.data && event.notification.data.link) {
    clickAction = event.notification.data.link;
  }
  event.waitUntil(
    clients.matchAll({ type: 'window' }).then(windowClients => {
      for (let client of windowClients) {
        if (client.url.includes('/easyerp/') && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(clickAction);
      }
    })
  );
});

