(function () {
    const root = document.documentElement;
    const installButtons = document.querySelectorAll('[data-pwa-install]');
    const directInstallButtons = document.querySelectorAll('[data-pwa-install-direct]');
    const offlineBadge = document.querySelector('[data-pwa-offline]');
    const installModalElement = document.getElementById('pwaInstallModal');
    const userAgent = navigator.userAgent || '';
    let deferredPrompt = null;

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

    const browserInfo = () => {
        const isIOS = /iphone|ipad|ipod/i.test(userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
        const isAndroid = /android/i.test(userAgent);
        const isEdge = /edg/i.test(userAgent);
        const isOpera = /opr|opera/i.test(userAgent);
        const isFirefox = /firefox|fxios/i.test(userAgent);
        const isSamsung = /samsungbrowser/i.test(userAgent);
        const isChrome = /chrome|crios|chromium/i.test(userAgent) && !isEdge && !isOpera && !isSamsung;
        const isSafari = /safari/i.test(userAgent) && !isChrome && !isEdge && !isOpera && !isAndroid;

        if (isIOS && isSafari) {
            return {
                name: 'iPhone/iPad Safari',
                status: 'Apple browsers install PWAs through the Share menu.',
                note: 'Tap Share, choose Add to Home Screen, then tap Add.',
                steps: ['Tap the Share button in Safari.', 'Choose Add to Home Screen.', 'Tap Add and open the app from your home screen.'],
                nativePrompt: false,
            };
        }

        if (isIOS) {
            return {
                name: 'iPhone/iPad browser',
                status: 'On iOS, installation is usually handled through Safari.',
                note: 'If Add to Home Screen is not visible here, open this same link in Safari.',
                steps: ['Open this website in Safari.', 'Tap Share.', 'Choose Add to Home Screen and tap Add.'],
                nativePrompt: false,
            };
        }

        if (isFirefox) {
            return {
                name: 'Firefox',
                status: 'Firefox has limited PWA install support.',
                note: 'If your Firefox version does not show Add to Home Screen, use Chrome, Edge, Brave, or Safari for installation.',
                steps: ['Open the browser menu.', 'Look for Add to Home Screen or Install if available.', 'If unavailable, bookmark the website or open it in a PWA-supported browser.'],
                nativePrompt: false,
            };
        }

        if (isAndroid) {
            return {
                name: isSamsung ? 'Samsung Internet on Android' : 'Android browser',
                status: deferredPrompt ? 'This browser can install the app directly.' : 'Use the browser menu if the direct prompt is not available.',
                note: 'The installed app will appear on the phone home screen.',
                steps: deferredPrompt
                    ? ['Click Install now.', 'Confirm the browser installation prompt.', 'Open NewKipp Microfinance Solution from your home screen.']
                    : ['Open the browser menu.', 'Choose Install app or Add to Home screen.', 'Confirm and open the app from your home screen.'],
                nativePrompt: Boolean(deferredPrompt),
            };
        }

        if (isChrome || isEdge || isOpera || isSamsung) {
            return {
                name: isEdge ? 'Microsoft Edge' : (isOpera ? 'Opera' : (isSamsung ? 'Samsung Internet' : 'Chrome/Chromium browser')),
                status: deferredPrompt ? 'This browser can install the app directly.' : 'Use the install icon or browser menu if the direct prompt is not available yet.',
                note: 'If the install option does not appear, confirm the site is served over HTTPS when hosted online.',
                steps: deferredPrompt
                    ? ['Click Install now.', 'Confirm the install prompt.', 'Launch the app from your desktop or home screen.']
                    : ['Look for the install icon in the address bar.', 'Or open the browser menu and choose Install app.', 'Confirm and launch the app.'],
                nativePrompt: Boolean(deferredPrompt),
            };
        }

        if (isSafari) {
            return {
                name: 'Safari',
                status: 'Safari supports Add to Home Screen on Apple devices, but may not show a native install prompt.',
                note: 'Use the Share menu on iPhone or iPad. On Mac, use the Dock/Add to Dock option where available.',
                steps: ['Open the Share menu.', 'Choose Add to Home Screen or Add to Dock where available.', 'Open the app from the home screen or Dock.'],
                nativePrompt: false,
            };
        }

        return {
            name: 'Your browser',
            status: deferredPrompt ? 'This browser can install the app directly.' : 'Manual installation may be required in this browser.',
            note: 'Chrome, Edge, Brave, Opera, and Android browsers usually provide the best PWA install support.',
            steps: deferredPrompt
                ? ['Click Install now.', 'Confirm the install prompt.', 'Open the app from your device.']
                : ['Open the browser menu.', 'Look for Install app or Add to Home Screen.', 'If unavailable, use a PWA-supported browser.'],
            nativePrompt: Boolean(deferredPrompt),
        };
    };

    const setOfflineState = () => {
        const offline = !navigator.onLine;
        document.body.classList.toggle('pwa-is-offline', offline);
        if (offlineBadge) {
            offlineBadge.hidden = !offline;
        }
    };

    const updateInstallButtons = () => {
        const installed = isStandalone();
        document.body.classList.toggle('pwa-install-ready', Boolean(deferredPrompt));
        document.body.classList.toggle('pwa-installed', installed);

        installButtons.forEach((button) => {
            const label = button.querySelector('[data-pwa-install-label]');
            if (label) {
                label.textContent = installed ? 'App installed' : 'Install app';
            }
            button.setAttribute('aria-label', installed ? 'App installed' : 'Install mobile app');
        });
    };

    const renderInstallHelp = () => {
        if (!installModalElement) {
            return;
        }

        const installed = isStandalone();
        const info = installed
            ? {
                name: 'Installed app mode',
                status: 'You are already using NewKipp Microfinance Solution like an installed app.',
                note: 'You can keep using this window or open it from your device home screen.',
                steps: ['Open the app icon from your device.', 'Sign in as super admin, tenant, merchant, staff, or member.', 'Continue your daily operations.'],
                nativePrompt: false,
            }
            : browserInfo();

        const platform = installModalElement.querySelector('[data-pwa-platform]');
        const status = installModalElement.querySelector('[data-pwa-status]');
        const note = installModalElement.querySelector('[data-pwa-note]');
        const instructions = installModalElement.querySelector('[data-pwa-instructions]');

        if (platform) {
            platform.textContent = info.name;
        }

        if (status) {
            status.textContent = info.status;
        }

        if (note) {
            note.textContent = info.note;
        }

        if (instructions) {
            instructions.innerHTML = '';
            info.steps.forEach((step) => {
                const item = document.createElement('li');
                item.textContent = step;
                instructions.appendChild(item);
            });
        }

        directInstallButtons.forEach((button) => {
            button.hidden = installed || !info.nativePrompt;
        });
    };

    const showInstallHelp = () => {
        renderInstallHelp();

        if (installModalElement && window.bootstrap) {
            window.bootstrap.Modal.getOrCreateInstance(installModalElement).show();
            return;
        }

        window.location.href = root.dataset.mobileAppUrl || '/mobile-app';
    };

    const requestInstall = async () => {
        if (isStandalone()) {
            showInstallHelp();
            return;
        }

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

        deferredPrompt.prompt();
        await deferredPrompt.userChoice;
        deferredPrompt = null;
        updateInstallButtons();
    };

    if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            navigator.serviceWorker.register(root.dataset.serviceWorker || '/sw.js').catch(() => {});
        });
    }

    window.addEventListener('beforeinstallprompt', (event) => {
        event.preventDefault();
        deferredPrompt = event;
        updateInstallButtons();
        renderInstallHelp();
    });

    window.addEventListener('appinstalled', () => {
        deferredPrompt = null;
        updateInstallButtons();
        renderInstallHelp();
    });

    installButtons.forEach((button) => {
        button.addEventListener('click', requestInstall);
    });

    directInstallButtons.forEach((button) => {
        button.addEventListener('click', requestInstall);
    });

    document.querySelectorAll('[data-mobile-menu-toggle]').forEach((button) => {
        button.addEventListener('click', () => document.body.classList.add('mobile-menu-open'));
    });

    document.querySelectorAll('[data-mobile-menu-close]').forEach((button) => {
        button.addEventListener('click', () => document.body.classList.remove('mobile-menu-open'));
    });

    document.querySelectorAll('.sidebar .nav-link').forEach((link) => {
        link.addEventListener('click', () => document.body.classList.remove('mobile-menu-open'));
    });

    updateInstallButtons();
    renderInstallHelp();
    setOfflineState();
    window.addEventListener('online', setOfflineState);
    window.addEventListener('offline', setOfflineState);
})();
