document.addEventListener('DOMContentLoaded', function() {
    // 标记通知为已读
    const markAsRead = (notificationId) => {
        fetch(`/announcement/notification/${notificationId}/mark-read`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新UI，如移除未读标记
                const notificationCard = document.querySelector(`.notification-card[data-id="${notificationId}"]`);
                if (notificationCard) {
                    notificationCard.classList.remove('unread');
                    const unreadBadge = notificationCard.querySelector('.unread-badge');
                    if (unreadBadge) {
                        unreadBadge.remove();
                    }
                }

                // 更新通知计数
                updateNotificationCount();
            }
        })
        .catch(error => console.error('Error:', error));
    };

    // 自动标记为已读
    const notificationCards = document.querySelectorAll('.notification-card.unread');
    notificationCards.forEach(card => {
        const notificationId = card.dataset.id;
        if (notificationId) {
            // 当用户查看通知列表时自动标记为已读
            // 这可以是可选的功能，也可能需要用户点击后才标记
            // markAsRead(notificationId);
        }
    });

    // 更新通知计数
    function updateNotificationCount() {
        // 获取当前未读通知数
        fetch('/announcement/notifications/count')
            .then(response => response.json())
            .then(data => {
                const badge = document.querySelector('.notifications .badge');
                if (data.count > 0) {
                    if (badge) {
                        badge.textContent = data.count;
                    } else {
                        const newBadge = document.createElement('span');
                        newBadge.className = 'badge';
                        newBadge.textContent = data.count;
                        document.querySelector('.notifications').appendChild(newBadge);
                    }
                } else {
                    if (badge) {
                        badge.remove();
                    }
                }
            })
            .catch(error => console.error('Error:', error));
    }
});
