// Service Worker for Omnia PWA Push Notifications
// MINIMAL SERVICE WORKER - ONLY FOR PUSH NOTIFICATIONS
// NO CACHING - Does not interfere with website cache/session

// Install event - activate immediately
self.addEventListener('install', function(event) {
  console.log('[ServiceWorker] Installing (notifications only)...');
  event.waitUntil(self.skipWaiting());
});

// Activate event - clean up any old caches and take control immediately
self.addEventListener('activate', function(event) {
  console.log('[ServiceWorker] Activating (notifications only)...');
  event.waitUntil(
    caches.keys()
      .then(function(cacheNames) {
        // Delete ALL caches - we don't use caching anymore
        return Promise.all(
          cacheNames.map(function(cacheName) {
            console.log('[ServiceWorker] Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          })
        );
      })
      .then(function() {
        console.log('[ServiceWorker] All caches cleared, claiming clients');
        return self.clients.claim();
      })
  );
});

// Push event - receive and display notification
self.addEventListener('push', function(event) {
  console.log('[ServiceWorker] Push received');

  let data = {
    title: 'New Notification',
    body: 'You have a new update',
    icon: '/icons/icon-192.png',
    badge: '/icons/icon-72.png',
    url: '/',
    sound: null,
    vibrate: [200, 100, 200],
    tag: 'default',
    requireInteraction: false
  };

  try {
    if (event.data) {
      data = event.data.json();
      console.log('[ServiceWorker] Push data received:', data);
      console.log('[ServiceWorker] Sound from data:', data.sound);
      console.log('[ServiceWorker] Data object:', data.data);
    }
  } catch (e) {
    console.error('[ServiceWorker] Error parsing push data:', e);
  }

  const options = {
    body: data.body,
    icon: data.icon || '/icons/icon-192.png',
    badge: data.badge || '/icons/icon-72.png',
    data: {
      url: data.url || '/',
      dateOfArrival: Date.now(),
      primaryKey: data.primaryKey || 1,
      orderId: data.orderId || null
    },
    vibrate: data.vibrate || [200, 100, 200],
    tag: data.orderId ? 'order-' + data.orderId : 'notification-' + Date.now(),
    requireInteraction: false,  // Auto-dismiss after timeout
    actions: data.actions || [
      {
        action: 'view',
        title: 'View Order',
        icon: '/icons/icon-72.png'
      },
      {
        action: 'close',
        title: 'Dismiss',
        icon: '/icons/icon-72.png'
      }
    ]
  };

  // Get sound URL (might be in data.sound or data.data.sound)
  const soundUrl = data.sound || (data.data && data.data.sound) || null;
  console.log('[ServiceWorker] Sound URL to play:', soundUrl);

  // Android custom sound support
  if (soundUrl) {
    options.sound = soundUrl;
  }

  event.waitUntil(
    self.registration.showNotification(data.title, options)
      .then(() => {
        console.log('[ServiceWorker] Notification shown');

        // Send message to all clients to play sound
        if (soundUrl) {
          console.log('[ServiceWorker] Sending PLAY_SOUND message with:', soundUrl);
          self.clients.matchAll({ type: 'window', includeUncontrolled: true })
            .then(clients => {
              console.log('[ServiceWorker] Found', clients.length, 'clients to notify');
              clients.forEach(client => {
                client.postMessage({
                  type: 'PLAY_SOUND',
                  sound: soundUrl
                });
              });
            });
        } else {
          console.warn('[ServiceWorker] No sound URL found in notification data');
        }
      })
  );
});

// Notification click event - handle user interaction
self.addEventListener('notificationclick', function(event) {
  console.log('[ServiceWorker] Notification click received');

  event.notification.close();

  const urlToOpen = event.notification.data && event.notification.data.url
    ? event.notification.data.url
    : '/';

  // Handle action buttons
  if (event.action === 'close') {
    return; // Just close, do nothing
  }

  event.waitUntil(
    clients.matchAll({
      type: 'window',
      includeUncontrolled: true
    }).then(function(windowClients) {
      // Check if there's already a window open
      for (let i = 0; i < windowClients.length; i++) {
        const client = windowClients[i];
        // If we find a window with the same URL, focus it
        if (client.url === urlToOpen && 'focus' in client) {
          return client.focus();
        }
      }
      // If no window is open, open a new one
      if (clients.openWindow) {
        return clients.openWindow(urlToOpen);
      }
    })
  );
});

// NO FETCH EVENT - Service worker does NOT intercept any network requests
// This allows the website to use its normal cache/session without interference

console.log('[ServiceWorker] Loaded successfully - Notifications only, no caching!');
