(function() {
    // Function to check if app is installed
    console.log("✅ pwa-init.js loaded");
    function isPWAInstalled() {
        return (window.matchMedia('(display-mode: standalone)').matches)
            || (window.navigator.standalone === true);
    }

    // Only run if PWA not installed and not injected yet
    if (!isPWAInstalled() && !localStorage.getItem('pwaInjected')) {
        // Dynamically inject manifest
        const link = document.createElement('link');
        link.rel = 'manifest';
        link.href = '/manifest.json';
        document.head.appendChild(link);

        // Register Service Worker
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js')
                .then(reg => console.log('Service Worker registered:', reg.scope))
                .catch(err => console.error('SW registration failed:', err));
        }

        // Mark as injected to prevent running again
        localStorage.setItem('pwaInjected', 'true');
    }
})();
