{% extends 'base.html' %}
{% load static %}

{% block title %}Notifications - {{ block.super }}{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold">Notifications & System Alerts</h1>
        <div class="flex space-x-4">
            <button id="markAllRead" class="bg-secondary text-white px-4 py-2 rounded hover:bg-opacity-90">
                Mark All as Read
            </button>
            <div class="relative">
                <select id="filterType" class="bg-white border rounded px-4 py-2 appearance-none pr-8">
                    <option value="all">All Types</option>
                    {% for type_value, type_label in notification_types %}
                    <option value="{{ type_value }}">{{ type_label }}</option>
                    {% endfor %}
                </select>
                <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2">
                    <span>﹀</span>
                </div>
            </div>
        </div>
    </div>

    {% if is_admin %}
    <!-- System Statistics Dashboard -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 cursor-pointer hover:shadow-2xl hover:scale-105 hover:bg-blue-50 dark:hover:bg-gray-700 transition-all duration-300 border-2 border-transparent hover:border-blue-500" 
             onclick="window.location.href='{% url 'loans:loans' %}'">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>💵</span>
                </div>
                <div class="ml-4 flex-grow">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Loan Portfolio</h3>
                    <p class="text-2xl font-bold text-blue-600">KES {{ loan_statistics.total_disbursed|floatformat:0 }}</p>
                    <p class="text-sm text-gray-500">{{ loan_statistics.active_loans }} Active Loans</p>
                </div>
                <span>→</span>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 cursor-pointer hover:shadow-2xl hover:scale-105 hover:bg-green-50 dark:hover:bg-gray-700 transition-all duration-300 border-2 border-transparent hover:border-green-500"
             onclick="window.location.href='{% url 'users:client_list' %}'">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>👥</span>
                </div>
                <div class="ml-4 flex-grow">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Users</h3>
                    <p class="text-2xl font-bold text-green-600">{{ user_statistics.total_users }}</p>
                    <p class="text-sm text-gray-500">{{ user_statistics.active_users }} Active</p>
                </div>
                <span>→</span>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 cursor-pointer hover:shadow-2xl hover:scale-105 hover:bg-red-50 dark:hover:bg-gray-700 transition-all duration-300 border-2 border-transparent hover:border-red-500"
             onclick="window.location.href='{% url 'loans:loans' %}?status=defaulted'">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>⚠️</span>
                </div>
                <div class="ml-4 flex-grow">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Default Rate</h3>
                    <p class="text-2xl font-bold text-red-600">{{ loan_statistics.default_rate|floatformat:1 }}%</p>
                    <p class="text-sm text-gray-500">{{ loan_statistics.defaulted_loans }} Defaulted</p>
                </div>
                <span>→</span>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 cursor-pointer hover:shadow-2xl hover:scale-105 hover:bg-orange-50 dark:hover:bg-gray-700 transition-all duration-300 border-2 border-transparent hover:border-orange-500"
             onclick="window.location.href='{% url 'loans:applications' %}'">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <span>⏰</span>
                </div>
                <div class="ml-4 flex-grow">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Pending</h3>
                    <p class="text-2xl font-bold text-orange-600">{{ pending_applications.count }}</p>
                    <p class="text-sm text-gray-500">Applications</p>
                </div>
                <span>→</span>
            </div>
        </div>
    </div>


    <!-- System Alerts Section -->
    {% if system_alerts %}
    <div class="mb-8">
        <h2 class="text-xl font-semibold mb-4 text-red-600">System Alerts</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {% for alert in system_alerts %}
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-4 border-l-4 
                        {% if alert.priority == 'urgent' %}border-red-500{% elif alert.priority == 'high' %}border-orange-500{% elif alert.priority == 'medium' %}border-yellow-500{% else %}border-blue-500{% endif %}
                        {% if alert.action_url %}cursor-pointer hover:shadow-2xl hover:scale-105 hover:border-l-8 transition-all duration-300{% endif %}"
                 {% if alert.action_url %}onclick="window.location.href='{{ alert.action_url }}'"{% endif %}>
                <div class="flex items-start">
                    <div class="flex-shrink-0">
                        <i class="fas {{ alert.icon }} text-2xl 
                                   {% if alert.priority == 'urgent' %}text-red-500{% elif alert.priority == 'high' %}text-orange-500{% elif alert.priority == 'medium' %}text-yellow-500{% else %}text-blue-500{% endif %}"></i>
                    </div>
                    <div class="ml-4 flex-grow">
                        <h3 class="text-lg font-semibold">{{ alert.title }}</h3>
                        <p class="text-gray-600 dark:text-gray-300 mt-1">{{ alert.message }}</p>
                        <div class="mt-2 flex items-center justify-between">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                       {% if alert.priority == 'urgent' %}bg-red-100 text-red-800{% elif alert.priority == 'high' %}bg-orange-100 text-orange-800{% elif alert.priority == 'medium' %}bg-yellow-100 text-yellow-800{% else %}bg-blue-100 text-blue-800{% endif %}">
                                {{ alert.priority|title }}
                            </span>
                            {% if alert.action_url %}
                            <span class="text-secondary hover:text-opacity-80 text-sm">
                                View Details <span>→</span>
                            </span>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}

    <!-- Security Alerts Section -->
    {% if security_alerts %}
    <div class="mb-8">
        <h2 class="text-xl font-semibold mb-4 text-red-600">Security Alerts</h2>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-50 dark:bg-gray-700">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Alert Type</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Description</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Priority</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Time</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                        {% for alert in security_alerts %}
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <i class="fas {{ alert.icon }} text-red-500 mr-2"></i>
                                    <span class="text-sm font-medium text-gray-900 dark:text-white">{{ alert.title }}</span>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                                {{ alert.message }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                    {{ alert.priority|title }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                {{ alert.timestamp|timesince }} ago
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Recent Activity Section -->
    <div class="mb-8">
        <h2 class="text-xl font-semibold mb-4">Recent Activity (Last 24 Hours)</h2>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <div class="flow-root">
                <ul role="list" class="-mb-8" id="activityList">
                    {% for activity in recent_activities %}
                    <li>
                        <div class="relative pb-8">
                            {% if not forloop.last %}
                            <span class="absolute left-4 top-4 -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true"></span>
                            {% endif %}
                            <div class="relative flex space-x-3">
                                <div>
                                    <span class="h-8 w-8 rounded-full flex items-center justify-center ring-8 ring-white
                                        {% if activity.action == 'delete' %}bg-red-500
                                        {% elif activity.action == 'create' %}bg-green-500
                                        {% elif activity.action == 'update' %}bg-blue-500
                                        {% elif activity.action == 'payment' %}bg-purple-500
                                        {% elif activity.action == 'login' %}bg-indigo-500
                                        {% else %}bg-gray-500{% endif %}">
                                        <i class="fas fa-{% if activity.action == 'delete' %}trash{% elif activity.action == 'create' %}plus-circle{% elif activity.action == 'update' %}edit{% elif activity.action == 'payment' %}money-bill-wave{% elif activity.action == 'login' %}sign-in-alt{% else %}info{% endif %} h-5 w-5 text-white"></i>
                                    </span>
                                </div>
                                <div class="flex min-w-0 flex-1 justify-between space-x-4 pt-1.5">
                                    <div>
                                        <p class="text-sm text-gray-500">
                                            <span class="font-medium text-gray-900">{{ activity.user.get_full_name|default:"System" }}</span>
                                            {{ activity.description }}
                                        </p>
                                        <p class="text-xs text-gray-400">{{ activity.model_name }} - {{ activity.object_id }}</p>
                                    </div>
                                    <div class="whitespace-nowrap text-right text-sm text-gray-500">
                                        <time datetime="{{ activity.created_at|date:'c' }}" class="timeago">{{ activity.created_at|timesince }} ago</time>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                    {% empty %}
                    <li>
                        <p class="text-sm text-gray-500 text-center">No recent activity</p>
                    </li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </div>

    {% if overdue_loans %}
    <!-- Overdue Loans Section -->
    <div class="mb-8">
        <h2 class="text-xl font-semibold mb-4 text-red-600">Overdue Loans</h2>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-50 dark:bg-gray-700">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Borrower</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Loan Amount</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Due Date</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Days Overdue</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                        {% for loan in overdue_loans %}
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ loan.borrower.get_full_name }}</div>
                                <div class="text-sm text-gray-500 dark:text-gray-400">{{ loan.borrower.phone_number }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                                KES {{ loan.total_amount|floatformat:2 }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                                {{ loan.due_date|date:"M d, Y" }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                    {{ loan.due_date|timesince }} overdue
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <a href="{% url 'loans:loan_detail' loan.id %}" class="text-secondary hover:text-opacity-80">View Details</a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    {% endif %}

    {% if pending_applications %}
    <!-- Pending Applications Section -->
    <div class="mb-8">
        <h2 class="text-xl font-semibold mb-4 text-orange-600">Pending Applications</h2>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-50 dark:bg-gray-700">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Applicant</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Loan Amount</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Applied Date</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                        {% for application in pending_applications %}
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ application.borrower.get_full_name }}</div>
                                <div class="text-sm text-gray-500 dark:text-gray-400">{{ application.borrower.phone_number }}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                                KES {{ application.requested_amount|floatformat:2 }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                                {{ application.created_at|date:"M d, Y" }}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                    Pending Review
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <a href="{% url 'loans:application_detail' application.id %}" class="text-secondary hover:text-opacity-80">Review</a>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    {% endif %}
    {% endif %}

    <!-- User Notifications Section -->
    <div class="mb-8">
        <h2 class="text-xl font-semibold mb-4">Your Notifications</h2>
        <div id="notifications-container" class="space-y-4">
            {% for notification in notifications %}
            <div class="notification-item bg-white dark:bg-gray-800 rounded-lg shadow p-4 {% if not notification.is_read %}border-l-4 border-secondary{% endif %} {% if notification.action_url %}cursor-pointer hover:shadow-2xl hover:scale-102 hover:bg-gray-50 dark:hover:bg-gray-700 transition-all duration-300 hover:border-l-8{% endif %}"
                 data-id="{{ notification.id }}" data-type="{{ notification.notification_type }}" data-action-url="{% if notification.action_url %}{{ notification.action_url }}{% endif %}"
                 onclick="handleNotificationClick(this, event)">
                <div class="flex items-start">
                    <div class="flex-shrink-0">
                        <i class="fas {{ notification.icon }} text-2xl {% if notification.priority == 'urgent' %}text-red-500{% elif notification.priority == 'high' %}text-orange-500{% elif notification.priority == 'medium' %}text-yellow-500{% else %}text-green-500{% endif %}"></i>
                    </div>
                    <div class="ml-4 flex-grow">
                        <div class="flex justify-between items-start">
                            <h3 class="text-lg font-semibold">{{ notification.title }}</h3>
                            <div class="flex items-center space-x-2">
                                <span class="text-sm text-gray-500" title="{{ notification.created_at|date:'Y-m-d H:i:s' }}">
                                    {{ notification.age_display }} ago
                                </span>
                                {% if not notification.is_read %}
                                <button class="mark-read-btn text-secondary hover:text-opacity-80" onclick="event.stopPropagation();">
                                    <span>✓</span>
                                </button>
                                {% endif %}
                            </div>
                        </div>
                        <p class="text-gray-600 dark:text-gray-300 mt-1">{{ notification.message }}</p>
                        {% if notification.action_url %}
                        <div class="inline-flex items-center mt-2 text-secondary">
                            <span class="mr-1">Click to view</span>
                            <span>→</span>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="text-center py-8">
                <i class="fas fa-bell-slash text-4xl text-gray-400 mb-4"></i>
                <p class="text-gray-500">No notifications to display</p>
            </div>
            {% endfor %}
        </div>
    </div>

    <div id="notification-toast" class="fixed bottom-4 right-4 transform translate-y-full opacity-0 transition-all duration-300">
        <!-- New notifications will appear here -->
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/timeago.js/4.0.2/timeago.min.js"></script>
<script>
    // Poll for new notifications every 30 seconds
    const POLL_INTERVAL = 30000;
    
    function pollNewNotifications() {
        fetch('/utils/api/notifications/new/', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.notifications && data.notifications.length > 0) {
                data.notifications.forEach(notification => {
                    showNotificationToast(notification);
                    appendNotification(notification);
                });
            }
        });
    }

    function showNotificationToast(notification) {
        const toast = document.getElementById('notification-toast');
        toast.innerHTML = `
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-4 mb-4 flex items-start max-w-md">
                <i class="fas ${notification.icon} text-2xl mr-4 ${getPriorityColor(notification.priority)}"></i>
                <div>
                    <h4 class="font-semibold">${notification.title}</h4>
                    <p class="text-sm text-gray-600 dark:text-gray-300">${notification.message}</p>
                </div>
            </div>
        `;
        toast.classList.remove('translate-y-full', 'opacity-0');
        
        setTimeout(() => {
            toast.classList.add('translate-y-full', 'opacity-0');
        }, 5000);
    }

    function appendNotification(notification) {
        const container = document.getElementById('notifications-container');
        const emptyMessage = container.querySelector('p.text-gray-500');
        if (emptyMessage) {
            emptyMessage.remove();
        }

        const notificationHtml = `
            <div class="notification-item bg-white dark:bg-gray-800 rounded-lg shadow p-4 border-l-4 border-secondary" 
                 data-id="${notification.id}" data-type="${notification.notification_type}">
                <div class="flex items-start">
                    <div class="flex-shrink-0">
                        <i class="fas ${notification.icon} text-2xl ${getPriorityColor(notification.priority)}"></i>
                    </div>
                    <div class="ml-4 flex-grow">
                        <div class="flex justify-between items-start">
                            <h3 class="text-lg font-semibold">${notification.title}</h3>
                            <div class="flex items-center space-x-2">
                                <span class="text-sm text-gray-500">just now</span>
                                <button class="mark-read-btn text-secondary hover:text-opacity-80">
                                    <span>✓</span>
                                </button>
                            </div>
                        </div>
                        <p class="text-gray-600 dark:text-gray-300 mt-1">${notification.message}</p>
                        ${notification.action_url ? `
                            <a href="${notification.action_url}" class="inline-block mt-2 text-secondary hover:text-opacity-80">
                                Take Action <span>→</span>
                            </a>
                        ` : ''}
                    </div>
                </div>
            </div>
        `;
        container.insertAdjacentHTML('afterbegin', notificationHtml);
        
        // Add event listener to new mark-read button
        const newNotification = container.firstElementChild;
        const markReadBtn = newNotification.querySelector('.mark-read-btn');
        if (markReadBtn) {
            markReadBtn.addEventListener('click', handleMarkRead);
        }
    }

    function getPriorityColor(priority) {
        switch(priority) {
            case 'urgent': return 'text-red-500';
            case 'high': return 'text-orange-500';
            case 'medium': return 'text-yellow-500';
            default: return 'text-green-500';
        }
    }

    // Filter notifications
    document.getElementById('filterType').addEventListener('change', function(e) {
        const type = e.target.value;
        document.querySelectorAll('.notification-item').forEach(item => {
            if (type === 'all' || item.dataset.type === type) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });

    // Mark all as read
    document.getElementById('markAllRead').addEventListener('click', function() {
        fetch('/utils/api/notifications/mark-all-read/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
            },
        }).then(response => {
            if (response.ok) {
                document.querySelectorAll('.notification-item').forEach(item => {
                    item.classList.remove('border-l-4', 'border-secondary');
                    const readBtn = item.querySelector('.mark-read-btn');
                    if (readBtn) readBtn.remove();
                });
            }
        });
    });

    // Individual mark as read
    function handleMarkRead() {
        const item = this.closest('.notification-item');
        const id = item.dataset.id;
        
        fetch(`/utils/api/notifications/${id}/mark-read/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken'),
            },
        }).then(response => {
            if (response.ok) {
                item.classList.remove('border-l-4', 'border-secondary');
                this.remove();
            }
        });
    }

    document.querySelectorAll('.mark-read-btn').forEach(btn => {
        btn.addEventListener('click', handleMarkRead);
    });

    // Handle notification click - mark as read and navigate
    function handleNotificationClick(element, event) {
        const actionUrl = element.dataset.actionUrl;
        const notificationId = element.dataset.id;
        
        // Don't navigate if clicking the mark-read button
        if (event.target.closest('.mark-read-btn')) {
            return;
        }
        
        // Only navigate if there's a valid action URL (not empty, None, null, or undefined)
        if (!actionUrl || actionUrl === '' || actionUrl === 'None' || actionUrl === 'null') {
            return;
        }
        
        // Mark as read if unread
        const isUnread = element.classList.contains('border-secondary');
        if (isUnread) {
            fetch(`/utils/api/notifications/${notificationId}/mark-read/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCookie('csrftoken'),
                },
            }).then(response => {
                if (response.ok) {
                    element.classList.remove('border-l-4', 'border-secondary');
                }
            });
        }
        
        // Navigate to the action URL
        window.location.href = actionUrl;
    }

    // Helper function to get CSRF token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // Initialize timeago
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof timeago !== 'undefined') {
            timeago.render(document.querySelectorAll('.timeago'));
        }
    });

    // Start polling
    setInterval(pollNewNotifications, POLL_INTERVAL);
    
    // Initial poll
    pollNewNotifications();
</script>
{% endblock %} 