<!-- src/components/Toast.vue -->
<template>
  <div
    v-if="show"
    class="mt-20 toast "
    :class="{ 'toast-error': currentMessage?.type === 'error', 'toast-success': currentMessage?.type === 'success' }"
  >
    <div
      class="alert"
      :class="{ 'alert-error': currentMessage?.type === 'error', 'alert-success': currentMessage?.type === 'success' }"
    >
      <span>{{ currentMessage?.message }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted, watch, onMounted } from 'vue';

const props = defineProps({
  queue: {
    type: Array,
    required: true,
  },
});

const show = ref(false);
const currentMessage = ref(null);
let timer = null;

const processQueue = () => {
  if (props.queue.length === 0) {
      show.value = false;
      currentMessage.value = null;
    return;
  }
    
  currentMessage.value = props.queue.shift();
  show.value = true;
  
  timer = setTimeout(() => {
      processQueue();
  }, currentMessage.value.duration || 3000);
  
};

watch(() => props.queue, () => {
    if(!show.value) {
        processQueue()
    }
}, { deep: true });
    
onUnmounted(() => {
  if (timer) {
    clearTimeout(timer);
  }
});


</script>