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

// 2. INITIALIZE FIREBASE IN SW
firebase.initializeApp({
  apiKey: "AIzaSyDGlBocq5uuiaU8lDi1M1lHRV20xJSjW8g",
    projectId: "sna-crm-software",
    messagingSenderId: "1004217416886",
    appId: "1:1004217416886:web:29790211f3156c07c0fa17"
});

const messaging = firebase.messaging();

// 3. BACKGROUND NOTIFICATION HANDLER
messaging.onBackgroundMessage((payload) => {
  console.log('[sw.js] Received background message ', payload);
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: '/sna/assets/img/favicon.png' 
  };

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

// 4. YOUR EXISTING CACHE LOGIC
const CACHE_NAME = 'sna-erp-v1';
const urlsToCache = [
  '/sna/',
  '/sna/index.php',
  '/sna/assets/css/style.css',
  '/sna/login'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(urlsToCache);
    })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    fetch(event.request).catch(() => {
      return caches.match(event.request);
    })
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== CACHE_NAME) {
            return caches.delete(cache);
          }
        })
      );
    })
  );
});