document.addEventListener('DOMContentLoaded', function() {
    const bell = document.getElementById('notificationBell');
    const dropdown = document.getElementById('notificationDropdown');
    const count = document.getElementById('notificationCount');
    const list = document.getElementById('notificationList');
    let isOpen = false;
    let previousCount = 0;
    
    function loadNotifications() {
        fetch('/allura/php/get_user_notifications.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateNotificationCount(data.unread_count);
                    displayNotifications(data.notifications);
                }
            })
            .catch(error => console.error('Error loading notifications:', error));
    }
    
    function updateNotificationCount(unreadCount) {
        if (unreadCount > previousCount && previousCount > 0) {
            bell.classList.add('notification-pulse');
            setTimeout(() => bell.classList.remove('notification-pulse'), 1000);
            
            if (typeof showInfo === 'function') {
                showInfo('You have a new notification!', 3000);
            }
        }
        
        previousCount = unreadCount;
        
        if (unreadCount > 0) {
            count.textContent = unreadCount;
            count.style.display = 'inline';
            bell.classList.add('has-notifications');
        } else {
            count.style.display = 'none';
            bell.classList.remove('has-notifications');
        }
    }
    
    const notificationIcons = {
        'success': '<i class="fas fa-check-circle" style="color: #28a745;"></i>',
        'info': '<i class="fas fa-info-circle" style="color: #17a2b8;"></i>',
        'warning': '<i class="fas fa-exclamation-triangle" style="color: #ffc107;"></i>',
        'error': '<i class="fas fa-times-circle" style="color: #dc3545;"></i>'
    };
    
    function displayNotifications(notifications) {
        if (notifications.length === 0) {
            list.innerHTML = '<div class="no-notifications">No notifications</div>';
            return;
        }
        
        list.innerHTML = notifications.map(notification => {
            const icon = notificationIcons[notification.type] || notificationIcons['info'];
            const readClass = notification.is_read ? 'read' : 'unread';
            
            return `
                <div class="notification-item ${readClass}" data-id="${notification.id}">
                    <div style="display: flex; align-items: start; gap: 10px;">
                        <div style="margin-top: 3px;">${icon}</div>
                        <div style="flex: 1;">
                            <div class="notification-title">${notification.title}</div>
                            <div class="notification-message">${notification.message}</div>
                            <div class="notification-time">${formatTime(notification.created_at)}</div>
                        </div>
                    </div>
                </div>
            `;
        }).join('');
        
        document.querySelectorAll('.notification-item.unread').forEach(item => {
            item.addEventListener('click', function() {
                markAsRead(this.dataset.id);
                this.classList.remove('unread');
                this.classList.add('read');
            });
        });
    }
    
    function markAsRead(notificationId) {
        fetch('/allura/php/get_user_notifications.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({mark_read: true, notification_id: notificationId})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadNotifications();
            }
        });
    }
    
    function formatTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diffMs = now - date;
        const diffMinutes = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);
        
        if (diffMinutes < 1) return 'Just now';
        if (diffMinutes < 60) return `${diffMinutes}m ago`;
        if (diffHours < 24) return `${diffHours}h ago`;
        if (diffDays === 1) return 'Yesterday';
        if (diffDays < 7) return `${diffDays}d ago`;
        return date.toLocaleDateString();
    }
    
    bell.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        isOpen = !isOpen;
        dropdown.style.display = isOpen ? 'block' : 'none';
        if (isOpen) loadNotifications();
    });
    
    document.addEventListener('click', function(e) {
        if (!bell.contains(e.target) && !dropdown.contains(e.target)) {
            dropdown.style.display = 'none';
            isOpen = false;
        }
    });
    
    loadNotifications();
    setInterval(loadNotifications, 5000);
});
