<script src="@Url.Content("~/driver/lib/jquery/dist/jquery.min.js")"></script>
<script src="@Url.Content("~/driver/lib/bootstrap/dist/js/bootstrap.bundle.min.js")"></script>
<script src="@Url.Content("~/driver/js/site.js")" asp-append-version="true"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<script>
        document.addEventListener('DOMContentLoaded', function () {
    lucide.createIcons();
});
</script>
<script>
    if ("serviceWorker" in navigator) {
        window.addEventListener("load", () => {
            navigator.serviceWorker.register("@Url.Content("~/driver/serviceworker.js")", { scope: "/upst" });
        });
    }
</script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const installPrompt = document.getElementById("pwaInstallPrompt");
        const installButton = document.getElementById("pwaInstallButton");
        const dismissButton = document.getElementById("pwaInstallDismiss");
        const helpButton = document.getElementById("pwaInstallHelpButton");
        const helpModal = document.getElementById("pwaInstallHelpModal");
        const helpClose = document.getElementById("pwaInstallHelpClose");
        const helpPrimary = document.getElementById("pwaInstallHelpPrimary");
        const helpText = document.getElementById("pwaInstallHelpText");
        const helpSteps = document.getElementById("pwaInstallHelpSteps");
        const description = document.getElementById("pwaInstallDescription");

        if (!installPrompt || !installButton || !dismissButton || !helpButton || !helpModal || !helpClose || !helpPrimary || !helpText || !helpSteps || !description) {
            return;
        }

        const dismissKey = "espj-upst-pwa-install-dismissed-session";
        let deferredPrompt = null;

        function isStandalone() {
            return window.matchMedia("(display-mode: standalone)").matches || window.navigator.standalone === true;
        }

        function isIos() {
            return /iphone|ipad|ipod/i.test(window.navigator.userAgent);
        }

        function isAndroid() {
            return /android/i.test(window.navigator.userAgent);
        }

        function isFirefox() {
            return /firefox|fxios/i.test(window.navigator.userAgent);
        }

        function isDesktopFirefox() {
            return isFirefox() && !isAndroid() && !isIos();
        }

        function showInstallPrompt() {
            if (isStandalone()) return;
            installPrompt.classList.remove("hidden");
        }

        function hideInstallPrompt(rememberDismissal) {
            installPrompt.classList.add("hidden");
            if (rememberDismissal) {
                window.sessionStorage.setItem(dismissKey, "true");
            }
        }

        function openHelpModal() {
            helpModal.classList.remove("hidden");
            helpModal.classList.add("flex");
        }

        function closeHelpModal() {
            helpModal.classList.add("hidden");
            helpModal.classList.remove("flex");
        }

        function updateManualInstallCopy() {
            if (isIos()) {
                description.textContent = "Di iPhone/iPad, install dilakukan lewat menu Share browser, termasuk di Firefox iOS.";
                helpText.textContent = "Tekan tombol Share di browser, lalu pilih Add to Home Screen untuk memasang eSPJ.";
                helpSteps.innerHTML = `
                    <p>Safari / Chrome / Edge / Firefox di iPhone & iPad: tekan <span class="font-bold text-slate-800">Share</span>, lalu pilih <span class="font-bold text-slate-800">Add to Home Screen</span>.</p>
                    <p>Kalau opsi belum terlihat, scroll menu Share ke bawah sampai bagian tindakan tambahan.</p>
                `;
                helpPrimary.textContent = "Lihat Panduan";
                installButton.textContent = "Buka Panduan";
                return;
            }

            if (isDesktopFirefox()) {
                description.textContent = "Firefox desktop belum mendukung install PWA berbasis manifest langsung dari web.";
                helpText.textContent = "eSPJ tetap bisa dipakai normal di Firefox desktop, tapi untuk install sebagai app gunakan Chrome, Edge, atau Safari macOS yang mendukung.";
                helpSteps.innerHTML = `
                    <p>Firefox desktop: belum ada dukungan install PWA via manifest file.</p>
                    <p>Jika ingin pengalaman app di desktop, buka eSPJ di <span class="font-bold text-slate-800">Chrome</span> atau <span class="font-bold text-slate-800">Edge</span>, lalu pilih <span class="font-bold text-slate-800">Install app</span>.</p>
                `;
                helpPrimary.textContent = "Mengerti";
                installButton.textContent = "Info Firefox";
                return;
            }

            if (isFirefox() && isAndroid() && !deferredPrompt) {
                description.textContent = "Firefox Android biasanya install lewat menu browser, bukan popup native seperti Chrome.";
                helpText.textContent = "Buka menu tiga titik Firefox lalu pilih Install atau Add to Home screen jika tersedia.";
                helpSteps.innerHTML = `
                    <p>Firefox Android: buka menu <span class="font-bold text-slate-800">⋮</span> lalu cari <span class="font-bold text-slate-800">Install</span> atau <span class="font-bold text-slate-800">Add to Home screen</span>.</p>
                    <p>Kalau opsi belum muncul, refresh `/upst` sekali setelah service worker aktif lalu cek lagi.</p>
                `;
                helpPrimary.textContent = "Lihat Panduan";
                installButton.textContent = "Cara Install";
                return;
            }

            description.textContent = deferredPrompt
                ? "Install app untuk pengalaman lebih cepat dan nyaman dari browser."
                : "Kalau popup install belum muncul, tekan tombol ini lalu ikuti panduan. Kadang perlu refresh sekali setelah service worker aktif.";
            helpText.textContent = deferredPrompt
                ? "Tekan Install untuk membuka dialog install native dari browser."
                : "Gunakan menu browser lalu pilih Install app atau Add to Home screen. Jika ini pertama kali buka `/upst`, refresh sekali lalu coba lagi.";
            helpSteps.innerHTML = `
                <p>Chrome / Edge: buka menu browser lalu pilih <span class="font-bold text-slate-800">Install app</span> atau <span class="font-bold text-slate-800">Add to Home screen</span>.</p>
                <p>Firefox Android: buka menu browser lalu pilih <span class="font-bold text-slate-800">Install</span> atau <span class="font-bold text-slate-800">Add to Home screen</span> jika tersedia.</p>
                <p>Firefox desktop: belum mendukung install PWA berbasis manifest dari web.</p>
            `;
            helpPrimary.textContent = deferredPrompt ? "Install" : "Buka Panduan";
            installButton.textContent = deferredPrompt ? "Install Sekarang" : "Cara Install";
        }

        const isDismissedThisSession = window.sessionStorage.getItem(dismissKey) === "true";

        updateManualInstallCopy();

        if (!isStandalone() && !isDismissedThisSession) {
            showInstallPrompt();
        }

        window.addEventListener("beforeinstallprompt", function (event) {
            event.preventDefault();
            deferredPrompt = event;
            updateManualInstallCopy();

            if (!isStandalone()) {
                showInstallPrompt();
            }
        });

        window.addEventListener("appinstalled", function () {
            deferredPrompt = null;
            hideInstallPrompt(false);
            closeHelpModal();
        });

        dismissButton.addEventListener("click", function () {
            hideInstallPrompt(true);
        });

        helpButton.addEventListener("click", function () {
            updateManualInstallCopy();
            openHelpModal();
        });

        helpClose.addEventListener("click", closeHelpModal);

        helpModal.addEventListener("click", function (event) {
            if (event.target === helpModal) {
                closeHelpModal();
            }
        });

        async function triggerInstall() {
            updateManualInstallCopy();

            if (!deferredPrompt) {
                openHelpModal();
                return;
            }

            deferredPrompt.prompt();
            const choice = await deferredPrompt.userChoice;
            if (choice.outcome !== "accepted") {
                showInstallPrompt();
            }
            deferredPrompt = null;
            updateManualInstallCopy();
        }

        installButton.addEventListener("click", triggerInstall);
        helpPrimary.addEventListener("click", function () {
            if (deferredPrompt) {
                closeHelpModal();
                triggerInstall();
                return;
            }

            closeHelpModal();
        });
    });
</script>