(function () {
    'use strict';

    const STORAGE_KEY = 'gatepass_last_pending_count';

    let lastPendingCount = Number(localStorage.getItem(STORAGE_KEY) || 0);

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

    document.addEventListener('click', function () {
        sound.load();
        sound.play().then(function () {
            sound.pause();
            sound.currentTime = 0;
        }).catch(function () {});
    }, { once: true });

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

        if (!toast) {
            document.body.insertAdjacentHTML('beforeend', `
                <div id="requestToast"
                     style="
                        position:fixed;
                        top:20px;
                        right:20px;
                        z-index:9999;
                        background:#ffffff;
                        border-left:5px solid #0088d1;
                        box-shadow:0 10px 30px rgba(0,0,0,0.15);
                        padding:15px 18px;
                        border-radius:10px;
                        font-weight:600;
                        display:none;
                     ">
                </div>
            `);

            toast = document.getElementById('requestToast');
        }

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

        setTimeout(function () {
            toast.style.display = 'none';
        }, 4000);
    }

    async function checkNotifications() {
        try {
            const response = await fetch('api/notifications.php', {
                headers: {
                    Accept: 'application/json'
                }
            });

            const result = await response.json();

            if (!result.success) return;

            const currentPending = Number(result.total_pending || 0);

            if (currentPending > lastPendingCount) {
                sound.currentTime = 0;
                sound.play().catch(function () {});

                showToast('New gatepass request received.');
            }

            lastPendingCount = currentPending;
            localStorage.setItem(STORAGE_KEY, String(currentPending));

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

    document.addEventListener('DOMContentLoaded', function () {
        checkNotifications();
        setInterval(checkNotifications, 5000);
    });

})();