/**
 * PWA Install & Push Handler - PocketBooking Pro
 * 
 * Funktionen:
 * - Service Worker Registration
 * - Push-Subscription Management
 * - Install-Prompt Handling
 * 
 * @package SimpleBookingCalendar
 * @since 2.1.0
 */

(function($) {
    'use strict';
    
    // PWA-Konfiguration aus WordPress
    const config = window.simpbookPWAConfig || {};
    
    /**
     * Service Worker registrieren
     */
    function registerServiceWorker() {
        if (!('serviceWorker' in navigator)) {
            console.log('[Simpbook PWA] Service Workers not supported');
            return;
        }
        
        if (!config.isEnabled) {
            console.log('[Simpbook PWA] PWA not enabled');
            return;
        }
        
        // Fix Mixed Content issues
        let swUrl = config.serviceWorkerUrl || '/simpbook-sw.js';
        if (window.location.protocol === 'https:' && swUrl.indexOf('http:') === 0) {
            swUrl = swUrl.replace('http:', 'https:');
            console.log('[Simpbook PWA] Upgraded SW URL to HTTPS:', swUrl);
        }

        console.log('[Simpbook PWA] Registering Service Worker:', swUrl);
        
        navigator.serviceWorker.register(swUrl, { scope: '/' })
            .then(function(registration) {
                console.log('[Simpbook PWA] ✓ Service Worker registered, scope:', registration.scope);
                
                // ⭐ Sende aktuelle Sprache an Service Worker (für mehrsprachige Push-Notifications)
                sendLanguageToServiceWorker();
                
                // Push-Benachrichtigungen einrichten
                if (config.isPushEnabled && config.vapidPublicKey) {
                    setupPushNotifications(registration);
                }
                
                // Update-Handler
                registration.addEventListener('updatefound', function() {
                    const newWorker = registration.installing;
                    console.log('[Simpbook PWA] New Service Worker found');
                    
                    newWorker.addEventListener('statechange', function() {
                        if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                            // Neuer Service Worker verfügbar - optional User informieren
                            console.log('[Simpbook PWA] New Service Worker installed');
                        }
                    });
                });
            })
            .catch(function(error) {
                console.error('[Simpbook PWA] Service Worker registration failed:', error);
            });
        
        // Controller-Change Event
        navigator.serviceWorker.addEventListener('controllerchange', function() {
            console.log('[Simpbook PWA] Controller changed');
            // Sende Sprache auch beim Controller-Wechsel
            sendLanguageToServiceWorker();
        });
    }
    
    /**
     * Sendet die aktuelle Sprache an den Service Worker (für mehrsprachige Push-Notifications)
     */
    function sendLanguageToServiceWorker() {
        if (!navigator.serviceWorker || !navigator.serviceWorker.controller) {
            console.log('[Simpbook PWA] No SW controller yet, will send language later');
            return;
        }
        
        // Aktuelle Sprache aus Config holen (wird von PHP gesetzt)
        const currentLanguage = config.currentLanguage || 'de_DE';
        
        console.log('[Simpbook PWA] Sending language to Service Worker:', currentLanguage);
        
        navigator.serviceWorker.controller.postMessage({
            type: 'SET_LANGUAGE',
            language: currentLanguage
        });
    }
    
    /**
     * Push-Benachrichtigungen einrichten
     */
    function setupPushNotifications(registration) {
        if (!config.isPushEnabled) {
            return;
        }
        
        const $pushNavItem = $('#simpbook-pwa-push-nav-item');
        const $pushBtn = $('#simpbook-pwa-enable-push-btn');
        
        if (!$pushNavItem.length) {
            return;
        }
        
        // Sicherheits-Check
        if (!window.isSecureContext && window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
            $pushNavItem.show();
            $pushBtn.html('<span class="dashicons dashicons-warning"></span> HTTPS erforderlich');
            $pushBtn.on('click', function(e) {
                e.preventDefault();
                alert('Push-Benachrichtigungen benötigen eine sichere HTTPS-Verbindung.');
            });
            return;
        }
        
        if (!('PushManager' in window)) {
            $pushNavItem.show();
            $pushBtn.html('<span class="dashicons dashicons-warning"></span> Nicht unterstützt');
            return;
        }
        
        // Immer anzeigen, Text je nach Status ändern
        $pushNavItem.show();
        
        if (Notification.permission === 'default') {
            $pushBtn.html('<span class="dashicons dashicons-bell"></span> Push aktivieren');
            $pushBtn.off('click').on('click', function(e) {
                e.preventDefault();
                requestPushPermission(registration);
            });
            
            // 🔥 Automatische Anfrage beim ersten App-Start (nur im PWA-Modus)
            if (isStandaloneMode() && !localStorage.getItem('simpbook_pwa_push_asked')) {
                console.log('[Simpbook PWA] First app launch - auto-requesting push permission');
                // Kurze Verzögerung, damit die App zuerst lädt
                setTimeout(function() {
                    requestPushPermission(registration, true); // true = auto-subscribe
                    localStorage.setItem('simpbook_pwa_push_asked', '1');
                }, 2000);
            }
        } else if (Notification.permission === 'granted') {
            // Prüfe ob bereits eine Subscription existiert
            registration.pushManager.getSubscription().then(existingSubscription => {
                if (existingSubscription) {
                    console.log('[Simpbook PWA] Push subscription active');
                    $pushBtn.html('<span class="dashicons dashicons-yes"></span> Push aktiv');
                    $pushBtn.css('color', '#46b450'); // WordPress Green
                } else {
                    console.log('[Simpbook PWA] Permission granted, but no subscription yet');
                    $pushBtn.html('<span class="dashicons dashicons-bell"></span> Subscription erstellen');
                    $pushBtn.off('click').on('click', function(e) {
                        e.preventDefault();
                        subscribeToPush(registration);
                    });
                }
            });
        } else if (Notification.permission === 'denied') {
            $pushBtn.html('<span class="dashicons dashicons-warning"></span> Push blockiert');
            $pushBtn.css('color', '#d63638'); // WordPress Red
            $pushBtn.off('click').on('click', function(e) {
                e.preventDefault();
                alert('Push-Benachrichtigungen sind im Browser blockiert. Bitte in den App-Einstellungen freigeben.');
            });
        }
    }
    
    /**
     * Fragt nach Push-Permission
     * @param {ServiceWorkerRegistration} registration
     * @param {boolean} autoSubscribe - Automatisch subscriben nach Erlaubnis
     */
    function requestPushPermission(registration, autoSubscribe = false) {
        console.log('[Simpbook PWA] Requesting push permission (autoSubscribe:', autoSubscribe + ')');
        
        Notification.requestPermission().then(function(permission) {
            console.log('[Simpbook PWA] Permission result:', permission);
            
            if (permission === 'granted') {
                if (autoSubscribe) {
                    console.log('[Simpbook PWA] Auto-subscribing user after permission grant');
                }
                subscribeToPush(registration);
            }
            
            // UI Update
            setupPushNotifications(registration);
        }).catch(err => {
            console.error('[Simpbook PWA] Error requesting permission:', err);
            alert('Fehler bei der Berechtigungsanfrage: ' + err.message);
        });
    }
    
    /**
     * Push-Subscription erstellen und an Server senden
     */
    function subscribeToPush(registration) {
        if (!config.vapidPublicKey) {
            console.error('[Simpbook PWA] VAPID public key missing');
            alert('VAPID-Schlüssel fehlt. Bitte in den App-Einstellungen generieren.');
            return;
        }
        
        // Validiere VAPID Key Format
        const vapidPublicKey = config.vapidPublicKey.trim();
        if (vapidPublicKey.length < 80) {
            console.error('[Simpbook PWA] VAPID key too short:', vapidPublicKey.length, 'chars');
            alert('VAPID-Schlüssel ungültig (zu kurz). Bitte neu generieren.');
            return;
        }
        
        console.log('[Simpbook PWA] Subscribing to push... (Key length: ' + vapidPublicKey.length + ')');
        
        registration.pushManager.getSubscription()
            .then(function(existingSubscription) {
                if (existingSubscription) {
                    console.log('[Simpbook PWA] ✓ Already subscribed');
                    return existingSubscription;
                }
                
                // Neue Subscription erstellen
                let convertedVapidKey;
                try {
                    convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
                    console.log('[Simpbook PWA] VAPID key converted, length:', convertedVapidKey.length);
                    
                    // VAPID Key muss genau 65 bytes sein (Uncompressed P-256 public key)
                    if (convertedVapidKey.length !== 65) {
                        throw new Error('VAPID key must be 65 bytes, got ' + convertedVapidKey.length);
                    }
                } catch (err) {
                    console.error('[Simpbook PWA] Failed to convert VAPID key:', err);
                    throw new Error('VAPID-Schlüssel konvertierung fehlgeschlagen: ' + err.message);
                }
                
                return registration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: convertedVapidKey
                });
            })
            .then(function(subscription) {
                console.log('[Simpbook PWA] ✓ Push subscription created');
                
                // Subscription an Server senden
                return fetch(config.ajaxUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'simpbook_pwa_subscribe',
                        nonce: config.nonce,
                        subscription: JSON.stringify(subscription)
                    })
                });
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                if (data.success) {
                    console.log('[Simpbook PWA] ✓ Subscription saved on server');
                    // UI aktualisieren nach erfolgreicher Subscription
                    setupPushNotifications(registration);
                } else {
                    console.error('[Simpbook PWA] Failed to save subscription:', data.data);
                    alert('Fehler beim Speichern: ' + (data.data || 'Unbekannter Fehler'));
                }
            })
            .catch(function(error) {
                console.error('[Simpbook PWA] Push subscription error:', error);
                
                // Benutzerfreundliche Fehlermeldung
                let errorMsg = 'Fehler bei der Subscription: ';
                if (error.message.includes('VAPID')) {
                    errorMsg += 'VAPID-Schlüssel ungültig. Bitte in den App-Einstellungen neu generieren.';
                } else if (error.message.includes('applicationServerKey')) {
                    errorMsg += 'VAPID-Schlüssel ungültig. Bitte neu generieren.';
                } else {
                    errorMsg += error.message;
                }
                
                alert(errorMsg);
            });
    }
    
    /**
     * Helper: VAPID Key konvertieren
     */
    function urlBase64ToUint8Array(base64String) {
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
        const base64 = (base64String + padding)
            .replace(/\-/g, '+')
            .replace(/_/g, '/');
        
        const rawData = window.atob(base64);
        const outputArray = new Uint8Array(rawData.length);
        
        for (let i = 0; i < rawData.length; ++i) {
            outputArray[i] = rawData.charCodeAt(i);
        }
        
        return outputArray;
    }
    
    /**
     * Install-Prompt Handler
     */
    let deferredPrompt = null;
    
    window.addEventListener('beforeinstallprompt', function(e) {
        console.log('[Simpbook PWA] ✓ beforeinstallprompt event fired');
        
        // Prevent default
        e.preventDefault();
        deferredPrompt = e;
        
        // Optional: Install-Button anzeigen
        // $('.simpbook-pwa-install-btn').show();
    });
    
    // Install-Button Handler (falls vorhanden)
    $(document).on('click', '.simpbook-pwa-install-btn', function(e) {
        e.preventDefault();
        
        if (!deferredPrompt) {
            console.log('[Simpbook PWA] No install prompt available');
            return;
        }
        
        deferredPrompt.prompt();
        
        deferredPrompt.userChoice.then(function(choiceResult) {
            console.log('[Simpbook PWA] User choice:', choiceResult.outcome);
            
            if (choiceResult.outcome === 'accepted') {
                console.log('[Simpbook PWA] ✓ App installed');
            }
            
            deferredPrompt = null;
        });
    });
    
    // Frontend Install Button im Overlay
    $(document).on('click', '#simpbook_pwa_install_btn_frontend', function(e) {
        e.preventDefault();
        console.log('[Simpbook PWA] Frontend install button clicked');
        
        if (!deferredPrompt) {
            console.log('[Simpbook PWA] No install prompt available');
            alert('Installationsprompt nicht verfügbar. Bitte verwenden Sie die Browser-eigene Installation über das Menü.');
            return;
        }
        
        // ⭐ Button ausblenden, Loading anzeigen
        $('#simpbook_pwa_install_button_container').fadeOut(200, function() {
            $('#simpbook_pwa_install_loading').fadeIn(200);
        });
        $('#simpbook_pwa_install_skip_container').fadeOut(200);
        
        // Browser-Prompt anzeigen
        deferredPrompt.prompt();
        
        deferredPrompt.userChoice.then(function(choiceResult) {
            console.log('[Simpbook PWA] User choice:', choiceResult.outcome);
            
            if (choiceResult.outcome === 'accepted') {
                console.log('[Simpbook PWA] ✓ User accepted installation');
                // Warte auf appinstalled Event (siehe unten)
            } else {
                console.log('[Simpbook PWA] User cancelled installation');
                // Overlay schließen bei Abbruch
                $('#simpbook_pwa_install_overlay').fadeOut(300);
            }
            
            deferredPrompt = null;
        }).catch(function(err) {
            console.error('[Simpbook PWA] Error during prompt:', err);
            // Bei Fehler zurück zum Button
            $('#simpbook_pwa_install_loading').fadeOut(200, function() {
                $('#simpbook_pwa_install_button_container').fadeIn(200);
            });
            $('#simpbook_pwa_install_skip_container').fadeIn(200);
        });
    });
    
    // Überspringen Button - Overlay schließen
    $(document).on('click', '#simpbook_pwa_install_skip', function(e) {
        e.preventDefault();
        console.log('[Simpbook PWA] Install overlay skipped');
        $('#simpbook_pwa_install_overlay').fadeOut(300);
        // Merken dass User übersprungen hat (für diese Session)
        sessionStorage.setItem('simpbook_pwa_install_skipped', '1');
    });
    
    /**
     * Prüft ob die App bereits als Standalone läuft
     */
    function isStandaloneMode() {
        return window.matchMedia('(display-mode: standalone)').matches ||
               window.navigator.standalone === true ||
               document.referrer.includes('android-app://');
    }
    
    /**
     * Overlay Show/Hide Logik - NUR anzeigen wenn PWA NICHT installiert
     */
    function setupInstallOverlay() {
        const $overlay = $('#simpbook_pwa_install_overlay');
        
        if (!$overlay.length) {
            return; // Kein Overlay vorhanden
        }
        
        // ⭐ Prüfe ZUERST ob bereits installiert - dann gar nicht erst anzeigen
        if (isStandaloneMode()) {
            console.log('[Simpbook PWA] Already installed - overlay stays hidden');
            $overlay.hide(); // Sicherheitshalber
            return; // NICHT anzeigen
        }
        
        // ⭐ Prüfe ob Session-Skip gesetzt ist
        if (sessionStorage.getItem('simpbook_pwa_install_skipped') === '1') {
            console.log('[Simpbook PWA] Install skipped in this session');
            return; // NICHT anzeigen
        }
        
        // ⭐ Warte kurz auf beforeinstallprompt Event
        setTimeout(function() {
            if (!deferredPrompt) {
                console.log('[Simpbook PWA] No install prompt available - overlay stays hidden');
                return; // NICHT anzeigen wenn kein Prompt verfügbar
            }
            
            // ⭐ Overlay ANZEIGEN - PWA nicht installiert und Prompt verfügbar
            console.log('[Simpbook PWA] Showing install overlay');
            $overlay.fadeIn(300);
        }, 1000);
    }

    
    // ⭐ Nach erfolgreicher Installation (Browser-Event)
    window.addEventListener('appinstalled', function() {
        console.log('[Simpbook PWA] ✓ App installed successfully (appinstalled event)');
        
        // Success-State anzeigen mit "Fenster schließen" Button
        $('#simpbook_pwa_install_loading').fadeOut(200, function() {
            $('#simpbook_pwa_install_success').fadeIn(200);
        });
    });
    
    // "Fenster schließen" Button nach erfolgreicher Installation
    $(document).on('click', '#simpbook_pwa_install_close', function(e) {
        e.preventDefault();
        console.log('[Simpbook PWA] User closed install overlay - redirecting to settings');
        
        // Redirect zu App-Einstellungen (wir sind bereits im WP-Admin)
        const settingsUrl = 'admin.php?page=simpbook-reservierungen-einstellungen&simpbook_tab=app';
        window.location.href = settingsUrl;
    });
    
    /**
     * Initialize
     */
    $(document).ready(function() {
        console.log('[Simpbook PWA] Initializing...');
        registerServiceWorker();
        setupInstallOverlay();
    });
    
})(jQuery);
