// CannaManage Service Worker — PWA + Push Notifications
const CACHE_NAME = "cannamanage-v1"

// Cache static assets on install
self.addEventListener("install", (event) => {
  self.skipWaiting()
})

self.addEventListener("activate", (event) => {
  event.waitUntil(clients.claim())
})

// Handle incoming push messages
self.addEventListener("push", (event) => {
  const data = event.data ? event.data.json() : {}
  const options = {
    body: data.body || "Neue Benachrichtigung",
    icon: data.icon || "/icons/icon-192.png",
    badge: "/icons/icon-192.png",
    tag: data.type || "default",
    data: { url: data.url || "/portal/notifications", ...data.data },
    actions: data.actions || [{ action: "open", title: "Anzeigen" }],
    vibrate: [100, 50, 100],
  }
  event.waitUntil(
    self.registration.showNotification(data.title || "CannaManage", options)
  )
})

// Handle notification click
self.addEventListener("notificationclick", (event) => {
  event.notification.close()
  const url = event.notification.data?.url || "/portal/notifications"
  event.waitUntil(
    clients.matchAll({ type: "window" }).then((windowClients) => {
      for (const client of windowClients) {
        if (client.url.includes(url) && "focus" in client) return client.focus()
      }
      return clients.openWindow(url)
    })
  )
})
