<script setup lang="ts">
/**
 * Offline detection banner.
 *
 * Uses navigator.onLine and online/offline events to detect
 * network connectivity changes. Shows a warning banner when
 * offline and a brief success message when back online.
 */

const isOnline = ref(true)
const showReconnected = ref(false)

let reconnectedTimer: ReturnType<typeof setTimeout> | null = null

function handleOffline() {
  isOnline.value = false
  showReconnected.value = false
  if (reconnectedTimer) {
    clearTimeout(reconnectedTimer)
    reconnectedTimer = null
  }
}

function handleOnline() {
  isOnline.value = true
  showReconnected.value = true

  // Show "reconnected" message briefly then hide
  reconnectedTimer = setTimeout(() => {
    showReconnected.value = false
    reconnectedTimer = null
  }, 3000)
}

onMounted(() => {
  isOnline.value = navigator.onLine
  window.addEventListener('offline', handleOffline)
  window.addEventListener('online', handleOnline)
})

onUnmounted(() => {
  window.removeEventListener('offline', handleOffline)
  window.removeEventListener('online', handleOnline)
  if (reconnectedTimer) {
    clearTimeout(reconnectedTimer)
  }
})
</script>

<template>
  <Transition name="slide-down">
    <div
      v-if="!isOnline"
      class="bg-warning-100 dark:bg-warning-900/50 border-b border-warning-300 dark:border-warning-700 px-4 py-2 text-center"
      role="alert"
    >
      <div class="flex items-center justify-center gap-2 text-sm text-warning-800 dark:text-warning-200">
        <UIcon name="i-lucide-wifi-off" class="text-lg flex-shrink-0" />
        <span>Vous etes hors ligne. Certaines fonctionnalites sont indisponibles.</span>
      </div>
    </div>
  </Transition>

  <Transition name="slide-down">
    <div
      v-if="showReconnected && isOnline"
      class="bg-success-100 dark:bg-success-900/50 border-b border-success-300 dark:border-success-700 px-4 py-2 text-center"
      role="status"
    >
      <div class="flex items-center justify-center gap-2 text-sm text-success-800 dark:text-success-200">
        <UIcon name="i-lucide-wifi" class="text-lg flex-shrink-0" />
        <span>Connexion retablie</span>
      </div>
    </div>
  </Transition>
</template>

<style scoped>
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease;
}

.slide-down-enter-from,
.slide-down-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}

.slide-down-enter-to,
.slide-down-leave-from {
  transform: translateY(0);
  opacity: 1;
}
</style>
