// PWA Registration and Installation
class PWAManager {
    constructor() {
        this.deferredPrompt = null;
        this.init();
    }

    init() {
        // Register service worker
        if ('serviceWorker' in navigator) {
            this.registerServiceWorker();
        }

        // Handle install prompt
        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            this.deferredPrompt = e;
            this.showInstallButton();
        });

        // Handle app installed
        window.addEventListener('appinstalled', () => {
            console.log('PWA installed successfully');
            this.deferredPrompt = null;
            this.showToast('App installed successfully!', 'success');
        });
    }

    async registerServiceWorker() {
        try {
            const registration = await navigator.serviceWorker.register('/sw.js');
            console.log('Service Worker registered:', registration.scope);

            // Check for updates
            registration.addEventListener('updatefound', () => {
                const newWorker = registration.installing;
                newWorker.addEventListener('statechange', () => {
                    if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                        this.showUpdateNotification();
                    }
                });
            });
        } catch (error) {
            console.error('Service Worker registration failed:', error);
        }
    }

    showInstallButton() {
        // Show header install button if exists
        const headerInstallBtn = document.getElementById('installAppBtn');
        if (headerInstallBtn) {
            headerInstallBtn.classList.remove('hidden');
            headerInstallBtn.addEventListener('click', () => this.installApp());
            return;
        }

        // Fallback: Create install button if it doesn't exist
        if (document.getElementById('installBtn')) return;

        const installBtn = document.createElement('button');
        installBtn.id = 'installBtn';
        installBtn.className = 'btn btn-primary';
        installBtn.innerHTML = '📱 Install App';
        installBtn.style.cssText = `
      position: fixed;
      bottom: 100px;
      right: 20px;
      z-index: 98;
      box-shadow: var(--shadow-xl);
    `;

        installBtn.addEventListener('click', () => this.installApp());
        document.body.appendChild(installBtn);
    }

    async installApp() {
        if (!this.deferredPrompt) return;

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

        console.log(`User response to install prompt: ${outcome}`);

        if (outcome === 'accepted') {
            const installBtn = document.getElementById('installBtn');
            if (installBtn) installBtn.remove();

            const headerInstallBtn = document.getElementById('installAppBtn');
            if (headerInstallBtn) headerInstallBtn.classList.add('hidden');
        }

        this.deferredPrompt = null;
    }

    showUpdateNotification() {
        const updateBanner = document.createElement('div');
        updateBanner.className = 'toast toast-warning';
        updateBanner.innerHTML = `
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <span>New version available!</span>
        <button class="btn btn-sm btn-primary" onclick="window.location.reload()">Update</button>
      </div>
    `;

        const container = document.getElementById('toastContainer');
        if (container) {
            container.appendChild(updateBanner);
        }
    }

    showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;

        const container = document.getElementById('toastContainer');
        if (container) {
            container.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
    }
}

// Initialize PWA
const pwaManager = new PWAManager();

// Check if running as PWA
function isRunningAsPWA() {
    return window.matchMedia('(display-mode: standalone)').matches ||
        window.navigator.standalone === true;
}

// Export for use in other scripts
window.PWAManager = pwaManager;
window.isRunningAsPWA = isRunningAsPWA;
