/**
 * pwa.js — Titipin Ba Be PWA Manager
 *
 * Tanggung jawab:
 * 1. Register Service Worker
 * 2. Install Prompt (tombol "Pasang Aplikasi")
 * 3. Auto-update notification saat SW baru tersedia
 */

// ── 1. Register Service Worker ─────────────────────────────────────────────
if ('serviceWorker' in navigator) {
    window.addEventListener('load', async () => {
        try {
            const registration = await navigator.serviceWorker.register('/sw.js', {
                scope: '/',
            });

            // ── Auto-update: cek SW baru setiap 60 menit
            setInterval(() => registration.update(), 60 * 60 * 1000);

            // ── Deteksi SW baru yang menunggu
            registration.addEventListener('updatefound', () => {
                const newWorker = registration.installing;
                if (!newWorker) return;

                newWorker.addEventListener('statechange', () => {
                    if (
                        newWorker.state === 'installed' &&
                        navigator.serviceWorker.controller
                    ) {
                        // Ada versi baru — tampilkan notifikasi update
                        showUpdateToast();
                    }
                });
            });

        } catch (err) {
            // SW gagal register — aplikasi tetap berjalan normal
            console.warn('[PWA] Service Worker registration failed:', err);
        }
    });

    // Reload otomatis saat SW baru aktif
    let refreshing = false;
    navigator.serviceWorker.addEventListener('controllerchange', () => {
        if (!refreshing) {
            refreshing = true;
            window.location.reload();
        }
    });
}

// ── 2. Install Prompt ──────────────────────────────────────────────────────
let deferredPrompt = null;

window.addEventListener('beforeinstallprompt', (e) => {
    // Cegah prompt otomatis browser
    e.preventDefault();
    deferredPrompt = e;

    // Tampilkan tombol install custom (hanya jika belum pernah dismiss)
    const dismissed = localStorage.getItem('pwa_install_dismissed');
    if (!dismissed) {
        showInstallBanner();
    }
});

// Aplikasi berhasil diinstall
window.addEventListener('appinstalled', () => {
    deferredPrompt = null;
    hideInstallBanner();
    localStorage.removeItem('pwa_install_dismissed');
});

/**
 * Dipanggil saat user klik tombol install (dari view).
 * Expose ke window agar bisa dipanggil dari Blade.
 */
window.pwaInstall = async function () {
    if (!deferredPrompt) return;

    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;

    if (outcome === 'dismissed') {
        localStorage.setItem('pwa_install_dismissed', '1');
    }

    deferredPrompt = null;
    hideInstallBanner();
};

window.pwaDismiss = function () {
    localStorage.setItem('pwa_install_dismissed', '1');
    hideInstallBanner();
};

// ── 3. UI Helpers ──────────────────────────────────────────────────────────

function showInstallBanner() {
    const banner = document.getElementById('pwa-install-banner');
    if (banner) {
        banner.style.display = 'flex';
        // Animasi slide-up
        requestAnimationFrame(() => {
            banner.style.transform = 'translateY(0)';
            banner.style.opacity  = '1';
        });
    }
}

function hideInstallBanner() {
    const banner = document.getElementById('pwa-install-banner');
    if (banner) {
        banner.style.transform = 'translateY(100%)';
        banner.style.opacity  = '0';
        setTimeout(() => { banner.style.display = 'none'; }, 300);
    }
}

function showUpdateToast() {
    const toast = document.getElementById('pwa-update-toast');
    if (toast) {
        toast.style.display = 'flex';
        requestAnimationFrame(() => {
            toast.style.transform = 'translateY(0)';
            toast.style.opacity  = '1';
        });
    }
}

window.pwaUpdate = function () {
    // Perintahkan SW baru untuk skipWaiting
    navigator.serviceWorker.ready.then((reg) => {
        reg.waiting?.postMessage({ type: 'SKIP_WAITING' });
    });
};
