@php
@endphp

<div class="notifications" x-data="alertHandler()" style="" @alert.window="add($event.detail)">
    <template x-for="alert of alerts" :key="alert.id">
        <div 
            x-show="visible.includes(alert)" 
            class="alert" 
            :id="alert.id"
            :data-theme="alert.type" 
            x-transition:enter="animation-fade-in" 
            x-transition:leave="animation-fade-out"
            style="opacity: 0;"
        >
            <x-bs-alert.dismiss 
                @click="remove(alert.id)"
            />
            <x-bs-alert.icon
                theme="info"
                x-show="alert.type === 'info'"
            />
            <x-bs-alert.icon
                theme="error"
                x-show="alert.type === 'error'"
            />
            <x-bs-alert.icon
                theme="warning"
                x-show="alert.type === 'warning'"
            />
            <x-bs-alert.icon
                theme="success"
                x-show="alert.type === 'success'"
            />
            <x-bs-alert.content>
                <h3 x-show="alert.title" class="font-medium text-sm" x-text="alert.title"></h3>
                <p x-show="alert.message" class="text-sm" x-text="alert.message"></p>
            </x-bs-alert.content>
        </div>
    </template>
</div>

<script>
    function alertHandler() {
        return {
            alerts: [],
            visible: [],
            add(alert) {
                alert.id = Date.now();
                this.alerts.push(alert);
                this.fire(alert.id);
                
                setTimeout(() => {
                    const alertElement = document.getElementById(alert.id);
                    alertElement.style.opacity = 1;
                })
            },
            fire(id) {
                this.visible.push(this.alerts.find(alert => alert.id == id));
                const timeShown = 4000 * this.visible.length;
                
                setTimeout(() => {
                    this.remove(id)
                }, timeShown)
            },
            remove(id) {
                const alert = this.visible.find(alert => alert.id == id);
                const index = this.visible.indexOf(alert);
                this.visible.splice(index, 1);
            },
        }
    }
</script>