/**
 * 🚀 UNIFIED SIDEBAR JAVASCRIPT 🚀
 * Volvo Apple Design - Einheitliche Sidebar-Funktionalität
 * 
 * Features:
 * - Sidebar Toggle (Collapse/Expand)
 * - Mobile Menu Support
 * - Theme Toggle Integration
 * - Smooth Animations
 * - Local Storage Persistence
 */

document.addEventListener('DOMContentLoaded', function() {
    // Initialize sidebar functionality
    initializeSidebar();
    initializeThemeToggle();
    initializeMobileMenu();
    initializeUserMenu();
    initializeCollapsibleSections();
});

function initializeSidebar() {
    const sidebar = document.getElementById('smartSidebar');
    const mainContent = document.querySelector('.admin-main');
    
    if (!sidebar) return;
    
    // Create mobile menu toggle button
    createMobileMenuToggle();
    
    // Restore sidebar state from localStorage
    const isCollapsed = localStorage.getItem('sidebar-collapsed') === 'true';
    if (isCollapsed) {
        sidebar.classList.add('collapsed');
    }
    
    // Add click event to logo for toggle functionality
    const logoSection = sidebar.querySelector('.logo-section');
    if (logoSection) {
        logoSection.addEventListener('click', function() {
            toggleSidebar();
        });
        
        // Add cursor pointer to indicate it's clickable
        logoSection.style.cursor = 'pointer';
    }
}

function createMobileMenuToggle() {
    // Only create on mobile devices
    if (window.innerWidth > 768) return;
    
    const toggleButton = document.createElement('button');
    toggleButton.className = 'mobile-menu-toggle';
    toggleButton.innerHTML = '<i class="fas fa-bars"></i>';
    toggleButton.setAttribute('aria-label', 'Menü öffnen');
    
    document.body.appendChild(toggleButton);
    
    // Create overlay
    const overlay = document.createElement('div');
    overlay.className = 'sidebar-overlay';
    document.body.appendChild(overlay);
    
    // Add event listeners
    toggleButton.addEventListener('click', function() {
        toggleMobileSidebar();
    });
    
    overlay.addEventListener('click', function() {
        closeMobileSidebar();
    });
}

function toggleSidebar() {
    const sidebar = document.getElementById('smartSidebar');
    if (!sidebar) return;
    
    sidebar.classList.toggle('collapsed');
    localStorage.setItem('sidebar-collapsed', sidebar.classList.contains('collapsed'));
    
    // Add animation class for smooth transition
    sidebar.style.transition = 'width 0.3s cubic-bezier(0.4, 0, 0.2, 1)';
}

function toggleMobileSidebar() {
    const sidebar = document.getElementById('smartSidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    const toggleButton = document.querySelector('.mobile-menu-toggle');
    
    if (!sidebar) return;
    
    sidebar.classList.toggle('open');
    overlay.classList.toggle('active');
    
    // Update button icon
    if (toggleButton) {
        const icon = toggleButton.querySelector('i');
        if (sidebar.classList.contains('open')) {
            icon.className = 'fas fa-times';
            toggleButton.setAttribute('aria-label', 'Menü schließen');
        } else {
            icon.className = 'fas fa-bars';
            toggleButton.setAttribute('aria-label', 'Menü öffnen');
        }
    }
}

function closeMobileSidebar() {
    const sidebar = document.getElementById('smartSidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    const toggleButton = document.querySelector('.mobile-menu-toggle');
    
    if (!sidebar) return;
    
    sidebar.classList.remove('open');
    overlay.classList.remove('active');
    
    // Update button icon
    if (toggleButton) {
        const icon = toggleButton.querySelector('i');
        icon.className = 'fas fa-bars';
        toggleButton.setAttribute('aria-label', 'Menü öffnen');
    }
}

function initializeThemeToggle() {
    const themeToggle = document.querySelector('.theme-toggle');
    if (!themeToggle) return;
    
    // Initialize theme on page load
    const savedTheme = localStorage.getItem('admin-theme') || 'light';
    document.documentElement.setAttribute('data-theme', savedTheme);
    document.body.setAttribute('data-theme', savedTheme);
    
    console.log('Sidebar initializing theme:', savedTheme);
    
    // Update icon based on current theme
    updateThemeIcon(savedTheme);
}

function updateThemeIcon(theme) {
    const themeToggle = document.querySelector('.theme-toggle');
    if (!themeToggle) return;
    
    const icon = themeToggle.querySelector('i');
    if (icon) {
        if (theme === 'dark') {
            icon.className = 'fas fa-sun';
        } else {
            icon.className = 'fas fa-moon';
        }
    }
}

function initializeMobileMenu() {
    // Handle window resize
    window.addEventListener('resize', function() {
        const sidebar = document.getElementById('smartSidebar');
        const overlay = document.querySelector('.sidebar-overlay');
        const toggleButton = document.querySelector('.mobile-menu-toggle');
        
        if (window.innerWidth > 768) {
            // Desktop view
            if (sidebar) {
                sidebar.classList.remove('open');
            }
            if (overlay) {
                overlay.classList.remove('active');
            }
            if (toggleButton) {
                toggleButton.style.display = 'none';
            }
        } else {
            // Mobile view
            if (toggleButton) {
                toggleButton.style.display = 'flex';
            }
        }
    });
    
    // Close mobile sidebar when clicking on nav items
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            if (window.innerWidth <= 768) {
                closeMobileSidebar();
            }
        });
    });
}

