function alerts() {
        $(".crud_section").html("");

    var userObj = JSON.parse(localStorage.getItem('userObj'));

    let currentAttendId = null;
    let currentAttendBtn = null;

    let notificationsCache = [];
    let currentPage = 0;
    const pageSize = 12; // Increased for better grid layout

    /* PRIORITY ORDER */
    const PRIORITY_ORDER = {
        CRITICAL: 1,
        HIGH: 2,
        MEDIUM: 3,
        LOW: 4
    };

    /* ================= LOAD ================= */
    loadNotificationData();

    function loadNotificationData() {
        $(".tab_alarms").html(`
            <div class="alarms-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                <!-- Header Skeleton -->
                <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; border: 1px solid #eaeef2;">
                    <div style="height: 32px; width: 200px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 8px;"></div>
                </div>
                
                <!-- Stats Skeleton -->
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(4).fill().map(() => `
                        <div style="height: 100px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
                    `).join('')}
                </div>
                
                <!-- Filters Skeleton -->
                <div style="height: 60px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 12px; margin-bottom: 24px;"></div>
                
                <!-- Grid Skeleton -->
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
                    ${Array(6).fill().map(() => `
                        <div style="height: 200px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
                    `).join('')}
                </div>
                
                <style>
                    @keyframes loading {
                        0% { background-position: 200% 0; }
                        100% { background-position: -200% 0; }
                    }
                </style>
            </div>
        `);

        $.ajax({
            url: serverURL + "notifications?page=0&size=10000000&alarm=false&sort=createdAt,desc",
            type: "GET",
            dataType: "json",
            headers: {
                Authorization: "Bearer " + userObj.accessToken,
                "Content-Type": "application/json"
            },
            success: function (response) {
                if (!response.content || response.content.length === 0) {
                    $(".tab_alarms").html(`
                        <div class="alarms-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
                            <div style="text-align: center; padding: 60px 20px; background: white; border-radius: 16px; border: 1px solid #eaeef2;">
                                <i class="fas fa-bell-slash" style="font-size: 64px; color: #94a3b8; margin-bottom: 16px;"></i>
                                <h3 style="color: #1a1f36; margin-bottom: 8px;">No Notifications</h3>
                                <p style="color: #5b677c;">All caught up! No notifications at the moment.</p>
                            </div>
                        </div>
                    `);
                    return;
                }

                notificationsCache = response.content.sort((a, b) => {
                    const p1 = PRIORITY_ORDER[a.priority] || 99;
                    const p2 = PRIORITY_ORDER[b.priority] || 99;
                    if (p1 !== p2) return p1 - p2;
                    return new Date(b.createdAt) - new Date(a.createdAt);
                });

                currentPage = 0;
                renderNotificationsPage();
            },
            error: function () {
                $(".tab_alarms").html(`
                    <div class="alarms-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
                        <div style="text-align: center; padding: 60px 20px; background: white; border-radius: 16px; border: 1px solid #eaeef2;">
                            <i class="fas fa-exclamation-triangle" style="font-size: 64px; color: #dc2626; margin-bottom: 16px;"></i>
                            <h3 style="color: #1a1f36; margin-bottom: 8px;">Failed to Load Notifications</h3>
                            <p style="color: #5b677c; margin-bottom: 20px;">Please try again</p>
                            <button onclick="alarms()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                                <i class="fas fa-sync-alt"></i> Retry
                            </button>
                        </div>
                    </div>
                `);
            }
        });
    }

    /* ================= RENDER PAGE ================= */
    function renderNotificationsPage() {
        const start = currentPage * pageSize;
        const pageItems = notificationsCache.slice(start, start + pageSize);

        // Calculate statistics
        const total = notificationsCache.length;
        const unread = notificationsCache.filter(n => !n.read).length;
        const unattended = notificationsCache.filter(n => !n.attended).length;
        const critical = notificationsCache.filter(n => n.priority === 'CRITICAL').length;

        let html = `
        <div class="alarms-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            
            <!-- Header -->
            <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                <div style="display: flex; align-items: center; gap: 16px;">
                    <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-bell" style="color: #000;"></i>
                        Alerts
                    </h1>
                    <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                        ${total} Total
                    </span>
                </div>
                <div style="display: flex; gap: 8px;">
                    <button onclick="markAllAsRead()" style="display: flex; align-items: center; gap: 8px; padding: 10px 16px; background: white; color: #1a1f36; border: 1px solid #eaeef2; border-radius: 10px; font-weight: 500; cursor: pointer;">
                        <i class="fas fa-check-double"></i> Mark All Read
                    </button>
                    <button onclick="refreshNotifications()" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 10px; background: white; cursor: pointer;">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                <!-- Total Card -->
                <div style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #f0f2f5; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-bell" style="font-size: 20px; color: #000;"></i>
                    </div>
                    <div>
                        <div style="font-size: 13px; color: #5b677c;">Total</div>
                        <div style="font-size: 24px; font-weight: 700; color: #1a1f36;">${total}</div>
                    </div>
                </div>

                <!-- Unread Card -->
                <div style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #e3f2fd; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-envelope" style="font-size: 20px; color: #1976d2;"></i>
                    </div>
                    <div>
                        <div style="font-size: 13px; color: #5b677c;">Unread</div>
                        <div style="font-size: 24px; font-weight: 700; color: #1976d2;">${unread}</div>
                    </div>
                </div>

                <!-- Unattended Card -->
                <div style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #fff3e0; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-clock" style="font-size: 20px; color: #ed6c02;"></i>
                    </div>
                    <div>
                        <div style="font-size: 13px; color: #5b677c;">Unattended</div>
                        <div style="font-size: 24px; font-weight: 700; color: #ed6c02;">${unattended}</div>
                    </div>
                </div>

                <!-- Critical Card -->
                <div style="background: #ffffff; border-radius: 16px; padding: 20px; border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                    <div style="width: 48px; height: 48px; background: #fee2e2; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                        <i class="fas fa-exclamation-circle" style="font-size: 20px; color: #dc2626;"></i>
                    </div>
                    <div>
                        <div style="font-size: 13px; color: #5b677c;">Critical</div>
                        <div style="font-size: 24px; font-weight: 700; color: #dc2626;">${critical}</div>
                    </div>
                </div>
            </div>

            <!-- Filter Tabs -->
            <div style="background: #ffffff; border-radius: 12px; padding: 12px; margin-bottom: 24px; border: 1px solid #eaeef2; display: flex; gap: 8px; flex-wrap: wrap;">
                <button class="filter-tab active" data-filter="all" onclick="filterNotifications('all')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; color: #1a1f36; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-list"></i> All
                </button>
                <button class="filter-tab" data-filter="unread" onclick="filterNotifications('unread')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; color: #1a1f36; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-envelope"></i> Unread
                </button>
                <button class="filter-tab" data-filter="unattended" onclick="filterNotifications('unattended')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; color: #1a1f36; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-clock"></i> Unattended
                </button>
                <button class="filter-tab" data-filter="critical" onclick="filterNotifications('critical')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; color: #1a1f36; cursor: pointer; font-size: 13px; display: inline-flex; align-items: center; gap: 6px;">
                    <i class="fas fa-exclamation-triangle"></i> Critical
                </button>
            </div>

            <!-- Notifications Grid -->
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 24px;">
        `;

        pageItems.forEach(item => {
            const priorityColors = {
                CRITICAL: { bg: '#fee2e2', color: '#dc2626', icon: 'fa-exclamation-circle' },
                HIGH: { bg: '#ffedd5', color: '#f97316', icon: 'fa-exclamation-triangle' },
                MEDIUM: { bg: '#fef9c3', color: '#eab308', icon: 'fa-clock' },
                LOW: { bg: '#e0f2fe', color: '#0284c7', icon: 'fa-info-circle' }
            };

            const priorityStyle = priorityColors[item.priority] || priorityColors.LOW;

            html += `
                <div class="notification-card ${item.read ? 'read' : 'unread'}" 
                     data-id="${item.id}"
                     data-read="${item.read}"
                     data-attended="${item.attended}"
                     data-priority="${item.priority}"
                     style="background: #ffffff; border-radius: 16px; border: 1px solid ${item.read ? '#eaeef2' : '#000'}; overflow: hidden; transition: all 0.2s; box-shadow: 0 2px 8px rgba(0,0,0,0.02);">
                    
                    <!-- Priority Bar -->
                    <div style="height: 4px; background: ${priorityStyle.color};"></div>
                    
                    <!-- Header -->
                    <div style="padding: 16px; border-bottom: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <i class="fas ${priorityStyle.icon}" style="color: ${priorityStyle.color};"></i>
                            <span style="font-weight: 600; color: #1a1f36;">${item.title || 'Notification'}</span>
                        </div>
                        <span style="font-size: 12px; color: #5b677c;">
                            <i class="far fa-clock"></i> ${formatTimeAgo(item.createdAt)}
                        </span>
                    </div>
                    
                    <!-- Body -->
                    <div style="padding: 16px;">
                        <p style="margin: 0; color: #1a1f36; line-height: 1.5; font-size: 14px;">
                            ${item.message || 'No message content'}
                        </p>
                        
                        <!-- Metadata -->
                        <div style="margin-top: 12px; display: flex; flex-wrap: wrap; gap: 8px;">
                            <span style="background: ${priorityStyle.bg}; color: ${priorityStyle.color}; padding: 4px 10px; border-radius: 40px; font-size: 11px; font-weight: 600;">
                                ${item.priority}
                            </span>
                            
                            ${item.type ? `
                                <span style="background: #f0f2f5; color: #5b677c; padding: 4px 10px; border-radius: 40px; font-size: 11px;">
                                    ${item.type}
                                </span>
                            ` : ''}
                        </div>
                    </div>
                    
                    <!-- Footer -->
                    <div style="padding: 16px; background: #f8fafc; border-top: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                        <div style="display: flex; gap: 8px;">
                            ${!item.read ? `
                                <button onclick="markAsRead(${item.id}, this)" 
                                        style="padding: 6px 12px; background: white; border: 1px solid #eaeef2; border-radius: 8px; font-size: 12px; color: #1a1f36; cursor: pointer; display: flex; align-items: center; gap: 4px;">
                                    <i class="fas fa-check"></i> Mark Read
                                </button>
                            ` : ''}
                            
                            ${!item.attended ? `
                                <button onclick="openAttendModal(${item.id}, this)" 
                                        style="padding: 6px 12px; background: #000; border: none; border-radius: 8px; font-size: 12px; color: white; cursor: pointer; display: flex; align-items: center; gap: 4px;">
                                    <i class="fas fa-pen"></i> Attend
                                </button>
                            ` : ''}
                        </div>
                        
                        ${item.deviceSerialNumber ? `
                            <button onclick="viewDeviceOnMap('${item.deviceSerialNumber}')" 
                                    style="padding: 6px 12px; background: #e3f2fd; border: none; border-radius: 8px; font-size: 12px; color: #1976d2; cursor: pointer; display: flex; align-items: center; gap: 4px;">
                                <i class="fas fa-map-marker-alt"></i> View
                            </button>
                        ` : ''}
                    </div>
                </div>
            `;
        });

        html += `
            </div>
            
            <!-- Pagination -->
            <div style="background: #ffffff; border-radius: 12px; padding: 16px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                <div style="color: #5b677c; font-size: 14px;">
                    Showing ${start + 1} to ${Math.min(start + pageSize, notificationsCache.length)} of ${notificationsCache.length} notifications
                </div>
                
                <div style="display: flex; gap: 8px;">
                    <button ${currentPage === 0 ? 'disabled' : ''} 
                            onclick="changePage(${currentPage - 1})"
                            style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 8px; background: white; color: #1a1f36; cursor: ${currentPage === 0 ? 'not-allowed' : 'pointer'}; opacity: ${currentPage === 0 ? 0.5 : 1};">
                        <i class="fas fa-chevron-left"></i> Previous
                    </button>
                    
                    <span style="padding: 8px 16px; background: #f8fafc; border-radius: 8px; color: #1a1f36; font-weight: 500;">
                        Page ${currentPage + 1} of ${Math.ceil(notificationsCache.length / pageSize)}
                    </span>
                    
                    <button ${currentPage >= Math.ceil(notificationsCache.length / pageSize) - 1 ? 'disabled' : ''} 
                            onclick="changePage(${currentPage + 1})"
                            style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 8px; background: white; color: #1a1f36; cursor: ${currentPage >= Math.ceil(notificationsCache.length / pageSize) - 1 ? 'not-allowed' : 'pointer'}; opacity: ${currentPage >= Math.ceil(notificationsCache.length / pageSize) - 1 ? 0.5 : 1};">
                        Next <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>
            
            <style>
                /* Notification card hover */
                .notification-card:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 8px 16px rgba(0,0,0,0.05) !important;
                }
                
                /* Filter tab active state */
                .filter-tab.active {
                    background: #000 !important;
                    color: white !important;
                    border-color: #000 !important;
                }
                
                /* Unread indicator */
                .notification-card.unread {
                    border-left-width: 3px;
                }
                
                /* Responsive grid */
                @media (max-width: 1024px) {
                    .alarms-container { padding: 16px !important; }
                    .statistics-grid { grid-template-columns: repeat(2, 1fr) !important; }
                    .notifications-grid { grid-template-columns: repeat(2, 1fr) !important; }
                }
                
                @media (max-width: 768px) {
                    .notifications-grid { grid-template-columns: 1fr !important; }
                }
            </style>
        </div>
        `;

        $(".tab_alerts").html(html);
    }

    /* ================= PAGINATION ================= */
    window.changePage = function(page) {
        currentPage = page;
        renderNotificationsPage();
    };

    /* ================= FILTER ================= */
    window.filterNotifications = function(filter) {
        // Update active tab
        $('.filter-tab').removeClass('active');
        $(`.filter-tab[data-filter="${filter}"]`).addClass('active');
        
        // Filter the cache
        let filtered = [...notificationsCache];
        
        if (filter === 'unread') {
            filtered = filtered.filter(n => !n.read);
        } else if (filter === 'unattended') {
            filtered = filtered.filter(n => !n.attended);
        } else if (filter === 'critical') {
            filtered = filtered.filter(n => n.priority === 'CRITICAL');
        }
        
        // Temporarily replace cache and render
        const originalCache = [...notificationsCache];
        notificationsCache = filtered;
        currentPage = 0;
        renderNotificationsPage();
        
        // Restore original cache (but keep filtered view)
        window._originalCache = originalCache;
    };

    /* ================= MAP FUNCTIONS ================= */
    window.viewDeviceOnMap = function(deviceSerialNumber) {
        if (typeof focusDevice === "function") {
            // Switch to monitoring tab first
            $('.tab-item[onclick*="position"]').click();
            setTimeout(() => {
                focusDevice(deviceSerialNumber);
            }, 500);
        } else {
            openmap(deviceSerialNumber);
        }
    };

    let historyMap;
    let historyPolyline;

    window.openmap = function(deviceSerialNumber) {
        $.ajax({
            url: serverURL + "telemetry/device/" + deviceSerialNumber + "?page=0&size=10",
            type: "GET",
            dataType: "json",
            headers: {
                Authorization: "Bearer " + userObj.accessToken,
                "Content-Type": "application/json"
            },
            success: function (response) {
                if (!response.content || response.content.length < 2) {
                    Swal.fire({
                        title: 'Insufficient Data',
                        text: 'Not enough data points to draw path',
                        icon: 'warning',
                        confirmButtonColor: '#000'
                    });
                    return;
                }
                drawHistoryMap(response.content.reverse(), deviceSerialNumber);
            },
            error: function () {
                Swal.fire({
                    title: 'Error',
                    text: 'Failed to load device history',
                    icon: 'error',
                    confirmButtonColor: '#000'
                });
            }
        });
    };

    window.drawHistoryMap = function(data, deviceSn) {
        // Create modal if it doesn't exist
        if ($('#historyMapModal').length === 0) {
            $('body').append(`
                <div id="historyMapModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10000; backdrop-filter: blur(4px);">
                    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 90%; max-width: 1200px; height: 80%; background: white; border-radius: 24px; overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
                        <div style="padding: 16px 20px; background: #ffffff; border-bottom: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                            <h3 style="margin: 0; font-size: 18px; color: #1a1f36;">
                                <i class="fas fa-history" style="margin-right: 8px; color: #000;"></i>
                                Device History - ${deviceSn}
                            </h3>
                            <button onclick="closeHistoryMap()" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer;">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div id="historyMap" style="height: calc(100% - 70px); width: 100%;"></div>
                    </div>
                </div>
            `);
        }

        $("#historyMapModal").fadeIn(150);

        const pathCoords = data
            .filter(d => d.latitude && d.longitude)
            .map(d => ({ lat: d.latitude, lng: d.longitude }));

        const start = pathCoords[0];
        const end = pathCoords[pathCoords.length - 1];

        historyMap = new google.maps.Map(
            document.getElementById("historyMap"),
            {
                zoom: 14,
                center: end,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                gestureHandling: "greedy",
                zoomControl: true,
                streetViewControl: true,
                mapTypeControl: true,
                fullscreenControl: true,
                styles: [
                    {
                        featureType: "poi",
                        elementType: "labels",
                        stylers: [{ visibility: "off" }]
                    }
                ]
            }
        );

        /* PATH */
        historyPolyline = new google.maps.Polyline({
            path: pathCoords,
            geodesic: true,
            strokeColor: "#1976d2",
            strokeOpacity: 0.9,
            strokeWeight: 4,
            icons: [{
                icon: {
                    path: google.maps.SymbolPath.FORWARD_OPEN_ARROW
                },
                offset: '100%',
                repeat: '100px'
            }]
        });

        historyPolyline.setMap(historyMap);

        /* START MARKER */
        new google.maps.Marker({
            position: start,
            map: historyMap,
            icon: {
                url: "https://maps.google.com/mapfiles/ms/icons/green-dot.png",
                scaledSize: new google.maps.Size(40, 40)
            },
            title: "Start"
        });

        /* END MARKER */
        new google.maps.Marker({
            position: end,
            map: historyMap,
            icon: {
                url: "https://maps.google.com/mapfiles/ms/icons/red-dot.png",
                scaledSize: new google.maps.Size(40, 40)
            },
            title: "Current Position"
        });

        /* FIT BOUNDS */
        const bounds = new google.maps.LatLngBounds();
        pathCoords.forEach(p => bounds.extend(p));
        historyMap.fitBounds(bounds);
    };

    window.closeHistoryMap = function() {
        $("#historyMapModal").fadeOut(150);
        if (historyPolyline) {
            historyPolyline.setMap(null);
        }
    };

    /* ================= ACTIONS ================= */
    window.openAttendModal = function(id, btn) {
        currentAttendId = id;
        currentAttendBtn = btn;
        
        // Create modal if it doesn't exist
        if ($('#attendModal').length === 0) {
            $('body').append(`
                <div id="attendModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10001; backdrop-filter: blur(4px);">
                    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 90%; max-width: 500px; background: white; border-radius: 24px; overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,0.3);">
                        <div style="padding: 20px; background: #ffffff; border-bottom: 1px solid #eaeef2;">
                            <h3 style="margin: 0; font-size: 18px; color: #1a1f36;">Attend Notification</h3>
                        </div>
                        <div style="padding: 20px;">
                            <textarea id="attendComments" placeholder="Enter comments..." style="width: 100%; padding: 12px; border: 1px solid #eaeef2; border-radius: 12px; min-height: 100px; font-family: inherit; resize: vertical;"></textarea>
                        </div>
                        <div style="padding: 20px; border-top: 1px solid #eaeef2; display: flex; justify-content: flex-end; gap: 12px;">
                            <button onclick="closeAttendModal()" style="padding: 10px 20px; border: 1px solid #eaeef2; border-radius: 10px; background: white; color: #1a1f36; cursor: pointer;">Cancel</button>
                            <button onclick="submitAttend()" style="padding: 10px 24px; border: none; border-radius: 10px; background: #000; color: white; cursor: pointer;">Submit</button>
                        </div>
                    </div>
                </div>
            `);
        }
        
        $("#attendModal").fadeIn(150);
    };

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

    window.submitAttend = function() {
        const comments = $("#attendComments").val().trim();
        if (!comments) {
            Swal.fire({
                title: 'Required',
                text: 'Please enter comments',
                icon: 'warning',
                confirmButtonColor: '#000'
            });
            return;
        }

        $.ajax({
            url: serverURL + "notifications/" + currentAttendId + "/attend",
            type: "POST",
            headers: {
                Authorization: "Bearer " + userObj.accessToken,
                "Content-Type": "application/json"
            },
            data: JSON.stringify({ comments }),
            success: function () {
                // Update button
                $(currentAttendBtn).closest('.notification-card').attr('data-attended', 'true');
                $(currentAttendBtn).replaceWith(`
                    <span style="padding: 6px 12px; background: #e8f5e9; border-radius: 8px; font-size: 12px; color: #2e7d32;">
                        <i class="fas fa-check-circle"></i> Attended
                    </span>
                `);
                
                closeAttendModal();
                
                // Show success message
                Swal.fire({
                    title: 'Success',
                    text: 'Notification marked as attended',
                    icon: 'success',
                    timer: 2000,
                    showConfirmButton: false,
                    background: '#ffffff'
                });
            },
            error: function() {
                Swal.fire({
                    title: 'Error',
                    text: 'Failed to mark as attended',
                    icon: 'error',
                    confirmButtonColor: '#000'
                });
            }
        });
    };

    window.markAsRead = function(id, btn) {
        $.ajax({
            url: serverURL + "notifications/" + id + "/read",
            type: "POST",
            headers: {
                Authorization: "Bearer " + userObj.accessToken,
                "Content-Type": "application/json"
            },
            success: function () {
                // Update card
                const $card = $(btn).closest('.notification-card');
                $card.attr('data-read', 'true');
                $card.css('border-color', '#eaeef2');
                
                // Remove button
                $(btn).fadeOut(300, function() {
                    $(this).remove();
                });
                
                // Update stats
                updateStats();
            },
            error: function() {
                Swal.fire({
                    title: 'Error',
                    text: 'Failed to mark as read',
                    icon: 'error',
                    confirmButtonColor: '#000'
                });
            }
        });
    };

    window.markAllAsRead = function() {
        const unreadIds = notificationsCache.filter(n => !n.read).map(n => n.id);
        if (unreadIds.length === 0) {
            Swal.fire({
                title: 'Info',
                text: 'No unread notifications',
                icon: 'info',
                confirmButtonColor: '#000'
            });
            return;
        }

        // Process sequentially
        let processed = 0;
        
        unreadIds.forEach(id => {
            $.ajax({
                url: serverURL + "notifications/" + id + "/read",
                type: "POST",
                headers: {
                    Authorization: "Bearer " + userObj.accessToken,
                    "Content-Type": "application/json"
                },
                success: function () {
                    processed++;
                    if (processed === unreadIds.length) {
                        refreshNotifications();
                        Swal.fire({
                            title: 'Success',
                            text: 'All notifications marked as read',
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    }
                }
            });
        });
    };

    window.refreshNotifications = function() {
        loadNotificationData();
    };

    function updateStats() {
        // This will be called after actions to refresh stats
        // For now, just reload the page data
        loadNotificationData();
    }

    /* ================= UTILS ================= */
    function formatTimeAgo(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const seconds = Math.floor((now - date) / 1000);
        
        if (seconds < 60) return 'just now';
        if (seconds < 3600) return Math.floor(seconds / 60) + ' minutes ago';
        if (seconds < 86400) return Math.floor(seconds / 3600) + ' hours ago';
        if (seconds < 604800) return Math.floor(seconds / 86400) + ' days ago';
        
        return date.toLocaleDateString();
    }
}