<?php if (!isset($hideFooter) || !$hideFooter): ?>
<!-- Global Toast Container -->
<div class="fixed bottom-24 left-1/2 transform -translate-x-1/2 z-50" id="toast-container"></div>

<?php if (isAuthenticated()): ?>
<!-- Bottom Navigation (Mobile Only) -->
<?php if (!isset($hideBottomNav) || !$hideBottomNav): ?>
<footer class="fixed bottom-0 left-0 right-0 bg-background-light dark:bg-background-dark border-t border-slate-200 dark:border-slate-800 z-40">
    <div class="flex gap-1 px-2 pb-safe pt-2 max-w-md mx-auto">
        <a class="flex flex-1 flex-col items-center justify-center gap-1 <?php echo $activePage === 'home' ? 'text-primary' : 'text-slate-500 dark:text-slate-400'; ?> py-2" href="index.php">
            <span class="material-symbols-outlined <?php echo $activePage === 'home' ? 'font-variation-settings: \'FILL\' 1;' : ''; ?>">home</span>
            <p class="text-[10px] font-medium leading-normal">Home</p>
        </a>
        <a class="flex flex-1 flex-col items-center justify-center gap-1 <?php echo $activePage === 'chats' ? 'text-primary' : 'text-slate-500 dark:text-slate-400'; ?> py-2" href="chats.php">
            <span class="material-symbols-outlined <?php echo $activePage === 'chats' ? 'font-variation-settings: \'FILL\' 1;' : ''; ?>">chat_bubble</span>
            <p class="text-[10px] font-medium leading-normal">Chats</p>
        </a>
        <a class="flex flex-1 flex-col items-center justify-center gap-1 <?php echo $activePage === 'search' ? 'text-primary' : 'text-slate-500 dark:text-slate-400'; ?> py-2" href="search.php">
            <span class="material-symbols-outlined">search</span>
            <p class="text-[10px] font-medium leading-normal">Search</p>
        </a>
        <a class="flex flex-1 flex-col items-center justify-center gap-1 <?php echo $activePage === 'profile' ? 'text-primary' : 'text-slate-500 dark:text-slate-400'; ?> py-2" href="profile.php">
            <span class="material-symbols-outlined">person</span>
            <p class="text-[10px] font-medium leading-normal">Profile</p>
        </a>
        <a class="flex flex-1 flex-col items-center justify-center gap-1 <?php echo $activePage === 'settings' ? 'text-primary' : 'text-slate-500 dark:text-slate-400'; ?> py-2" href="settings.php">
            <span class="material-symbols-outlined">settings</span>
            <p class="text-[10px] font-medium leading-normal">Settings</p>
        </a>
    </div>
</footer>
<?php endif; ?>
<?php endif; ?>

