<script setup lang="ts">
import { RouterView } from 'vue-router'
import { registerServiceWorker } from '@/registerServiceWorker'

const router = useRouter()
const debugEnabled = ref(import.meta.env.DEV)
const debugItems = ref<string[]>([])
const debug = (...data: unknown[]) => {
  if (debugEnabled.value) {
    debugItems.value.push(JSON.stringify(data))
  }
}

provide('debug', debug)

registerServiceWorker()
  .then(() => {
    console.log('Service Worker успешно зарегистрирован')
    navigator.serviceWorker.addEventListener('message', (event) => {
      if (event.data.type === 'debug') {
        if ('debug' in event.data && typeof event.data.debug === 'object') {
          debug(event.data.debug)
        }
      } else if (event.data.type === 'notificationClick' && !event.data.matchUrl) {
        const url = new URL(event.data.url, location.origin)
        console.debug('go to', `${url.pathname}${url.search}${url.hash}`)
        router.push(`${url.pathname}${url.search}${url.hash}`)
      }
    })
  })
  .catch(console.error)
</script>

<template>
  <div class="debug gap-2 py-2 flex flex-col" v-if="debugEnabled">
    <div class="px-2 text-nowrap" v-for="(value, key) in debugItems" :key>
      <Button
        icon="pi pi-trash"
        class="p-button-danger p-button-text"
        size="small"
        @click="debugItems.splice(key, 1)"
      />
      <span class="font-mono text-xs">{{ value }}</span>
    </div>
  </div>
  <RouterView />
</template>

<style scoped>
.debug {
  position: fixed;
  top: 0;
  left: 0;
  max-width: 100vw;
  max-height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  overflow-y: scroll;
  color: white;
}
</style>
