<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { RefreshCw, WifiOff } from '@lucide/vue'

import Button from '../components/ui/Button.vue'
import { useAwardsStore } from '../stores/awards'
import './networkErrorView.css'

const route = useRoute()
const router = useRouter()
const store = useAwardsStore()
const retrying = ref(false)
const online = ref(typeof navigator === 'undefined' ? true : navigator.onLine)

const from = computed(() => {
  const queryFrom = route.query.from
  return typeof queryFrom === 'string' && queryFrom.startsWith('/') ? queryFrom : '/'
})

const isServerError = computed(() => store.lastPublicErrorKind === 'server')

const title = computed(() =>
  isServerError.value
    ? 'Die Bühne hat gerade einen kleinen 500-Meltdown'
    : online.value
    ? 'Der Sternenhimmel sucht noch die Verbindung'
    : 'Du bist gerade offline durch die Galaxie unterwegs',
)

const text = computed(() =>
  isServerError.value
    ? 'Der Server hat mit einem internen Fehler geantwortet. Statt einer kaputten Seite bekommst du hier die cineastische Fallback-Ansicht, bis die Bühne wieder steht.'
    : online.value
    ? 'Die Award-Seite antwortet im Moment nicht. Das wirkt wie ein Server- oder Netzwerkproblem zwischen Browser und Backend.'
    : 'Ohne Internet können Landingpage, Voting und Archiv nicht sauber geladen werden. Sobald die Verbindung zurück ist, kannst du direkt neu ansetzen.',
)

const detail = computed(() => store.lastPublicError || 'Bitte prüfe deine Verbindung und versuche es gleich noch einmal.')

function syncOnlineState() {
  online.value = typeof navigator === 'undefined' ? true : navigator.onLine
}

async function retry() {
  retrying.value = true
  syncOnlineState()

  try {
    await store.loadHomeData()
    if (store.apiMode === 'api') {
      await router.replace(from.value)
    }
  } finally {
    retrying.value = false
  }
}

onMounted(() => {
  window.addEventListener('online', syncOnlineState)
  window.addEventListener('offline', syncOnlineState)
})

onBeforeUnmount(() => {
  window.removeEventListener('online', syncOnlineState)
  window.removeEventListener('offline', syncOnlineState)
})
</script>

<template>
  <div class="network-scene">
    <div class="network-scene__nebula network-scene__nebula--violet"></div>
    <div class="network-scene__nebula network-scene__nebula--rose"></div>
    <div class="network-scene__nebula network-scene__nebula--gold"></div>
    <div class="network-scene__stars network-scene__stars--far"></div>
    <div class="network-scene__stars network-scene__stars--near"></div>
    <div class="network-scene__orbital network-scene__orbital--one"></div>
    <div class="network-scene__orbital network-scene__orbital--two"></div>
    <div class="network-scene__comet network-scene__comet--one"></div>
    <div class="network-scene__comet network-scene__comet--two"></div>

    <div class="network-scene__content">
      <div class="network-scene__signal">
        <div class="network-scene__signal-ring network-scene__signal-ring--outer"></div>
        <div class="network-scene__signal-ring network-scene__signal-ring--mid"></div>
        <div class="network-scene__signal-core">
          <WifiOff class="h-10 w-10" />
        </div>
      </div>

      <div class="network-scene__copy">
        <p class="network-scene__eyebrow">{{ isServerError ? 'Serverfehler 500' : 'Verbindungsproblem' }}</p>
        <h1 class="network-scene__title">{{ title }}</h1>
        <p class="network-scene__text">{{ text }}</p>
        <p class="network-scene__detail">{{ detail }}</p>
      </div>

      <div class="network-scene__actions">
        <Button :disabled="retrying" @click="retry">
          <RefreshCw class="h-4 w-4" :class="{ 'animate-spin': retrying }" />
          {{ retrying ? 'Versucht erneut ...' : 'Erneut versuchen' }}
        </Button>
        <button class="network-scene__ghost" @click="router.replace('/')">Zur Landingpage</button>
      </div>
    </div>
  </div>
</template>
