<script setup lang="ts">
const needRefresh = ref(false)
let updateServiceWorker: (() => Promise<void>) | undefined
const onNeedRefresh = () => (needRefresh.value = true)

onBeforeMount(async () => {
  const { registerSW } = await import('virtual:pwa-register')
  updateServiceWorker = registerSW({
    immediate: true,
    onNeedRefresh
  })
})
</script>

<template>
  <div
    class="pwa-toast p-5 fixed right-30px bottom-30px rounded-12px z-5000 shadow-xl font-500 max-w-500px text-5"
    role="alertdialog"
    aria-labelledby="pwa-message"
    v-if="needRefresh"
  >
    <div class="message mb-5">
      <h2 class="text-center m-b-2">有新的内容更新啦！</h2>
      <p>点击 按钮 获取最新版本，享受更好的授课体验。</p>
    </div>
    <div class="flex gap-5 grid-justify-end">
      <button
        class="py-10px px-20px rounded-2 font-600 text-4 border-0 cursor-pointer outline-0"
        @click="updateServiceWorker?.()"
      >
        获取新内容
      </button>
    </div>
  </div>
</template>

<style scoped>
.pwa-toast {
  background-image: -webkit-linear-gradient(315deg, #e940c9 25%, #647eff);
  box-shadow: 0px 0px 60px var(--color-gray-6);
  h2 {
    background: -webkit-linear-gradient(315deg, #faff00 25%, #0efaa5);
    background-clip: text;
    -webkit-text-fill-color: transparent;
  }
  button {
    background-image: linear-gradient(to right, #0efaa5, #faff00);
    color: var(--color-black);
    &:hover {
      background-image: linear-gradient(to top, #0efaa5, #faff00);
    }
  }
}
</style>
