(function () {
    'use strict';
    const closeBtn = document.getElementById('notifClose');
    const bell = document.getElementById('notifBell');
    const count = document.getElementById('notifCount');
    const dropdown = document.getElementById('notifDropdown');
    const list = document.getElementById('notifList');

    if (!bell || !count || !dropdown || !list) return;

    const LAST_ID_KEY = 'gatepass_last_seen_notification_id';
    const LAST_PLAYED_KEY = 'gatepass_last_played_notification_id';

    let firstLoad = true;
    let lastSeenId = Number(localStorage.getItem(LAST_ID_KEY) || 0);
    let lastPlayedId = Number(localStorage.getItem(LAST_PLAYED_KEY) || 0);
    let isPlaying = false;

    const sound = new Audio('assets/sounds/notification.mp3');
    sound.volume = 1;
    sound.preload = 'auto';

    function playSoundOnce(notificationId) {
        if (isPlaying) return;
        if (notificationId <= lastPlayedId) return;

        isPlaying = true;
        lastPlayedId = notificationId;
        localStorage.setItem(LAST_PLAYED_KEY, String(notificationId));

        sound.pause();
        sound.currentTime = 0;

        sound.play()
            .catch(() => {})
            .finally(() => {
                setTimeout(() => {
                    isPlaying = false;
                }, 1500);
            });
    }

    function showToast(message) {
        let toast = document.getElementById('requestToast');

        if (!toast) {
            document.body.insertAdjacentHTML('beforeend', `
                <div id="requestToast"
                     style="
                        position:fixed;
                        top:90px;
                        right:20px;
                        z-index:999999;
                        background:#fff;
                        border-left:5px solid #dc3545;
                        box-shadow:0 15px 40px rgba(0,0,0,.15);
                        padding:15px 18px;
                        border-radius:12px;
                        font-weight:600;
                        display:none;
                     ">
                </div>
            `);
            toast = document.getElementById('requestToast');
        }

        toast.textContent = message;
        toast.style.display = 'block';

        setTimeout(() => {
            toast.style.display = 'none';
        }, 4000);
    }
    if (closeBtn) {
    closeBtn.addEventListener('click', function () {
        dropdown.classList.add('d-none');
    });
}
    async function loadNotifications() {
        try {
            const response = await fetch('api/notifications.php');
            const result = await response.json();

            if (!result.success) return;

            const unread = Number(result.unread_count || 0);
            const notifications = result.notifications || [];
            const newestId = notifications.length ? Number(notifications[0].id) : 0;

            if (unread > 0) {
                count.classList.remove('d-none');
                count.textContent = unread;
            } else {
                count.classList.add('d-none');
                count.textContent = '0';
            }

            if (firstLoad) {
                firstLoad = false;

                if (newestId > lastSeenId) {
                    lastSeenId = newestId;
                    localStorage.setItem(LAST_ID_KEY, String(newestId));
                }

                if (newestId > lastPlayedId) {
                    localStorage.setItem(LAST_PLAYED_KEY, String(newestId));
                    lastPlayedId = newestId;
                }
            } else if (newestId > lastSeenId) {
                showToast(notifications[0]?.message || 'New gatepass request received.');
                playSoundOnce(newestId);

                lastSeenId = newestId;
                localStorage.setItem(LAST_ID_KEY, String(newestId));
            }

            if (!notifications.length) {
                list.innerHTML = '<div class="notif-empty">No notifications</div>';
                return;
            }

            list.innerHTML = notifications.map(item => `
                <a href="${item.target_page}" class="notif-link">
                    <div class="notif-item">
                        <div class="notif-message">${item.message}</div>
                        <div class="notif-time">
                            Ref: ${item.transaction_ref}<br>
                            ${item.created_at}
                        </div>
                    </div>
                </a>
            `).join('');

        } catch (err) {
            console.error(err);
        }
    }

    bell.addEventListener('click', async function () {
        dropdown.classList.remove('d-none');

        try {
            await fetch('api/notifications.php?action=read');
            count.classList.add('d-none');
            count.textContent = '0';
        } catch (err) {
            console.error(err);
        }
    });

    document.addEventListener('click', function (e) {
        if (!dropdown.contains(e.target) && !bell.contains(e.target)) {
            dropdown.classList.add('d-none');
        }
    });

    loadNotifications();
    setInterval(loadNotifications, 5000);
})();