<template>
    <div class="notifications">
        <TransitionGroup name="notifications--transition">
            <div
                class="notifications__item"
                :class="'notifications__item--' + notification.type"
                v-for="notification in notifications"
                :key="notification.field + notification.text"
            >
                <div class="notifications__item-name" v-if="notification.field">{{ notification.field }}:</div>
                <div class="notifications__item-text">{{ notification.text }}</div>
                <FontAwesomeIcon class="notifications__item-close" icon="xmark" @click="closeNotification(notification)" />
                <div class="notifications__item-countdown"></div>
            </div>
        </TransitionGroup>
    </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import { notification } from "@/types";

const props = defineProps<{ modelValue: notification[] }>();
const emit = defineEmits(["update:modelValue"]);

const notifications = computed({
    get: () => props.modelValue,
    set: (to) => {
        emit("update:modelValue", to);
    },
});

function setNotificationsTimeout() {
    nextTick(() => {
        notifications.value.forEach((x) => {
            setTimeout(() => {
                closeNotification(x);
            }, 5000);
        });
    });
}

watch(
    () => props.modelValue,
    () => {
        setNotificationsTimeout();
    },
    { deep: true }
);

watch(
    () => notifications.value,
    (to, from) => {
        if (from.length > to.length) emit("update:modelValue", to);
    },
    { deep: true }
);

function closeNotification(notification: notification) {
    notifications.value = notifications.value.filter((x) => x !== notification);
}
</script>

<style lang="scss">
.notifications {
    z-index: 100;

    &--transition {
        &-enter-active {
            transition: 0.18s 0.18s ease;
        }
        &-leave-active {
            transition: 0.18s ease;
        }

        &-enter-from {
            opacity: 0;
            margin-bottom: r(-38);
        }
        &-leave-to {
            opacity: 0;
        }

        &-move {
            transition: all 0.18s ease;
        }
    }

    &__item {
        $__item: &;
        position: relative;
        display: flex;
        align-items: center;
        gap: r(5);
        padding: r(10) r(20);
        margin-top: r(1);
        font-size: r(18);
        color: color("ui-color-on-background");

        &-field {
            flex: 0 0 r(70);
        }

        &-text {
            flex: 1 1;
        }

        &-close {
            height: r(14);
            width: r(20);
            cursor: pointer;
        }

        &--success {
            background: color("success-color");
        }

        &--warning {
            background: color("warning-color");
        }
    }
}
</style>
