<!-- Message d'alerte -->
<!-- eslint-disable vue/valid-v-for -->

<template>
  <v-alert
    v-model="show"
    :type="props.alert.type"
    class="position"
    border="start"
    width="400"
    dismissible
    transition="fade-transition"
    @mouseover="onMouseOver"
    @mouseout="onMouseOut"
  >
    <ul v-if="props.alert.messages.length > 1">
      <li v-for="message in props.alert.messages" :key="message">
        {{ $t(message) }}
      </li>
    </ul>
    <span v-else>
      {{ $t(props.alert.messages[0]) }}
    </span>
  </v-alert>
</template>

<script setup lang="ts">
import type { Ref } from 'vue'
import type { Alert } from '~/types/interfaces'
import { usePageStore } from '~/stores/page'

const props = defineProps({
  /**
   * The alert object to display
   */
  alert: {
    type: Object as () => Alert,
    required: true,
  },
  /**
   * The time after which the alert disappears
   */
  timeout: {
    type: Number,
    required: false,
    default: 3000,
  },
})

const show: Ref<boolean> = ref(true)
let timeoutId: ReturnType<typeof setTimeout> | null = null

const pageStore = usePageStore()

/**
 * Retire l'alerte après `time` (en ms)
 * @param time
 */
const clearAlert = (time: number = 4000) => {
  timeoutId = setTimeout(() => {
    show.value = false
    pageStore.removeSlowlyAlert()
  }, time)
}

/**
 * Réinitialise et suspend le délai avant le retrait de l'alerte au survol du curseur
 */
const onMouseOver = () => {
  clearTimeout(timeoutId)
}

/**
 * Relance le timer avant le retrait de l'alerte lorsque le curseur quitte l'alerte
 */
const onMouseOut = () => {
  clearAlert(props.timeout)
}

clearAlert()

onUnmounted(() => {
  pageStore.clearAlertTimeout()
})
</script>

<style scoped></style>
