/**
 * LandSalesPro PWA Module
 * Handles service worker registration, install prompt, and PWA features
 * Works on Android, iOS, Windows, and other platforms
 */

const LandSalesPWA = {
    deferredPrompt: null,
    swRegistration: null,
    isInstalled: false,
    isIOS: false,
    isAndroid: false,
    isStandalone: false,

    /**
     * Initialize PWA
     */
    async init() {
        console.log('[PWA] Initializing...');

        // Detect platform
        this.detectPlatform();

        // Check if already installed
        this.isInstalled = this.checkIfInstalled();

        // Register service worker
        await this.registerServiceWorker();

        // Setup install prompt
        this.setupInstallPrompt();

        // Setup update handler
        this.setupUpdateHandler();

        // Create UI elements
        this.createPWAUI();

        // Show iOS install instructions if needed
        if (this.isIOS && !this.isInstalled && !this.isStandalone) {
            this.showIOSInstallPrompt();
        }

        console.log('[PWA] Initialized - Platform:', this.getPlatformInfo());
    },

    /**
     * Detect platform
     */
    detectPlatform() {
        const ua = navigator.userAgent || navigator.vendor || window.opera;

        // iOS detection
        this.isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream;

        // Android detection
        this.isAndroid = /android/i.test(ua);

        // Standalone mode (already installed)
        this.isStandalone = window.matchMedia('(display-mode: standalone)').matches ||
                           window.navigator.standalone === true;
    },

    /**
     * Get platform info for debugging
     */
    getPlatformInfo() {
        if (this.isIOS) return 'iOS';
        if (this.isAndroid) return 'Android';
        if (/Windows/.test(navigator.userAgent)) return 'Windows';
        if (/Mac/.test(navigator.userAgent)) return 'macOS';
        if (/Linux/.test(navigator.userAgent)) return 'Linux';
        return 'Unknown';
    },

    /**
     * Check if app is installed
     */
    checkIfInstalled() {
        // Check if running in standalone mode
        if (window.matchMedia('(display-mode: standalone)').matches) {
            console.log('[PWA] Running in standalone mode');
            return true;
        }

        // Check iOS standalone
        if (window.navigator.standalone === true) {
            console.log('[PWA] Running as iOS standalone');
            return true;
        }

        return false;
    },

    /**
     * Get the correct base path
     */
    getBasePath() {
        // Check if we're on localhost
        if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
            return '/landsales';
        }
        return '';
    },

    /**
     * Register service worker
     */
    async registerServiceWorker() {
        if (!('serviceWorker' in navigator)) {
            console.log('[PWA] Service workers not supported');
            return;
        }

        try {
            const basePath = this.getBasePath();
            const swPath = basePath + '/sw.js';
            const scope = basePath + '/';

            console.log('[PWA] Registering service worker:', swPath, 'scope:', scope);

            this.swRegistration = await navigator.serviceWorker.register(swPath, {
                scope: scope
            });

            console.log('[PWA] Service worker registered successfully');

            // Wait for the service worker to be ready
            await navigator.serviceWorker.ready;
            console.log('[PWA] Service worker is ready');

            // Check for updates periodically
            setInterval(() => {
                this.swRegistration.update();
            }, 60 * 60 * 1000); // Every hour

        } catch (error) {
            console.error('[PWA] Service worker registration failed:', error);
        }
    },

    /**
     * Setup install prompt handler
     */
    setupInstallPrompt() {
        // Listen for beforeinstallprompt (Chrome, Edge, Samsung Internet)
        window.addEventListener('beforeinstallprompt', (event) => {
            console.log('[PWA] beforeinstallprompt fired');

            // Prevent Chrome 67+ from automatically showing the prompt
            event.preventDefault();

            // Store the event for later use
            this.deferredPrompt = event;

            // Show install button
            this.showInstallButton();
        });

        // Handle successful installation
        window.addEventListener('appinstalled', () => {
            console.log('[PWA] App installed successfully');
            this.deferredPrompt = null;
            this.isInstalled = true;
            localStorage.setItem('pwa_installed', 'true');
            this.hideInstallButton();
            this.hideIOSPrompt();
            this.showToast('LandSalesPro installed successfully!');
        });
    },

    /**
     * Setup update handler
     */
    setupUpdateHandler() {
        if (!this.swRegistration) return;

        this.swRegistration.addEventListener('updatefound', () => {
            const newWorker = this.swRegistration.installing;

            newWorker.addEventListener('statechange', () => {
                if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                    // New version available
                    this.showUpdateAvailable();
                }
            });
        });

        // Listen for skip waiting message
        navigator.serviceWorker.addEventListener('controllerchange', () => {
            window.location.reload();
        });
    },

    /**
     * Create PWA UI elements
     */
    createPWAUI() {
        // Don't create if already installed
        if (this.isStandalone) return;

        // Create install banner (shown at bottom for Android/Desktop)
        const banner = document.createElement('div');
        banner.id = 'pwa-install-banner';
        banner.className = 'pwa-install-banner';
        banner.innerHTML = `
            <div class="pwa-banner-content">
                <div class="pwa-banner-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
                    </svg>
                </div>
                <div class="pwa-banner-text">
                    <strong>Install LandSalesPro</strong>
                    <span>Access your data anytime, even offline!</span>
                </div>
                <button class="pwa-install-btn" onclick="LandSalesPWA.promptInstall()">
                    Install
                </button>
                <button class="pwa-dismiss-btn" onclick="LandSalesPWA.dismissBanner()">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div>
        `;
        document.body.appendChild(banner);

        // Create iOS install prompt
        const iosPrompt = document.createElement('div');
        iosPrompt.id = 'ios-install-prompt';
        iosPrompt.className = 'ios-install-prompt';
        iosPrompt.innerHTML = `
            <div class="ios-prompt-content">
                <button class="ios-prompt-close" onclick="LandSalesPWA.hideIOSPrompt()">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
                <div class="ios-prompt-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
                    </svg>
                </div>
                <h3>Install LandSalesPro</h3>
                <p>Add this app to your home screen for quick access and offline use.</p>
                <div class="ios-steps">
                    <div class="ios-step">
                        <div class="step-num">1</div>
                        <div class="step-text">Tap the <strong>Share</strong> button <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 24 24" stroke="currentColor" style="vertical-align: middle;"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" /></svg></div>
                    </div>
                    <div class="ios-step">
                        <div class="step-num">2</div>
                        <div class="step-text">Scroll and tap <strong>"Add to Home Screen"</strong></div>
                    </div>
                    <div class="ios-step">
                        <div class="step-num">3</div>
                        <div class="step-text">Tap <strong>"Add"</strong> to install</div>
                    </div>
                </div>
                <button class="ios-got-it" onclick="LandSalesPWA.hideIOSPrompt()">Got it!</button>
            </div>
        `;
        document.body.appendChild(iosPrompt);

        // Create update notification
        const updateNotif = document.createElement('div');
        updateNotif.id = 'pwa-update-notification';
        updateNotif.className = 'pwa-update-notification';
        updateNotif.innerHTML = `
            <div class="pwa-update-content">
                <span>A new version is available!</span>
                <button onclick="LandSalesPWA.updateApp()">Update Now</button>
                <button class="dismiss" onclick="this.parentElement.parentElement.classList.remove('show')">Later</button>
            </div>
        `;
        document.body.appendChild(updateNotif);

        // Create offline indicator
        const offlineIndicator = document.createElement('div');
        offlineIndicator.id = 'offline-indicator';
        offlineIndicator.className = 'offline-indicator';
        offlineIndicator.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636a9 9 0 010 12.728m0 0l-2.829-2.829m2.829 2.829L21 21M15.536 8.464a5 5 0 010 7.072m0 0l-2.829-2.829m-4.243 2.829a4.978 4.978 0 01-1.414-2.83m-1.414 5.658a9 9 0 01-2.167-9.238m7.824 2.167a1 1 0 111.414 1.414m-1.414-1.414L3 3m8.293 8.293l1.414 1.414" />
            </svg>
            <span>You're offline</span>
        `;
        document.body.appendChild(offlineIndicator);

        // Create toast container
        const toastContainer = document.createElement('div');
        toastContainer.id = 'pwa-toast-container';
        toastContainer.className = 'pwa-toast-container';
        document.body.appendChild(toastContainer);

        // Show/hide offline indicator
        this.updateOnlineStatus();
        window.addEventListener('online', () => this.updateOnlineStatus());
        window.addEventListener('offline', () => this.updateOnlineStatus());
    },

    /**
     * Show install button (for Android/Desktop)
     */
    showInstallButton() {
        // Don't show if already installed
        if (this.isInstalled || this.isStandalone) return;

        // Don't show on iOS (use separate iOS prompt)
        if (this.isIOS) return;

        // Check if dismissed recently
        if (localStorage.getItem('pwa_banner_dismissed')) {
            const dismissedTime = parseInt(localStorage.getItem('pwa_banner_dismissed'));
            if (Date.now() - dismissedTime < 24 * 60 * 60 * 1000) {
                return; // Don't show for 24 hours after dismissal
            }
        }

        const banner = document.getElementById('pwa-install-banner');
        if (banner) {
            setTimeout(() => {
                banner.classList.add('show');
            }, 2000); // Show after 2 seconds
        }
    },

    /**
     * Hide install button
     */
    hideInstallButton() {
        const banner = document.getElementById('pwa-install-banner');
        if (banner) {
            banner.classList.remove('show');
        }
    },

    /**
     * Show iOS install prompt
     */
    showIOSInstallPrompt() {
        // Check if dismissed recently
        if (localStorage.getItem('ios_prompt_dismissed')) {
            const dismissedTime = parseInt(localStorage.getItem('ios_prompt_dismissed'));
            if (Date.now() - dismissedTime < 7 * 24 * 60 * 60 * 1000) {
                return; // Don't show for 7 days after dismissal
            }
        }

        const prompt = document.getElementById('ios-install-prompt');
        if (prompt) {
            setTimeout(() => {
                prompt.classList.add('show');
            }, 3000); // Show after 3 seconds
        }
    },

    /**
     * Hide iOS prompt
     */
    hideIOSPrompt() {
        const prompt = document.getElementById('ios-install-prompt');
        if (prompt) {
            prompt.classList.remove('show');
        }
        localStorage.setItem('ios_prompt_dismissed', Date.now().toString());
    },

    /**
     * Prompt user to install
     */
    async promptInstall() {
        if (!this.deferredPrompt) {
            console.log('[PWA] No install prompt available');
            // Show manual instructions
            this.showToast('Use your browser menu to install the app');
            return;
        }

        try {
            // Show the install prompt
            this.deferredPrompt.prompt();

            // Wait for the user's response
            const { outcome } = await this.deferredPrompt.userChoice;
            console.log('[PWA] User response:', outcome);

            if (outcome === 'accepted') {
                this.showToast('Installing LandSalesPro...');
            }
        } catch (error) {
            console.error('[PWA] Install prompt error:', error);
        }

        // Clear the prompt
        this.deferredPrompt = null;
        this.hideInstallButton();
    },

    /**
     * Dismiss install banner
     */
    dismissBanner() {
        this.hideInstallButton();
        localStorage.setItem('pwa_banner_dismissed', Date.now().toString());
    },

    /**
     * Show update available notification
     */
    showUpdateAvailable() {
        const notification = document.getElementById('pwa-update-notification');
        if (notification) {
            notification.classList.add('show');
        }
    },

    /**
     * Update the app
     */
    updateApp() {
        if (this.swRegistration && this.swRegistration.waiting) {
            this.swRegistration.waiting.postMessage({ type: 'SKIP_WAITING' });
        }
    },

    /**
     * Update online/offline status indicator
     */
    updateOnlineStatus() {
        const indicator = document.getElementById('offline-indicator');
        if (indicator) {
            if (navigator.onLine) {
                indicator.classList.remove('show');
            } else {
                indicator.classList.add('show');
            }
        }
    },

    /**
     * Show toast notification
     */
    showToast(message, duration = 3000) {
        const container = document.getElementById('pwa-toast-container');
        if (!container) return;

        const toast = document.createElement('div');
        toast.className = 'pwa-toast';
        toast.textContent = message;

        container.appendChild(toast);

        // Trigger animation
        setTimeout(() => toast.classList.add('show'), 10);

        // Remove after duration
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, duration);
    },

    /**
     * Show a system notification
     */
    async showNotification(title, body) {
        if (!('Notification' in window)) return;

        if (Notification.permission === 'granted') {
            const basePath = this.getBasePath();
            new Notification(title, {
                body: body,
                icon: basePath + '/assets/icons/icon-192x192.png',
                badge: basePath + '/assets/icons/badge-72x72.png'
            });
        } else if (Notification.permission !== 'denied') {
            const permission = await Notification.requestPermission();
            if (permission === 'granted') {
                this.showNotification(title, body);
            }
        }
    },

    /**
     * Request notification permission
     */
    async requestNotificationPermission() {
        if (!('Notification' in window)) {
            console.log('[PWA] Notifications not supported');
            return false;
        }

        if (Notification.permission === 'granted') {
            return true;
        }

        if (Notification.permission !== 'denied') {
            const permission = await Notification.requestPermission();
            return permission === 'granted';
        }

        return false;
    }
};

// Additional CSS for iOS prompt and toasts
const pwaStyles = document.createElement('style');
pwaStyles.textContent = `
    /* iOS Install Prompt */
    .ios-install-prompt {
        display: none;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        border-radius: 20px 20px 0 0;
        box-shadow: 0 -10px 40px rgba(0,0,0,0.2);
        z-index: 10000;
        transform: translateY(100%);
        transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .ios-install-prompt.show {
        display: block;
        transform: translateY(0);
    }

    .ios-prompt-content {
        padding: 30px 25px;
        text-align: center;
        position: relative;
    }

    .ios-prompt-close {
        position: absolute;
        top: 15px;
        right: 15px;
        background: #f1f5f9;
        border: none;
        border-radius: 50%;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: #64748b;
    }

    .ios-prompt-icon {
        width: 80px;
        height: 80px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20px;
        color: white;
    }

    .ios-prompt-content h3 {
        margin: 0 0 10px;
        font-size: 1.3rem;
        color: #1e293b;
    }

    .ios-prompt-content > p {
        margin: 0 0 25px;
        color: #64748b;
        font-size: 0.95rem;
    }

    .ios-steps {
        text-align: left;
        margin-bottom: 25px;
    }

    .ios-step {
        display: flex;
        align-items: center;
        gap: 15px;
        padding: 12px 0;
        border-bottom: 1px solid #f1f5f9;
    }

    .ios-step:last-child {
        border-bottom: none;
    }

    .step-num {
        width: 30px;
        height: 30px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 0.9rem;
        flex-shrink: 0;
    }

    .step-text {
        color: #475569;
        font-size: 0.95rem;
    }

    .ios-got-it {
        width: 100%;
        padding: 15px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 12px;
        font-size: 1rem;
        font-weight: 600;
        cursor: pointer;
    }

    /* Toast notifications */
    .pwa-toast-container {
        position: fixed;
        bottom: 100px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 10001;
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    .pwa-toast {
        background: #1e293b;
        color: white;
        padding: 12px 24px;
        border-radius: 8px;
        font-size: 0.9rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        opacity: 0;
        transform: translateY(20px);
        transition: all 0.3s ease;
    }

    .pwa-toast.show {
        opacity: 1;
        transform: translateY(0);
    }
`;
document.head.appendChild(pwaStyles);

// Initialize PWA when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    LandSalesPWA.init();
});

// Export to window
window.LandSalesPWA = LandSalesPWA;
