// Firebase Cloud Messaging service worker.
// This file must live at /firebase-messaging-sw.js (the root of the web app).
//
// The main thread sends the Firebase config via postMessage after registering
// this service worker — that way we don't have to hardcode credentials here.
//
// Configuration steps:
//   1. Set VITE_FIREBASE_* env vars in .env (see .env.example)
//   2. Admin panel → Notifications → Channels → Add FCM channel with your
//      Firebase service-account JSON
//   3. Deploy this file to / (it is already in public/ which Vite copies as-is)

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

let initialised = false

self.addEventListener('message', (event) => {
  if (event.data?.type === 'FIREBASE_CONFIG' && !initialised) {
    initialised = true
    firebase.initializeApp(event.data.config)

    const messaging = firebase.messaging()

    // Background message handler — fires when the app tab is not focused.
    // The browser will show the notification automatically using this data.
    messaging.onBackgroundMessage((payload) => {
      const notification = payload.notification ?? {}
      const title = notification.title ?? 'SLE Sales'
      const options = {
        body: notification.body ?? '',
        icon: notification.icon ?? '/favicon.svg',
        badge: '/favicon.svg',
        data: payload.data ?? {},
        // Re-focus an existing tab if one is open instead of opening a new one
        tag: payload.data?.tag ?? 'sle-notification',
      }
      self.registration.showNotification(title, options)
    })
  }
})

// Notification click — open or focus the relevant page
self.addEventListener('notificationclick', (event) => {
  event.notification.close()
  const navPath = event.notification.data?.nav_path ?? '/'
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
      // Re-focus existing tab if found
      for (const client of windowClients) {
        if ('focus' in client) return client.focus()
      }
      // Otherwise open a new tab
      if (clients.openWindow) return clients.openWindow(navPath)
    }),
  )
})
