<template>
  <div class="toast-list">
    <TransitionGroup name="slide-fade" appear>
      <ToastItem
        :class="{ single: toastList.length === 1 }"
        v-for="(toast, index) in toastList"
        :key="toast.id"
        :id="toast.id"
        :body="toast.body"
        :type="toast.type"
        @close="removeToast(index)"
      />
    </TransitionGroup>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch } from "vue";
import ToastItem from "./Toast.vue";
import { Toast } from "@/models";

export default defineComponent({
  components: { ToastItem },
  props: {
    toast: {
      type: Object as PropType<Toast>,
    },
  },
  setup(props, { emit }) {
    const toastList = ref<Toast[]>([]);

    const removeToast = (index: number): void => {
      toastList.value.splice(index, 1);
    };

    watch(
      (): Toast => props.toast,
      (newVal: Toast): void => {
        toastList.value.unshift(newVal);
        if (toastList.value.length > 4) {
          toastList.value.pop();
        }
      }
    );

    return {
      toastList,
      removeToast,
    };
  },
});
</script>

<style scoped lang="scss">
.toast-list {
  margin-left: 16px;
  position: fixed;
  top: 60px;
  right: 16px;
  z-index: 105;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: transform 0.5s ease, opacity 0.5s ease;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(25%);
  opacity: 0;
}
</style>
