var userObj = JSON.parse(localStorage.getItem('userObj'));
let currentAttendId = null;
let currentAttendBtn = null;



let lastNotificationId = null;



let notificationAudio = new Audio("assets/bells.mp3");
notificationAudio.preload = "auto";
notificationAudio.volume = 1;


document.addEventListener("click", function unlockAudio() {
    notificationAudio.play().then(() => {
        notificationAudio.pause();
        notificationAudio.currentTime = 0;
        console.log("🔓 Audio unlocked");
    }).catch(()=>{});
    
    document.removeEventListener("click", unlockAudio);
});


function startNotificationPolling() {
    // setInterval(() => {
    //     checkForNewNotifications();
    // }, 20000); // every 5 sec
}


function checkForNewNotifications() {
    $.ajax({
        url: serverURL + "notifications?page=0&size=1&sort=createdAt,desc",
        headers: { Authorization: "Bearer " + userObj.accessToken },
        success: function (res) {
            if (!res.content.length) return;

            const latest = res.content[0].id;

            if (lastNotificationId !== null && latest !== lastNotificationId) {
                loadNotificationData();
                playNotificationSound();
            }

            lastNotificationId = latest;
        }
    });
}



startNotificationPolling();




loadNotificationData();
function loadNotificationData() {

    var url = serverURL + "notifications?page=0&size=10&sort=createdAt,desc";

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        success: function (response) {

            let notifications = response.content || [];

            // 🔴 Count unread
            let unreadCount = notifications.filter(n => !n.read).length;
            $(".header-badge").text(unreadCount);

            // 📩 Build dropdown list
            let html = `
                <li class="not-head">
                    You have <b class="text-primary">${unreadCount}</b> new notifications.
                </li>
            `;

            if (notifications.length === 0) {
                html += `<li class="bell-notification text-center p-2">No notifications</li>`;
            }

           notifications.forEach(function (item) {
            html += `
            <li class="bell-notification ${item.read ? '' : 'unread'}">
                <div class="notification-row">
                    <a href="javascript:;" class="media notification-link" onclick="openNotification(${item.id})">
                        <span class="media-left media-icon">
                            <img  class="img-circle" src="assets/bell.png" alt="User">
                        </span>
                        <div class="media-body">
                            <span class="block">${item.title}</span>
                            <span class="text-muted block-time">
                                ${timeAgo(item.createdAt)}
                            </span>
                        </div>
                    </a>

                    <div class="notification-actions">
                        ${!item.read ? `
                            <button class="icon-btn read-btn" title="Mark as read"
                                onclick="markAsRead(${item.id}, this)">
                                <i class="fas fa-check"></i>
                            </button>` : ''}

                        <button class="icon-btn attend-btn" title="Attend"
                            onclick="openAttendModal(${item.id}, this)">
                            <i class="fas fa-user-check"></i>
                        </button>
                    </div>
                </div>
            </li>
            `;
        });


            html += `
                <li class="not-footer">
                    <a href="./#app/notiifications">See all notifications.</a>
                </li>
            `;

            $(".notification-menu .dropdown-menu").html(html);
        },
        error: function () {
            $(".notification-menu .dropdown-menu").html(`
                <li class="text-center p-2 text-danger">Failed to load</li>
            `);
        }
    });
}


function playNotificationSound() {
    notificationAudio.currentTime = 0;
    notificationAudio.play().catch(err => {
        console.log("Playback blocked:", err);
    });
}


function openAttendModal(notificationId, btn) {
    currentAttendId = notificationId;
    currentAttendBtn = btn;
    $("#attendComments").val("");
    $("#attendModal").fadeIn(150);
}
function closeAttendModal() {
    $("#attendModal").fadeOut(150);
    currentAttendId = null;
    currentAttendBtn = null;
}




function submitAttend() {

    const comments = $("#attendComments").val().trim();

    if (!comments) {
        alert("Please enter comments before attending.");
        return;
    }

    $.ajax({
        url: serverURL + "notifications/" + currentAttendId + "/attend",
        type: "POST",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        data: JSON.stringify({
            comments: comments
        }),
        success: function () {
            // Update UI
            $(currentAttendBtn).replaceWith(
                `<span class="attended-label">Attended</span>`
            );
            closeAttendModal();
        },
        error: function () {
            alert("Failed to attend notification");
        }
    });
}







function markAsRead(notificationId, btn) {

    $.ajax({
        url: serverURL + "notifications/" + notificationId + "/read",
        type: "POST",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        success: function () {
            const card = $(btn).closest(".notification-card");
            card.removeClass("unread");
            $(btn).remove();
            loadNotificationData();
        },
        error: function () {
            alert("Failed to mark notification as read");
        }
    });
}



function attendNotification(notificationId, btn) {

    $.ajax({
        url: serverURL + "notifications/" + notificationId + "/attend",
        type: "POST",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        success: function () {
            $(btn).replaceWith(`<span class="attended-label">Attended</span>`);
            loadNotificationData();
        },
        error: function () {
            alert("Failed to attend notification");
        }
    });
}








function formatDate(dateStr) {
    const date = new Date(dateStr);
    return date.toLocaleString();
}


function timeAgo(dateString) {
    const seconds = Math.floor((new Date() - new Date(dateString)) / 1000);

    let interval = seconds / 3600;
    if (interval > 1) return Math.floor(interval) + "h ago";

    interval = seconds / 60;
    if (interval > 1) return Math.floor(interval) + "m ago";

    return Math.floor(seconds) + "s ago";
}
function openNotification(id) {
    markAsRead(id);
    window.location.href = "#app/notiifications"; // or modal
}
