<script>
    import { deleteNotificacion } from '$/services/notificaciones'
    import { storeMessages } from '$/stores/global'
    let messages = []
    let hoy = (new Date()).toISOString().substring(0,10);

    storeMessages.subscribe(val => messages = val)

    async function onDelete(id) {
        try {
            await deleteNotificacion(id)
            storeMessages.update(val => val.filter(el => el.id !== id))
        } catch(error) {
            globalThis.toast.error(error.message || error)
        }
    }


    function formatTime(time) {
        if (!time) return '--:--';
        const myDate = new Date(time);

        if (myDate.toISOString() < hoy) {
            return myDate.toLocaleString()
        } else {
            return myDate.toLocaleTimeString()
        }
    }
</script>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel" style="visibility: inherit;">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title text-info" id="offcanvasRightLabel"><i class="bi bi-bell-fill text-info"></i> Alertas</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body">
        {#each messages as m, index}
        <div class={"alert d-flex mb-3" + (index === 0 ? ' alert-primary shadow' : ' alert-info shadow-sm')}>
            <i class="bi bi-info-circle fs-1 me-2"></i>
            <div>
                <strong>{formatTime(m.fecha_hora)}</strong>
                <div>{m.mensaje}</div>
            </div>
            <button type="button" class="btn-close ms-auto" aria-label="Close" on:click|preventDefault={() => onDelete(m.id)}></button>
        </div>
        {/each}
    </div>
</div>

<style>
    .shadow { box-shadow: 0 .5rem 1rem var(--bs-primary)!important; }
    .shadow-sm { box-shadow: 0 .125rem .25rem var(--bs-info)!important; }
</style>