function fetchNotifications() {
    fetch('/notifications/get')
        .then(response => response.json())
        .then(data => {
            let notificationContainer = document.querySelector(".modal-notif .modal-body .list-group");
            let notifIcon = document.querySelector(".nav-notif .dot");
            let acceptAllBtn = document.getElementById('acceptAllBtn');

            notificationContainer.innerHTML = "";

            if (data.length > 0) {
                notifIcon.style.display = "inline-block";

                notifIcon.textContent = data.length;
                notifIcon.classList.add("notif-count");

                data.forEach(notification => {
                    let item = document.createElement("div");
                    item.classList.add("list-group-item", "bg-transparent");
                
                    const messageHtml = `
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <span class="fe fe-inbox fe-24"></span>
                            </div>
                            <div class="col">
                                <small><strong>${notification.message}</strong></small>
                                <div class="my-0 text-muted small">Trámite N° ${notification.process_id}</div>
                                <small class="badge badge-pill badge-light text-muted">${formatTimeAgo(notification.created_at)}</small>
                            </div>
                        </div>
                    `;
                
                    if (USER_ROLE === 'COMUNITY') {
                        item.innerHTML = `<a href="${BASE_HREF}inbox" class="text-reset text-decoration-none">${messageHtml}</a>`;
                    } else {
                        item.innerHTML = messageHtml;
                    }
                
                    notificationContainer.appendChild(item);
                });

                acceptAllBtn.disabled = false;
            } else {
                notifIcon.style.display = "none";

                notifIcon.textContent = "";

                notificationContainer.innerHTML = "<p class='text-center text-muted'>No hay notificaciones</p>";
                acceptAllBtn.disabled = true;
            }
        })
        .catch(error => console.error("Error obteniendo notificaciones:", error));
}

function formatTimeAgo(timestamp) {
    let time = new Date(timestamp);
    let now = new Date();
    let diff = Math.floor((now - time) / 1000);

    if (diff < 60) return "hace unos segundos";
    if (diff < 3600) return `hace ${Math.floor(diff / 60)} min`;
    if (diff < 86400) return `hace ${Math.floor(diff / 3600)} h`;
    return `hace ${Math.floor(diff / 86400)} días`;
}


function acceptAllProcesses() {
    fetch('/processes/accept-all', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.querySelector(".modal-notif .modal-body .list-group").innerHTML = "<p class='text-center text-muted'>No hay notificaciones</p>";
            document.querySelector(".nav-notif .dot").style.display = "none";

            alert("Todos los trámites han sido aceptados correctamente.");

            fetchNotifications();
        } else {
            alert("Hubo un error al aceptar los trámites.");
        }
    })
    .catch(error => console.error("Error al aceptar los trámites:", error));
}


function clearNotifications() {
    fetch('/notifications/clear', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.querySelector(".modal-notif .modal-body .list-group").innerHTML = "<p class='text-center text-muted'>No hay notificaciones</p>";
            document.querySelector(".nav-notif .dot").style.display = "none";

            alert("Notificaciones limpiadas correctamente.");

            fetchNotifications();
        } else {
            alert("Hubo un error al limpiar las notificaciones.");
        }
    })
    .catch(error => console.error("Error al limpiar las notificaciones:", error));
}


document.addEventListener("DOMContentLoaded", function () {
    fetchNotifications();
    setInterval(fetchNotifications, 30000);

    let acceptAllBtn = document.getElementById("acceptAllBtn");
    if (acceptAllBtn) {
        acceptAllBtn.addEventListener("click", acceptAllProcesses);
    }

    let clearNotificationsBtn = document.getElementById("clearNotificationsBtn");
    if (clearNotificationsBtn) {
        clearNotificationsBtn.addEventListener("click", clearNotifications);
    }
});