function initializeUserMenu() {
    const userMenuBtn = document.getElementById('user-menu-btn');
    const userMenuContainer = document.querySelector('.user-menu-container');
    
    if (userMenuBtn && userMenuContainer) {
        userMenuBtn.addEventListener('click', function(e) {
            e.preventDefault();
            userMenuContainer.classList.toggle('active');
        });
        
        // Close user menu when clicking outside
        document.addEventListener('click', function(e) {
            if (!userMenuContainer.contains(e.target)) {
                userMenuContainer.classList.remove('active');
            }
        });
    }
}

// Handle theme toggle form submission
document.addEventListener('submit', function(e) {
    if (e.target.querySelector('button[name="toggle_theme"]')) {
        e.preventDefault();
        
        const currentTheme = document.body.getAttribute('data-theme') || 'light';
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        console.log('Form theme toggle:', currentTheme, '->', newTheme);
        
        // Update theme immediately for better UX
        document.documentElement.setAttribute('data-theme', newTheme);
        document.body.setAttribute('data-theme', newTheme);
        updateThemeIcon(newTheme);
        
        // Save to localStorage
        localStorage.setItem('admin-theme', newTheme);
        
        // Don't call global theme toggle function to prevent conflicts
        // The theme is already updated above
        
        // Submit form to update database
        setTimeout(() => {
            e.target.submit();
        }, 100);
    }
});

// Add smooth scroll behavior for sidebar navigation
document.querySelectorAll('.nav-item[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

// Add keyboard navigation support
document.addEventListener('keydown', function(e) {
    // Toggle sidebar with Ctrl/Cmd + B
    if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
        e.preventDefault();
        toggleSidebar();
    }
    
    // Toggle theme with Ctrl/Cmd + T
    if ((e.ctrlKey || e.metaKey) && e.key === 't') {
        e.preventDefault();
        const themeToggle = document.querySelector('.theme-toggle');
        if (themeToggle) {
            themeToggle.click();
        }
    }
});

// Add focus management for accessibility
document.addEventListener('keydown', function(e) {
    const sidebar = document.getElementById('smartSidebar');
    if (!sidebar || !sidebar.classList.contains('open')) return;
    
    // Close sidebar with Escape key
    if (e.key === 'Escape') {
        closeMobileSidebar();
    }
});

// Add loading states for navigation
document.querySelectorAll('.nav-item').forEach(item => {
    item.addEventListener('click', function(e) {
        // Add loading state for external links
        if (this.getAttribute('target') === '_blank') {
            return; // Don't add loading for external links
        }
        
        // Add loading indicator
        const icon = this.querySelector('.nav-icon i');
        if (icon) {
            const originalClass = icon.className;
            icon.className = 'fas fa-spinner fa-spin';
            
            // Reset after a short delay
            setTimeout(() => {
                icon.className = originalClass;
            }, 1000);
        }
    });
});

// Initialize Professional Navigation Groups
function initializeCollapsibleSections() {
    const groupTriggers = document.querySelectorAll('.nav-group-trigger');
    
    groupTriggers.forEach(trigger => {
        trigger.addEventListener('click', function() {
            const targetId = this.getAttribute('data-target');
            const targetMenu = document.getElementById(targetId);
            
            if (targetMenu) {
                // Toggle expanded state
                targetMenu.classList.toggle('expanded');
                this.classList.toggle('active');
                
                // Save state to localStorage
                const isExpanded = targetMenu.classList.contains('expanded');
                localStorage.setItem(`sidebar-group-${targetId}`, isExpanded);
            }
        });
        
        // Restore expanded state from localStorage
        const targetId = trigger.getAttribute('data-target');
        const isExpanded = localStorage.getItem(`sidebar-group-${targetId}`) === 'true';
        
        if (isExpanded) {
            const targetMenu = document.getElementById(targetId);
            if (targetMenu) {
                targetMenu.classList.add('expanded');
                trigger.classList.add('active');
            }
        }
    });
}

// Export functions for external use
window.SidebarManager = {
    toggle: toggleSidebar,
    toggleMobile: toggleMobileSidebar,
    closeMobile: closeMobileSidebar,
    updateTheme: updateThemeIcon
};
