self.addEventListener("push", (event) => {
  let data = {}

  try {
    data = event.data ? event.data.json() : {}
  } catch (error) {
    data = {
      title: "FEDEO",
      message: event.data?.text() || "Neue Benachrichtigung",
      payload: {},
    }
  }

  const payload = data.payload || {}
  const title = data.title || "FEDEO"
  const options = {
    body: data.message || "",
    icon: payload.icon || "/favicon.ico",
    badge: payload.badge || "/favicon.ico",
    data: {
      notificationId: data.id,
      link: payload.link || "/",
    },
  }

  event.waitUntil(self.registration.showNotification(title, options))
})

self.addEventListener("notificationclick", (event) => {
  event.notification.close()

  const targetUrl = new URL(event.notification.data?.link || "/", self.location.origin).href

  event.waitUntil((async () => {
    const windows = await self.clients.matchAll({
      type: "window",
      includeUncontrolled: true,
    })

    for (const client of windows) {
      if ("focus" in client) {
        await client.focus()
        if ("navigate" in client) await client.navigate(targetUrl)
        return
      }
    }

    await self.clients.openWindow(targetUrl)
  })())
})
