// notify.js – Modern notification system

let currentAttendId = null;
let currentAttendBtn = null;
let lastNotificationId = null;

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

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

// Start polling for new notifications every 5 seconds
function startNotificationPolling() {
    setInterval(() => {
        checkForNewNotifications();
    }, 5000);
}

// Check for new notifications (compare latest ID)
function checkForNewNotifications() {
        var url = serverURL + "tickets?page=0&size=10000000&sort=createdAt,desc";

    $.ajax({
        // url: serverURL + "notifications?page=0&size=1&alarm=true&sort=createdAt,desc",
                url: serverURL + "tickets?page=0&size=10000000&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();

// Load all notifications and update dropdown
function loadNotificationData() {
    var url = serverURL + "tickets?page=0&size=10000000&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 || [];
            let unreadCount = notifications.filter(n => !n.read).length;

            // Update badge with count and pulse effect
            // $(".header-badge").text(unreadCount).toggleClass('has-notifications', unreadCount > 0);

            // Build dropdown HTML
            let html = `
                <li class="not-head">
                    <span>Notifications</span>
                    <span class="badge-count">${unreadCount} new</span>
                </li>
                <li class="divider"></li>
            `;

            if (notifications.length === 0) {
                html += `<li class="empty-state"><i class="fas fa-bell-slash"></i> No notifications</li>`;
            } else {
                // Show only the 5 latest for performance
                notifications.slice(0, 5).forEach(item => {
                    const unreadClass = item.read ? '' : 'unread';
                    html += `
                        <li class="notification-item ${unreadClass}" data-id="${item.id}">
                            <div class="notification-content" onclick="openNotification(${item.id})">
                                <div class="notification-icon">
                                    <i class="fas ${getIconForType(item.type)}"></i>
                                </div>
                                <div class="notification-details">
                                    <div class="notification-title">${escapeHtml(item.title)}</div>
                                    <div class="notification-time">${timeAgo(item.createdAt)}</div>
                                </div>
                            </div>
                            <div class="notification-actions">
                                ${!item.read ? `
                                    <button class="action-btn read-btn" title="Mark as read" onclick="event.stopPropagation(); markAsRead(${item.id}, this)">
                                        <i class="fas fa-check"></i>
                                    </button>
                                ` : ''}
                                <button class="action-btn attend-btn" title="Attend" onclick="event.stopPropagation(); openAttendModal(${item.id}, this)">
                                    <i class="fas fa-user-check"></i>
                                </button>
                            </div>
                        </li>
                    `;
                });
            }

            html += `
                <li class="divider"></li>
                <li class="not-footer">
                    <a href="#app/mytickets">View all notifications <i class="fas fa-arrow-right"></i></a>
                </li>
            `;

            $(".notification-menu .dropdown-menu").html(html);
        },
        error: function () {
            $(".notification-menu .dropdown-menu").html(`
                <li class="error-state"><i class="fas fa-exclamation-triangle"></i> Failed to load</li>
            `);
        }
    });
}

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

// Helper: icon based on notification type
function getIconForType(type) {
    const icons = {
        'ALARM': 'fa-exclamation-circle',
        'INFO': 'fa-info-circle',
        'WARNING': 'fa-exclamation-triangle',
        'SUCCESS': 'fa-check-circle',
        'DEFAULT': 'fa-bell'
    };
    return icons[type] || icons.DEFAULT;
}

// Helper: escape HTML to prevent XSS
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Helper: relative time formatting
function timeAgo(dateString) {
    const seconds = Math.floor((new Date() - new Date(dateString)) / 1000);
    if (seconds < 60) return Math.floor(seconds) + "s ago";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return minutes + "m ago";
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return hours + "h ago";
    const days = Math.floor(hours / 24);
    return days + "d ago";
}

// Mark a notification as read
function markAsRead(notificationId, btn) {
    $.ajax({
        url: serverURL + "notifications/" + notificationId + "/read",
        type: "POST",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        success: function () {
            // Remove the read button
            $(btn).closest('.notification-actions').find('.read-btn').remove();
            // Remove unread class from parent
            $(btn).closest('.notification-item').removeClass('unread');
            // Update badge count
            loadNotificationData();
        },
        error: function () {
            alert("Failed to mark notification as read");
        }
    });
}

// Open attend modal
function openAttendModal(notificationId, btn) {
    currentAttendId = notificationId;
    currentAttendBtn = btn;
    $("#attendComments").val("");
    $("#attendModal").fadeIn(150);
}

function closeAttendModal() {
    $("#attendModal").fadeOut(150);
    currentAttendId = null;
    currentAttendBtn = null;
}

// Submit attend with comments
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 () {
            // Replace attend button with "Attended" label
            $(currentAttendBtn).replaceWith(
                `<span class="attended-label">Attended</span>`
            );
            closeAttendModal();
        },
        error: function () {
            alert("Failed to attend notification");
        }
    });
}

// Open notification (mark as read and navigate)
function openNotification(id) {
    markAsRead(id);
    window.location.href = "#app/notifications";
}

// Initial load
loadNotificationData();