let deferredInstallPrompt = null;

const currentScript =
    document.currentScript ||
    document.querySelector('script[src$="pwa.js"], script[src*="/pwa.js"]');

const appBase = currentScript
    ? new URL('./', currentScript.src).href
    : new URL('./', window.location.href).href;

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker
            .register(appBase + 'service-worker.js', { scope: appBase })
            .catch(error => {
                console.log('Service Worker registration failed:', error);
            });
    });
}

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

function createInstallButton() {
    if (document.getElementById('pwaInstallBtn') || isStandaloneMode()) return;

    const button = document.createElement('button');
    button.id = 'pwaInstallBtn';
    button.type = 'button';
    button.textContent = 'Install App';

    Object.assign(button.style, {
        position: 'fixed',
        right: '16px',
        bottom: '16px',
        zIndex: '9999',
        border: '0',
        borderRadius: '999px',
        padding: '12px 18px',
        fontWeight: '800',
        color: '#ffffff',
        background: 'linear-gradient(135deg, #0284c7, #10b981)',
        boxShadow: '0 16px 40px rgba(2, 132, 199, 0.28)',
        cursor: 'pointer'
    });

    button.addEventListener('click', async () => {
        if (!deferredInstallPrompt) return;

        deferredInstallPrompt.prompt();
        await deferredInstallPrompt.userChoice;

        deferredInstallPrompt = null;
        button.remove();
    });

    document.body.appendChild(button);
}

window.addEventListener('beforeinstallprompt', event => {
    event.preventDefault();
    deferredInstallPrompt = event;
    createInstallButton();
});

window.addEventListener('appinstalled', () => {
    deferredInstallPrompt = null;

    const button = document.getElementById('pwaInstallBtn');
    if (button) button.remove();
});
