/**
 * Firebase Cloud Messaging Service Worker
 * Handles background push notifications
 * 
 * IMPORTANT: Replace the firebaseConfig with your actual Firebase project config
 */

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

// Firebase configuration - REPLACE WITH YOUR CONFIG
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT.appspot.com",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase in service worker
let messaging = null;

try {
  const app = firebase.initializeApp(firebaseConfig);
  messaging = firebase.messaging();
  console.log('Firebase initialized in service worker');
} catch (error) {
  console.error('Error initializing Firebase in service worker:', error);
}

// Handle background messages
if (messaging) {
  messaging.onBackgroundMessage((payload) => {
    console.log('Background Message received:', payload);

    const notificationTitle = payload.notification?.title || 'New Notification';
    const notificationOptions = {
      body: payload.notification?.body || '',
      icon: '/logo.png',
      badge: '/logo.png',
      data: payload.data || {},
      tag: payload.data?.id || 'default',
      requireInteraction: false,
      vibrate: [200, 100, 200],
    };

    // Show notification
    self.registration.showNotification(notificationTitle, notificationOptions);
  });
}

// Handle notification click
self.addEventListener('notificationclick', (event) => {
  console.log('Notification clicked:', event);
  
  event.notification.close();

  // Get navigation URL from notification data
  const urlToOpen = event.notification.data?.web_navigation_url || event.notification.data?.url || '/dashboard';

  // Open or focus the client window
  event.waitUntil(
    clients.matchAll({
      type: 'window',
      includeUncontrolled: true,
    }).then((clientList) => {
      // Check if there's already a window open
      for (let i = 0; i < clientList.length; i++) {
        const client = clientList[i];
        if (client.url.includes(urlToOpen) && 'focus' in client) {
          return client.focus();
        }
      }
      // If not, open a new window
      if (clients.openWindow) {
        return clients.openWindow(urlToOpen);
      }
    })
  );
});

console.log('Firebase Messaging Service Worker loaded');

