document.addEventListener('DOMContentLoaded', () => {
    fetchHistory();

    document.getElementById('btn-refresh').addEventListener('click', fetchHistory);
});

function fetchHistory() {
    const list = document.getElementById('notifications-list');
    list.innerHTML = '<div class="text-center py-5"><i class="fa-solid fa-spinner fa-spin text-2xl text-primary"></i></div>';

    fetch('api/notifications.php?filter=all&limit=50')
        .then(res => res.json())
        .then(data => {
            if (data.data && data.data.length > 0) {
                list.innerHTML = data.data.map(n => {
                    const date = new Date(n.created_at);
                    const formattedDate = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                    const formattedTime = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });

                    const isUnread = n.is_read == 0;

                    let iconClass = 'fa-bell text-primary';
                    let bgClass = 'bg-blue-50';

                    if (n.type === 'New Application') {
                        iconClass = 'fa-file-lines text-blue-600';
                        bgClass = 'bg-blue-100';
                    }

                    return `
                    <div class="notification-item ${isUnread ? 'unread' : ''}">
                        <div class="notif-icon ${bgClass}">
                            <i class="fa-solid ${iconClass}"></i>
                        </div>
                        <div class="notification-content flex-grow">
                            <div class="flex justify-between items-start">
                                <div>
                                    <h4 class="mb-0">${n.type}</h4>
                                    <span class="time">${formattedDate} <span class="mx-1">•</span> ${formattedTime}</span>
                                </div>
                            </div>
                            <p>${n.message}</p>
                        </div>
                    </div>
                `;
                }).join('');
            } else {
                list.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">
                            <i class="fa-regular fa-bell-slash"></i>
                        </div>
                        <h3 class="text-lg font-bold text-slate-700">No Notifications</h3>
                        <p class="text-muted">You're all caught up!</p>
                    </div>
                `;
            }
        })
        .catch(err => {
            console.error(err);
            list.innerHTML = '<div class="text-center text-red-500 py-5">Failed to load notifications.</div>';
        });
}