<!-- Global JavaScript -->
<script>
    // Toast notification function
    function showToast(message, type = 'info') {
        const toast = document.createElement('div');
        const colors = {
            'success': 'bg-green-500',
            'error': 'bg-red-500',
            'info': 'bg-primary'
        };
        toast.className = `${colors[type]} text-white px-4 py-3 rounded-xl shadow-lg text-sm font-medium fade-in mb-2`;
        toast.textContent = message;
        document.getElementById('toast-container').appendChild(toast);
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-10px)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // Format timestamp
    function formatTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) {
            return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
        } else if (days === 1) {
            return 'Yesterday';
        } else if (days < 7) {
            return date.toLocaleDateString('en-US', { weekday: 'short' });
        } else {
            return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
        }
    }

    // Toggle dark mode
    function toggleDarkMode() {
        document.documentElement.classList.toggle('dark');
        const isDark = document.documentElement.classList.contains('dark');
        localStorage.setItem('darkMode', isDark);
        
        // Update icon if exists
        const icon = document.getElementById('darkModeIcon');
        if (icon) {
            icon.textContent = isDark ? 'light_mode' : 'dark_mode';
        }
    }

    // Initialize dark mode from localStorage
    (function() {
        const savedDarkMode = localStorage.getItem('darkMode');
        if (savedDarkMode !== null) {
            if (savedDarkMode === 'true') {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
        }
    })();

    // AJAX helper function
    function ajaxRequest(url, data, successCallback, errorCallback) {
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';
        
        $.ajax({
            url: url,
            type: 'POST',
            data: data,
            headers: {
                'X-CSRF-TOKEN': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            success: function(response) {
                if (successCallback) successCallback(response);
            },
            error: function(xhr, status, error) {
                if (errorCallback) {
                    errorCallback(xhr, status, error);
                } else {
                    showToast('An error occurred. Please try again.', 'error');
                }
            }
        });
    }

    // Close emoji picker when clicking outside
    document.addEventListener('click', (e) => {
        const picker = document.getElementById('emoji-picker');
        if (picker && !e.target.closest('#emoji-picker') && !e.target.closest('[onclick="toggleEmojiPicker()"]')) {
            picker.remove();
        }
        
        const gifPicker = document.getElementById('gif-picker');
        if (gifPicker && !e.target.closest('#gif-picker') && !e.target.closest('[onclick="toggleGifPicker()"]')) {
            gifPicker.remove();
        }
    });

    let notificationEventSource = null;
    let notificationPermission = 'default';

    // Request notification permission
    async function requestNotificationPermission() {
        if ('Notification' in window) {
            notificationPermission = await Notification.requestPermission();
            return notificationPermission === 'granted';
        }
        return false;
    }

    // Show browser notification
    function showBrowserNotification(title, body, icon = null) {
        if (notificationPermission !== 'granted') {
            return;
        }

        const options = {
            body: body,
            icon: icon || '/assets/icon-192x192.png',
            badge: '/assets/icon-192x192.png',
            tag: 'quickre-chat',
            requireInteraction: false
        };

        new Notification(title, options);
    }

    // Start notification monitoring
    function startNotificationMonitoring() {
        if (notificationEventSource) {
            notificationEventSource.close();
        }

        notificationEventSource = new EventSource('/api/notifications.php');
        
        notificationEventSource.onmessage = function(event) {
            const data = JSON.parse(event.data);
            
            switch(data.type) {
                case 'notification':
                    if (data.new_messages > 0) {
                        showToast(`You have ${data.new_messages} new message${data.new_messages > 1 ? 's' : ''}`, 'info');
                        
                        // Show browser notification if permission granted
                        showBrowserNotification(
                            'New Message' + (data.new_messages > 1 ? 's' : ''),
                            `You have ${data.new_messages} new message${data.new_messages > 1 ? 's' : ''}`
                        );
                        
                        // Update unread count in UI
                        updateUnreadCount(data.new_messages);
                    }
                    
                    if (data.new_announcements > 0) {
                        showToast(`You have ${data.new_announcements} new announcement${data.new_announcements > 1 ? 's' : ''}`, 'info');
                        
                        showBrowserNotification(
                            'New Announcement' + (data.new_announcements > 1 ? 's' : ''),
                            `${data.new_announcements} new announcement${data.new_announcements > 1 ? 's' : ''} available`
                        );
                    }
                    break;
                    
                case 'typing':
                    // Handle typing indicators
                    console.log('User is typing:', data.user.name);
                    break;
                    
                case 'keepalive':
                    // Keep connection alive
                    break;
            }
        };

        notificationEventSource.onerror = function(event) {
            console.error('Notification stream error:', event);
            // Reconnect after 5 seconds
            setTimeout(startNotificationMonitoring, 5000);
        };

        notificationEventSource.onopen = function() {
            console.log('Notification monitoring started');
        };
    }

    // Update unread count in UI
    function updateUnreadCount(count) {
        // Update bottom navigation badge if exists
        const chatsLink = document.querySelector('a[href="chats.php"]');
        if (chatsLink) {
            let badge = chatsLink.querySelector('.unread-badge');
            if (!badge && count > 0) {
                badge = document.createElement('span');
                badge.className = 'unread-badge absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center font-bold';
                chatsLink.style.position = 'relative';
                chatsLink.appendChild(badge);
            }
            if (badge) {
                badge.textContent = count;
                badge.style.display = count > 0 ? 'flex' : 'none';
            }
        }
    }

    // Initialize notifications when page loads
    document.addEventListener('DOMContentLoaded', function() {
        // Request notification permission
        requestNotificationPermission();
        
        // Remove floating install button since we have a better popup now
        if (document.body.dataset.authenticated === 'true') {
            startNotificationMonitoring();
        }
    });

    // Cleanup on page unload
    window.addEventListener('beforeunload', function() {
        if (notificationEventSource) {
            notificationEventSource.close();
        }
    });
</script>

<?php endif; ?>

</body>
</html>
