<?php
/**
 * Page Footer Template
 */
?>
<?php if (SessionManager::isLoggedIn()): ?>
        </main>
    </div>
</div>
<?php endif; ?>

<script>
function toggleSidebar() {
    document.body.classList.toggle('sidebar-collapsed');
}
document.querySelectorAll('.alert').forEach(function(el) {
    setTimeout(function() { el.style.opacity = '0'; setTimeout(function() { el.remove(); }, 300); }, 5000);
});
document.querySelectorAll('[data-confirm]').forEach(function(el) {
    el.addEventListener('click', function(e) {
        if (!confirm(el.getAttribute('data-confirm'))) e.preventDefault();
    });
});

// Load DataTables JS and init
const datatablesScript = document.createElement('script');
datatablesScript.src  = 'https://cdn.datatables.net/2.1.5/js/dataTables.js';
datatablesScript.defer = true;
datatablesScript.onload = function() {
    const responsiveScript = document.createElement('script');
    responsiveScript.src      = 'https://cdn.datatables.net/responsive/3.0.2/js/dataTables.responsive.js';
    responsiveScript.defer    = true;
    responsiveScript.onload   = function() {
        const pwaAppScript = document.createElement('script');
        pwaAppScript.src         = '<?= APP_URL ?>/assets/js/idb.js';
        pwaAppScript.defer       = true;
        pwaAppScript.onload      = function() {
            const pwaQueueScript = document.createElement('script');
            pwaQueueScript.src    = '<?= APP_URL ?>/assets/js/offline-queue.js';
            pwaQueueScript.defer  = true;
            pwaQueueScript.onload = function() {
                const appScript = document.createElement('script');
                appScript.src         = '<?= APP_URL ?>/assets/js/items_datatables.js';
                appScript.defer       = true;
                document.head.appendChild(appScript);
            };
            document.head.appendChild(pwaQueueScript);
        };
        document.head.appendChild(pwaAppScript);
    };

    document.head.appendChild(responsiveScript);
};
document.head.appendChild(datatablesScript);

// ======================  PWA — SERVICE WORKER  ============================
(function registerSW() {
    if (!('serviceWorker' in navigator)) return;

    const SW_URL = '/invcount/assets/js/sw.js';

    navigator.serviceWorker
        .register(SW_URL, { scope: '/invcount/' })
        .then(registration => {
            console.info('[PWARegister] Service Worker registered.', {
                scriptURL: registration.scriptURL,
                scope:     registration.scope,
                state:     registration.active?.state ?? 'unknown',
            });

            registration.addEventListener('updatefound', () => {
                const installing = registration.installing;
                installing.addEventListener('statechange', () => {
                    if (
                        installing.state === 'installed'
                        && navigator.serviceWorker.controller
                    ) {
                        console.info('[SW] New version ready. Reload to activate.');
                        window.location.reload();
                    }
                });
            });

            navigator.serviceWorker.addEventListener('controllerchange', () => {
                console.info('[PWARegister] Controller changed — reloading.');
                window.location.reload();
            });
        })
        .catch(error =>
            console.error('[PWARegister] Service Worker registration failed:', error)
        );
})();

// ======================  PWA — INSTALL PROMPT  ============================
window.addEventListener('beforeinstallprompt', e => {
    e.preventDefault();
    window.__deferredInstallPrompt = e;
    const btn = document.createElement('button');
    btn.id         = 'install-pwa-btn';
    btn.textContent = 'Install Inventory Counter';
    btn.style.cssText = [
        'display:none',
        'margin:1rem auto',
        'padding:.75rem 1.5rem',
        'background:#16213e',
        'color:#fff',
        'border:none',
        'border-radius:8px',
        'cursor:pointer',
        'font-size:1rem',
    ].join(';');
    // Append near the topbar where it won't be hidden by layout
    document.querySelector('.topbar-actions')?.appendChild(btn) ?? document.body.appendChild(btn);

    btn.addEventListener('click', async () => {
        const promptEvent = window.__deferredInstallPrompt;
        if (!promptEvent) return;
        const { outcome } = await promptEvent.prompt();
        console.log('[PWA] Install prompt outcome =', outcome);
        window.__deferredInstallPrompt = null;
        btn.remove();
    });
    btn.style.display = 'block';
});

// Handle app-installed event (Android / desktop)
window.addEventListener('appinstalled', () => {
    console.info('[PWA] Inventory Counter was installed.');
    window.__deferredInstallPrompt = null;
    const btn = document.getElementById('install-pwa-btn');
    if (btn) btn.remove();
});

// ======================  PWA — QUEUE BADGE  ==========================
(function queueBadge() {
    if (!window.offlineQueue) return;

    // Show badge whenever items are queued
    function updateBadge() {
        window.offlineQueue.getQueueCount().then(function (n) {
            var existing = document.getElementById('queue-badge');
            if (existing) existing.remove();

            if (n <= 0) return;

            var badge = document.createElement('div');
            badge.id = 'queue-badge';
            badge.title = n + ' count(s) waiting to sync';
            badge.textContent = '⚠ ' + n + ' pending';
            Object.assign(badge.style, {
                position:      'fixed',
                top:           '60px',
                right:         '12px',
                padding:       '5px 12px',
                background:    '#e67e22',
                color:         '#fff',
                borderRadius:  '20px',
                fontSize:      '.78rem',
                fontWeight:    '700',
                zIndex:        '9999',
                boxShadow:     '0 2px 8px rgba(0,0,0,.25)',
            });
            document.body.appendChild(badge);
        });
    }

    // Stale-data banner (posts still served from cache > 5 min old)
    var cacheAgeMinutes = 0;
    function getCacheAge() {
        try {
            var entry = performance.getEntriesByType('navigation')[0];
            cacheAgeMinutes = entry ? Math.round(performance.now() / 60000) : 0;
        } catch (_) { cacheAgeMinutes = 0; }
    }

    function showStaleBanner() {
        if (cacheAgeMinutes < 5) return;
        if (document.getElementById('stale-data-banner')) return;
        var banner = document.createElement('div');
        banner.id = 'stale-data-banner';
        banner.innerHTML = '<strong>Note:</strong> Some data loaded from cache (' + cacheAgeMinutes + ' minutes ago). Pull to refresh when online.';
        Object.assign(banner.style, {
            position:      'fixed',
            bottom:        '80px',
            left:          '50%',
            transform:     'translateX(-50%)',
            padding:       '8px 16px',
            background:    '#f39c12',
            color:         '#fff',
            borderRadius:  '8px',
            fontSize:      '.82rem',
            fontWeight:    '500',
            zIndex:        '9999',
            whiteSpace:    'nowrap',
            boxShadow:     '0 2px 8px rgba(0,0,0,.25)',
        });
        document.body.appendChild(banner);
        setTimeout(function () { banner.style.opacity = '0'; setTimeout(function () { banner.remove(); }, 300); }, 10000);
    }

    updateBadge();
    getCacheAge();
    showStaleBanner();

    window.addEventListener('online', function () { updateBadge(); });
    setInterval(updateBadge, 15000);
})();
</script>
</body>
</html>
