/**
 * Universal PWA Installation Script
 * Works on ALL devices and browsers
 */

class PWAInstaller {
    constructor() {
        this.deferredPrompt = null;
        this.isIOS = this.detectIOS();
        this.isStandalone = this.detectStandalone();
        this.isAndroid = this.detectAndroid();
        this.isDesktop = this.detectDesktop();
        
        this.init();
    }

    init() {
        this.setupInstallButton();
        this.setupEventListeners();
        this.showInstallInstructions();
    }

    detectIOS() {
        return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    }

    detectAndroid() {
        return /Android/.test(navigator.userAgent);
    }

    detectDesktop() {
        return !this.isIOS && !this.isAndroid;
    }

    detectBrowser() {
        const userAgent = navigator.userAgent;
        if (userAgent.includes('Chrome')) return 'chrome';
        if (userAgent.includes('Firefox')) return 'firefox';
        if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) return 'safari';
        if (userAgent.includes('Edge')) return 'edge';
        return 'unknown';
    }

    detectStandalone() {
        return window.matchMedia('(display-mode: standalone)').matches ||
               window.navigator.standalone === true ||
               document.referrer.includes('android-app://');
    }

    setupInstallButton() {
        const installBtn = document.getElementById('pwa-install-btn');
        if (!installBtn) return;

        // Show install button for all devices (universal compatibility)
        installBtn.style.display = 'block';
        installBtn.addEventListener('click', () => this.handleInstall());
        
        // Add visual indicator for different platforms
        this.updateInstallButtonForPlatform();
    }

    updateInstallButtonForPlatform() {
        const installBtn = document.getElementById('pwa-install-btn');
        if (!installBtn) return;

        const browser = this.detectBrowser();
        const platform = this.isIOS ? 'ios' : this.isAndroid ? 'android' : 'desktop';
        
        // Add platform-specific styling
        installBtn.setAttribute('data-platform', platform);
        installBtn.setAttribute('data-browser', browser);
        
        // Add tooltip with platform-specific instructions
        installBtn.title = this.getInstallTooltip(platform, browser);
    }

    getInstallTooltip(platform, browser) {
        if (platform === 'ios') {
            return 'Tap Share → Add to Home Screen';
        } else if (platform === 'android') {
            return 'Tap Menu → Add to Home Screen';
        } else {
            if (browser === 'chrome' || browser === 'edge') {
                return 'Click the install icon in the address bar';
            } else if (browser === 'firefox') {
                return 'Click Menu → Install';
            } else {
                return 'Install this app to your device';
            }
        }
    }

    setupEventListeners() {
        // Standard PWA install prompt
        window.addEventListener('beforeinstallprompt', (e) => {
            console.log('PWA install prompt available');
            e.preventDefault();
            this.deferredPrompt = e;
            this.updateInstallButton('ready');
        });

        // PWA installed event
        window.addEventListener('appinstalled', () => {
            console.log('PWA was installed');
            this.updateInstallButton('installed');
        });

        // Check if already installed
        if (this.isStandalone) {
            this.updateInstallButton('installed');
        }
    }

    handleInstall() {
        if (this.deferredPrompt) {
            // Standard PWA install (Chrome, Edge, etc.)
            this.deferredPrompt.prompt();
            this.deferredPrompt.userChoice.then((choiceResult) => {
                if (choiceResult.outcome === 'accepted') {
                    console.log('User accepted the install prompt');
                } else {
                    console.log('User dismissed the install prompt');
                }
                this.deferredPrompt = null;
            });
        } else if (this.isIOS) {
            // iOS Safari - show manual instructions
            this.showIOSInstructions();
        } else if (this.isAndroid) {
            // Android - show manual instructions
            this.showAndroidInstructions();
        } else {
            // Desktop - show manual instructions
            this.showDesktopInstructions();
        }
    }

    updateInstallButton(state) {
        const installBtn = document.getElementById('pwa-install-btn');
        if (!installBtn) return;

        switch (state) {
            case 'ready':
                installBtn.innerHTML = '<i class="fas fa-download"></i> Install App';
                installBtn.style.display = 'block';
                break;
            case 'installed':
                installBtn.innerHTML = '<i class="fas fa-check"></i> Installed';
                installBtn.style.display = 'none';
                break;
            case 'loading':
                installBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Installing...';
                break;
        }
    }

    showInstallInstructions() {
        // Create instruction modal if it doesn't exist
        if (!document.getElementById('install-instructions-modal')) {
            this.createInstructionModal();
        }
    }

    createInstructionModal() {
        const modal = document.createElement('div');
        modal.id = 'install-instructions-modal';
        modal.className = 'install-modal';
        modal.innerHTML = `
            <div class="install-modal-content">
                <div class="install-modal-header">
                    <h2><i class="fas fa-mobile-alt"></i> Install Al Mirag Poultry App</h2>
                    <span class="close-install-modal">&times;</span>
                </div>
                <div class="install-modal-body">
                    <div class="install-instructions">
                        <div class="instruction-step ios-instructions" style="display: none;">
                            <h3><i class="fab fa-apple"></i> iPhone/iPad Instructions</h3>
                            <ol>
                                <li>Tap the <strong>Share</strong> button <i class="fas fa-share"></i> at the bottom of Safari</li>
                                <li>Scroll down and tap <strong>"Add to Home Screen"</strong></li>
                                <li>Tap <strong>"Add"</strong> to confirm</li>
                                <li>The app will appear on your home screen!</li>
                            </ol>
                        </div>
                        
                        <div class="instruction-step android-instructions" style="display: none;">
                            <h3><i class="fab fa-android"></i> Android Instructions</h3>
                            <ol>
                                <li>Tap the <strong>Menu</strong> button <i class="fas fa-ellipsis-v"></i> in Chrome</li>
                                <li>Select <strong>"Add to Home screen"</strong> or <strong>"Install app"</strong></li>
                                <li>Tap <strong>"Add"</strong> or <strong>"Install"</strong> to confirm</li>
                                <li>The app will appear on your home screen!</li>
                            </ol>
                        </div>
                        
                        <div class="instruction-step desktop-instructions" style="display: none;">
                            <h3><i class="fas fa-desktop"></i> Desktop Instructions</h3>
                            <div class="browser-instructions">
                                <div class="browser-chrome">
                                    <h4><i class="fab fa-chrome"></i> Chrome/Edge</h4>
                                    <ol>
                                        <li>Look for the install icon <i class="fas fa-plus"></i> in the address bar</li>
                                        <li>Click the install icon</li>
                                        <li>Click "Install" in the popup</li>
                                        <li>The app will be added to your applications!</li>
                                    </ol>
                                </div>
                                <div class="browser-firefox">
                                    <h4><i class="fab fa-firefox"></i> Firefox</h4>
                                    <ol>
                                        <li>Click the menu button (three lines) in the top right</li>
                                        <li>Select "Install" from the menu</li>
                                        <li>Click "Allow" in the permission dialog</li>
                                        <li>The app will be added to your applications!</li>
                                    </ol>
                                </div>
                                <div class="browser-safari">
                                    <h4><i class="fab fa-safari"></i> Safari</h4>
                                    <ol>
                                        <li>Go to File → "Add to Dock"</li>
                                        <li>Or use the Share button → "Add to Dock"</li>
                                        <li>The app will be added to your dock!</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // Add modal styles
        const style = document.createElement('style');
        style.textContent = `
            .install-modal {
                display: none;
                position: fixed;
                z-index: 10000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.8);
                backdrop-filter: blur(5px);
            }
            
            .install-modal-content {
                background: white;
                margin: 5% auto;
                padding: 0;
                border-radius: 20px;
                width: 90%;
                max-width: 500px;
                box-shadow: 0 20px 40px rgba(0,0,0,0.3);
                animation: modalSlideIn 0.3s ease-out;
            }
            
            @keyframes modalSlideIn {
                from { opacity: 0; transform: translateY(-50px); }
                to { opacity: 1; transform: translateY(0); }
            }
            
            .install-modal-header {
                background: linear-gradient(135deg, #2E7D32, #4CAF50);
                color: white;
                padding: 1.5rem;
                border-radius: 20px 20px 0 0;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            
            .install-modal-header h2 {
                margin: 0;
                font-size: 1.3rem;
            }
            
            .close-install-modal {
                color: white;
                font-size: 2rem;
                font-weight: bold;
                cursor: pointer;
                transition: color 0.3s ease;
            }
            
            .close-install-modal:hover {
                color: #FFD700;
            }
            
            .install-modal-body {
                padding: 2rem;
            }
            
            .instruction-step h3 {
                color: #2E7D32;
                margin-bottom: 1rem;
                display: flex;
                align-items: center;
                gap: 0.5rem;
            }
            
            .instruction-step ol {
                padding-left: 1.5rem;
            }
            
            .instruction-step li {
                margin-bottom: 0.8rem;
                line-height: 1.6;
            }
            
            .instruction-step strong {
                color: #2E7D32;
            }
            
            .browser-instructions {
                display: flex;
                flex-direction: column;
                gap: 1.5rem;
            }
            
            .browser-chrome, .browser-firefox, .browser-safari {
                background: #f8f9fa;
                padding: 1rem;
                border-radius: 10px;
                border-left: 4px solid #2E7D32;
            }
            
            .browser-chrome h4, .browser-firefox h4, .browser-safari h4 {
                margin: 0 0 0.8rem 0;
                color: #2E7D32;
                display: flex;
                align-items: center;
                gap: 0.5rem;
            }
            
            .browser-chrome ol, .browser-firefox ol, .browser-safari ol {
                margin: 0;
                padding-left: 1.2rem;
            }
            
            .browser-chrome li, .browser-firefox li, .browser-safari li {
                margin-bottom: 0.5rem;
                line-height: 1.5;
            }
        `;
        
        document.head.appendChild(style);
        document.body.appendChild(modal);

        // Add event listeners
        modal.querySelector('.close-install-modal').addEventListener('click', () => {
            modal.style.display = 'none';
        });

        window.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.style.display = 'none';
            }
        });
    }

    showIOSInstructions() {
        const modal = document.getElementById('install-instructions-modal');
        const iosInstructions = modal.querySelector('.ios-instructions');
        const androidInstructions = modal.querySelector('.android-instructions');
        const desktopInstructions = modal.querySelector('.desktop-instructions');
        
        iosInstructions.style.display = 'block';
        androidInstructions.style.display = 'none';
        desktopInstructions.style.display = 'none';
        modal.style.display = 'block';
    }

    showAndroidInstructions() {
        const modal = document.getElementById('install-instructions-modal');
        const iosInstructions = modal.querySelector('.ios-instructions');
        const androidInstructions = modal.querySelector('.android-instructions');
        const desktopInstructions = modal.querySelector('.desktop-instructions');
        
        iosInstructions.style.display = 'none';
        androidInstructions.style.display = 'block';
        desktopInstructions.style.display = 'none';
        modal.style.display = 'block';
    }

    showDesktopInstructions() {
        const modal = document.getElementById('install-instructions-modal');
        const iosInstructions = modal.querySelector('.ios-instructions');
        const androidInstructions = modal.querySelector('.android-instructions');
        const desktopInstructions = modal.querySelector('.desktop-instructions');
        
        iosInstructions.style.display = 'none';
        androidInstructions.style.display = 'none';
        desktopInstructions.style.display = 'block';
        modal.style.display = 'block';
    }
}

// Initialize PWA installer when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new PWAInstaller();
});

// Also initialize if DOM is already loaded
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        new PWAInstaller();
    });
} else {
    new PWAInstaller();
}
