<script setup>
import { useRegisterSW } from 'virtual:pwa-register/vue'
import { watch, onMounted } from 'vue'

// Zmieniamy na autoUpdate w configu, więc tutaj tylko nasłuchujemy i ewentualnie wymuszamy
const {
  needRefresh,
  updateServiceWorker,
} = useRegisterSW({
  immediate: true,
  onRegistered(r) {
    // Sprawdzaj aktualizacje co godzinę
    r && setInterval(() => {
      r.update()
    }, 60 * 60 * 1000)
  }
})

const updateSW = async () => {
  if ('serviceWorker' in navigator) {
    try {
      const registration = await navigator.serviceWorker.ready
      console.log('Checking for SW update...')
      await registration.update()
    } catch (e) {
      console.error('Failed to update SW:', e)
    }
  }
}

onMounted(() => {
  // Check on load
  updateSW()

  // Check when app becomes visible again (e.g. switching tabs/apps)
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
      updateSW()
    }
  })
})
</script>

<template>
  <div
    v-if="needRefresh"
    class="pwa-toast"
    role="alert"
  >
    <div class="message">
      New content available, click on reload button to update.
    </div>
    <button @click="updateServiceWorker()">
      Reload
    </button>
  </div>
</template>

<style scoped>
.pwa-toast {
  position: fixed;
  right: 0;
  bottom: 0;
  margin: 16px;
  padding: 12px;
  border: 1px solid var(--glass-border);
  border-radius: 4px;
  z-index: 10000;
  text-align: left;
  box-shadow: var(--glass-shadow);
  background-color: var(--glass-bg);
  backdrop-filter: blur(10px);
  color: var(--text-color);
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.pwa-toast button {
  border: 1px solid var(--glass-border);
  outline: none;
  margin-right: 5px;
  border-radius: 2px;
  padding: 3px 10px;
  cursor: pointer;
  background: var(--button-bg);
  color: var(--text-color);
  transition: all 0.2s;
}

.pwa-toast button:hover {
  background: var(--button-hover-bg);
}
</style>
