/**
 * PWA Navigation JavaScript - PocketBooking Pro
 * 
 * Handhabt die PWA-Navigation:
 * - Hamburger Menu Toggle
 * - Back-Button Navigation
 * - Bottom Nav Active States
 * - Session Checks
 *
 * @package SimpleBookingCalendar
 * @since 1.2.0
 */

(function() {
    'use strict';

    // PWA Navigation Controller
    const simpbookPWA = {
        
        // DOM Elements
        elements: {
            menu: null,
            overlay: null,
            menuBtn: null,
            backBtn: null,
            bottomNav: null
        },

        /**
         * Initialize PWA Navigation
         */
        init: function() {
            this.cacheElements();
            this.bindEvents();
            this.updateActiveNavItem();
            this.checkSession();
            
            // Session Check alle 5 Minuten
            setInterval(() => this.checkSession(), 5 * 60 * 1000);
        },

        /**
         * Cache DOM Elements
         */
        cacheElements: function() {
            this.elements.menu = document.querySelector('.simpbook-pwa-menu');
            this.elements.overlay = document.querySelector('.simpbook-pwa-overlay');
            this.elements.menuBtn = document.querySelector('.simpbook-pwa-menu-btn');
            this.elements.backBtn = document.querySelector('.simpbook-pwa-back-btn');
            this.elements.bottomNav = document.querySelector('.simpbook-pwa-bottom-nav');
        },

        /**
         * Bind Event Handlers
         */
        bindEvents: function() {
            // Menu Toggle
            if (this.elements.menuBtn) {
                this.elements.menuBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.toggleMenu();
                });
            }

            // Overlay Click schließt Menu
            if (this.elements.overlay) {
                this.elements.overlay.addEventListener('click', () => {
                    this.closeMenu();
                });
            }

            // Back Button
            if (this.elements.backBtn) {
                this.elements.backBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.goBack();
                });
            }

            // Escape Key schließt Menu
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && this.isMenuOpen()) {
                    this.closeMenu();
                }
            });

            // Swipe to close menu (Touch)
            if (this.elements.menu) {
                let touchStartX = 0;
                let touchEndX = 0;

                this.elements.menu.addEventListener('touchstart', (e) => {
                    touchStartX = e.changedTouches[0].screenX;
                }, { passive: true });

                this.elements.menu.addEventListener('touchend', (e) => {
                    touchEndX = e.changedTouches[0].screenX;
                    const swipeDistance = touchEndX - touchStartX;
                    
                    // Swipe nach rechts schließt Menu
                    if (swipeDistance > 50) {
                        this.closeMenu();
                    }
                }, { passive: true });
            }

            // Logout Handler
            const logoutLinks = document.querySelectorAll('.simpbook-pwa-logout');
            logoutLinks.forEach(link => {
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    this.handleLogout();
                });
            });

            // Ripple Effect für Touch-Feedback
            this.initRippleEffect();
        },

        /**
         * Toggle Menu Open/Close
         */
        toggleMenu: function() {
            if (this.isMenuOpen()) {
                this.closeMenu();
            } else {
                this.openMenu();
            }
        },

        /**
         * Open Menu
         */
        openMenu: function() {
            if (this.elements.menu && this.elements.overlay) {
                this.elements.menu.classList.add('open');
                this.elements.overlay.classList.add('open');
                document.body.style.overflow = 'hidden';
                
                // Focus erstes Menu Item für Accessibility
                const firstLink = this.elements.menu.querySelector('a');
                if (firstLink) {
                    firstLink.focus();
                }
            }
        },

        /**
         * Close Menu
         */
        closeMenu: function() {
            if (this.elements.menu && this.elements.overlay) {
                this.elements.menu.classList.remove('open');
                this.elements.overlay.classList.remove('open');
                document.body.style.overflow = '';
                
                // Focus zurück zum Menu Button
                if (this.elements.menuBtn) {
                    this.elements.menuBtn.focus();
                }
            }
        },

        /**
         * Check if Menu is Open
         */
        isMenuOpen: function() {
            return this.elements.menu && this.elements.menu.classList.contains('open');
        },

        /**
         * Go Back Navigation
         */
        goBack: function() {
            if (window.history.length > 1) {
                window.history.back();
            } else {
                // Fallback: Zum Dashboard
                window.location.href = this.getPwaUrl('dashboard');
            }
        },

        /**
         * Update Active Navigation Item
         */
        updateActiveNavItem: function() {
            const currentUrl = window.location.href;
            const navItems = document.querySelectorAll('.simpbook-pwa-nav-item');
            const menuItems = document.querySelectorAll('.simpbook-pwa-menu-nav a');

            // Bottom Nav
            navItems.forEach(item => {
                const href = item.getAttribute('href');
                if (href && currentUrl.includes(href.split('?')[1] || href)) {
                    item.classList.add('active');
                } else {
                    item.classList.remove('active');
                }
            });

            // Menu Nav
            menuItems.forEach(item => {
                const href = item.getAttribute('href');
                if (href && currentUrl.includes(href.split('?')[1] || href)) {
                    item.classList.add('active');
                } else {
                    item.classList.remove('active');
                }
            });

            // Spezieller Check für Dashboard (Start)
            if (currentUrl.includes('page=simpbook-dashboard') || 
                currentUrl.includes('page=simple-booking-calendar')) {
                const homeNav = document.querySelector('.simpbook-pwa-nav-item[href*="dashboard"]');
                if (homeNav) homeNav.classList.add('active');
            }
        },

        /**
         * Get PWA URL
         */
        getPwaUrl: function(page) {
            const baseUrl = window.simpbookPWAConfig?.adminUrl || '/wp-admin/admin.php';
            const pwaParam = '&pwa=1';
            
            const pages = {
                'dashboard': 'page=simpbook-dashboard',
                'kalender': 'page=simpbook-kalender',
                'reservierungen': 'page=simpbook-reservierungen',
                'neue-reservierung': 'page=simpbook-neue-reservierung',
                'dienstleistungen': 'page=simpbook-dienstleistungen',
                'mitarbeiter': 'page=simpbook-mitarbeiter',
                'statistiken': 'page=simpbook-statistiken',
                'einstellungen': 'page=simpbook-einstellungen'
            };

            return baseUrl + '?' + (pages[page] || pages['dashboard']) + pwaParam;
        },

        /**
         * Check Session Status
         */
        checkSession: function() {
            if (typeof window.simpbookPWAConfig === 'undefined') {
                return;
            }

            fetch(window.simpbookPWAConfig.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'simpbook_check_pwa_session',
                    nonce: window.simpbookPWAConfig.nonce
                })
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    // Session abgelaufen - zum Login
                    this.showSessionExpiredMessage();
                }
            })
            .catch(error => {
                console.error('PWA Session Check Error:', error);
            });
        },

        /**
         * Show Session Expired Message
         */
        showSessionExpiredMessage: function() {
            const message = window.simpbookPWAConfig?.i18n?.sessionExpired || 
                           'Ihre Sitzung ist abgelaufen. Bitte melden Sie sich erneut an.';
            
            if (confirm(message)) {
                window.location.href = window.simpbookPWAConfig?.loginUrl || '/wp-login.php';
            }
        },

        /**
         * Handle Logout
         */
        handleLogout: function() {
            const confirmMessage = window.simpbookPWAConfig?.i18n?.confirmLogout || 
                                  'Möchten Sie sich wirklich abmelden?';
            
            if (!confirm(confirmMessage)) {
                return;
            }

            // Show Loading
            this.showLoading();

            fetch(window.simpbookPWAConfig.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'simpbook_pwa_logout',
                    nonce: window.simpbookPWAConfig.nonce
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = data.data.redirect || '/wp-login.php';
                } else {
                    this.hideLoading();
                    alert(data.data?.message || 'Logout fehlgeschlagen');
                }
            })
            .catch(error => {
                this.hideLoading();
                console.error('PWA Logout Error:', error);
                alert('Ein Fehler ist aufgetreten');
            });
        },

        /**
         * Show Loading Bar
         */
        showLoading: function() {
            let loading = document.querySelector('.simpbook-pwa-loading');
            if (!loading) {
                loading = document.createElement('div');
                loading.className = 'simpbook-pwa-loading';
                document.body.appendChild(loading);
            }
            loading.style.display = 'block';
        },

        /**
         * Hide Loading Bar
         */
        hideLoading: function() {
            const loading = document.querySelector('.simpbook-pwa-loading');
            if (loading) {
                loading.style.display = 'none';
            }
        },

        /**
         * Initialize Ripple Effect for Touch Feedback
         */
        initRippleEffect: function() {
            const rippleElements = document.querySelectorAll(
                '.simpbook-pwa-nav-item, .simpbook-pwa-back-btn, .simpbook-pwa-menu-btn'
            );

            rippleElements.forEach(element => {
                element.addEventListener('click', function(e) {
                    const ripple = document.createElement('span');
                    const rect = this.getBoundingClientRect();
                    const size = Math.max(rect.width, rect.height);
                    const x = e.clientX - rect.left - size / 2;
                    const y = e.clientY - rect.top - size / 2;

                    ripple.style.cssText = `
                        position: absolute;
                        width: ${size}px;
                        height: ${size}px;
                        left: ${x}px;
                        top: ${y}px;
                        background: rgba(255, 255, 255, 0.3);
                        border-radius: 50%;
                        transform: scale(0);
                        animation: ripple 0.6s ease-out;
                        pointer-events: none;
                    `;

                    this.style.position = 'relative';
                    this.style.overflow = 'hidden';
                    this.appendChild(ripple);

                    setTimeout(() => ripple.remove(), 600);
                });
            });

            // Add ripple keyframes if not exists
            if (!document.querySelector('#simpbook-ripple-styles')) {
                const style = document.createElement('style');
                style.id = 'simpbook-ripple-styles';
                style.textContent = `
                    @keyframes ripple {
                        to {
                            transform: scale(4);
                            opacity: 0;
                        }
                    }
                `;
                document.head.appendChild(style);
            }
        },

        /**
         * Navigate to Page
         */
        navigateTo: function(page) {
            this.showLoading();
            window.location.href = this.getPwaUrl(page);
        },

        /**
         * Show Toast Notification
         */
        showToast: function(message, type = 'info', duration = 3000) {
            const toast = document.createElement('div');
            toast.className = `simpbook-pwa-toast simpbook-pwa-toast-${type}`;
            toast.textContent = message;
            toast.style.cssText = `
                position: fixed;
                bottom: 80px;
                left: 50%;
                transform: translateX(-50%);
                padding: 12px 24px;
                background: ${type === 'error' ? '#d32f2f' : type === 'success' ? '#388e3c' : '#333'};
                color: white;
                border-radius: 8px;
                z-index: 100001;
                font-size: 14px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                animation: toast-in 0.3s ease;
            `;

            // Add animation keyframes
            if (!document.querySelector('#simpbook-toast-styles')) {
                const style = document.createElement('style');
                style.id = 'simpbook-toast-styles';
                style.textContent = `
                    @keyframes toast-in {
                        from { opacity: 0; transform: translateX(-50%) translateY(20px); }
                        to { opacity: 1; transform: translateX(-50%) translateY(0); }
                    }
                    @keyframes toast-out {
                        from { opacity: 1; transform: translateX(-50%) translateY(0); }
                        to { opacity: 0; transform: translateX(-50%) translateY(20px); }
                    }
                `;
                document.head.appendChild(style);
            }

            document.body.appendChild(toast);

            setTimeout(() => {
                toast.style.animation = 'toast-out 0.3s ease forwards';
                setTimeout(() => toast.remove(), 300);
            }, duration);
        }
    };

    // Initialize on DOM Ready - robuste Methode
    function initWhenReady() {
        // Warten auf PWA Navigation Elemente
        const checkElements = function() {
            const menu = document.querySelector('.simpbook-pwa-menu');
            const menuBtn = document.querySelector('.simpbook-pwa-menu-btn');
            
            if (menu && menuBtn) {
                simpbookPWA.init();
                console.log('SimplBook PWA Navigation initialized');
            } else {
                // Nochmal versuchen nach kurzer Verzögerung
                setTimeout(checkElements, 100);
            }
        };
        
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', checkElements);
        } else {
            checkElements();
        }
    }
    
    initWhenReady();

    // Expose to global scope sofort
    window.simpbookPWA = simpbookPWA;

})();
