// Modern Sidebar JavaScript Enhancements

document.addEventListener('DOMContentLoaded', function() {
    
    // Initialize modern sidebar functionality
    initModernSidebar();
    
    // Add smooth scrolling to sidebar
    initSmoothScrolling();
    
    // Add hover effects and animations
    initHoverEffects();
    
    // Add keyboard navigation
    initKeyboardNavigation();
    
    // Add ripple effects
    initRippleEffects();
    
    // Initialize submenu functionality
    initSubmenuFunctionality();
    
    // Hide specific menu items
    hideSpecificMenuItems();
    
    // Move settings to bottom
    moveSettingsToBottom();
    
    // Optimize scroll performance
    optimizeScrollPerformance();
});

function initModernSidebar() {
    const sidebar = document.querySelector('.main-sidebar, .main-sidebar2');
    const menuItems = document.querySelectorAll('.sidebar-menu > li > a');
    
    if (!sidebar) return;
    
    // Add stagger animation to menu items
    menuItems.forEach((item, index) => {
        item.style.setProperty('--item-index', index);
        item.style.animationDelay = `${index * 0.1}s`;
    });
    
    // Add intersection observer for scroll animations
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });
    
    menuItems.forEach(item => {
        observer.observe(item);
    });
}

function initSmoothScrolling() {
    const sidebarMenu = document.querySelector('.sidebar-menu');
    
    if (sidebarMenu) {
        // Ensure proper scroll behavior - let browser handle it naturally
        sidebarMenu.style.overflowY = 'auto';
        sidebarMenu.style.overflowX = 'hidden';
        
        // Remove any custom wheel listeners to allow natural scrolling
        sidebarMenu.removeEventListener('wheel', handleWheel);
        
        // Add custom scrollbar styling only
        sidebarMenu.addEventListener('scroll', function() {
            const scrollTop = this.scrollTop;
            const scrollHeight = this.scrollHeight;
            const clientHeight = this.clientHeight;
            
            // Add fade effect at top and bottom
            if (scrollTop > 0) {
                this.style.setProperty('--scroll-top', '1');
            } else {
                this.style.setProperty('--scroll-top', '0');
            }
            
            if (scrollTop + clientHeight < scrollHeight) {
                this.style.setProperty('--scroll-bottom', '1');
            } else {
                this.style.setProperty('--scroll-bottom', '0');
            }
        });
    }
}

function initHoverEffects() {
    const menuItems = document.querySelectorAll('.sidebar-menu > li > a, .sidebar-menu .treeview-menu > li > a');
    
    menuItems.forEach(item => {
        // Enhanced hover effects
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(8px) scale(1.02)';
            this.style.boxShadow = '0 8px 25px rgba(0, 0, 0, 0.3)';
            
            // Animate icon with bounce
            const icon = this.querySelector('iconify-icon');
            if (icon) {
                icon.style.transform = 'scale(1.1) rotate(5deg)';
                icon.style.animation = 'iconBounce 0.3s ease';
            }
            
            // Add hover sound
            playHoverSound();
            
            // Add magnetic effect
            addMagneticEffect(this);
        });
        
        item.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0) scale(1)';
            this.style.boxShadow = 'none';
            
            // Reset icon
            const icon = this.querySelector('iconify-icon');
            if (icon) {
                icon.style.transform = 'scale(1) rotate(0deg)';
                icon.style.animation = '';
            }
            
            // Remove magnetic effect
            removeMagneticEffect(this);
        });
        
        // Enhanced click animation
        item.addEventListener('click', function(e) {
            createRippleEffect(e, this);
            addClickPulse(this);
        });
    });
}

// Add magnetic effect to menu items
function addMagneticEffect(element) {
    element.addEventListener('mousemove', function(e) {
        const rect = this.getBoundingClientRect();
        const x = e.clientX - rect.left - rect.width / 2;
        const y = e.clientY - rect.top - rect.height / 2;
        
        this.style.transform = `translateX(${8 + x * 0.1}px) scale(1.02)`;
    });
}

function removeMagneticEffect(element) {
    element.style.transform = 'translateX(0) scale(1)';
}

// Add click pulse effect
function addClickPulse(element) {
    element.style.animation = 'clickPulse 0.3s ease';
    setTimeout(() => {
        element.style.animation = '';
    }, 300);
}

// Play hover sound
function playHoverSound() {
    if (window.AudioContext || window.webkitAudioContext) {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.03, audioContext.currentTime + 0.01);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 0.05);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.05);
    }
}

// Hide specific menu items and rearrange settings
function hideSpecificMenuItems() {
    const menuItemsToHide = [
        'attendance',
        'warranty',
        'servicing',
        'salary',
        'payroll',
        'fixed',
        'assets',
        'update',
        'software',
        'uninstall',
        'license'
    ];
    
    const menuItems = document.querySelectorAll('.sidebar-menu > li');
    
    menuItems.forEach(item => {
        const link = item.querySelector('a');
        if (link) {
            const span = link.querySelector('span');
            if (span) {
                const text = span.textContent.toLowerCase();
                
                // Check if this menu item should be hidden
                const shouldHide = menuItemsToHide.some(hideText => 
                    text.includes(hideText.toLowerCase())
                );
                
                if (shouldHide) {
                    item.style.display = 'none';
                }
            }
        }
    });
}

// Move settings menu to bottom
function moveSettingsToBottom() {
    const sidebarMenu = document.querySelector('.sidebar-menu');
    const settingsMenu = document.querySelector('.sidebar-menu > li:has(a span:contains("setting"))');
    
    if (sidebarMenu && settingsMenu) {
        // Remove settings from current position
        settingsMenu.remove();
        
        // Add settings to bottom
        sidebarMenu.appendChild(settingsMenu);
        
        // Add bottom positioning class
        settingsMenu.classList.add('settings-bottom');
    }
}

function initKeyboardNavigation() {
    const menuItems = document.querySelectorAll('.sidebar-menu > li > a, .sidebar-menu .treeview-menu > li > a');
    
    menuItems.forEach((item, index) => {
        item.setAttribute('tabindex', '0');
        
        item.addEventListener('keydown', function(e) {
            switch(e.key) {
                case 'Enter':
                case ' ':
                    e.preventDefault();
                    this.click();
                    break;
                case 'ArrowDown':
                    e.preventDefault();
                    const nextItem = menuItems[index + 1];
                    if (nextItem) nextItem.focus();
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    const prevItem = menuItems[index - 1];
                    if (prevItem) prevItem.focus();
                    break;
            }
        });
    });
}

function initRippleEffects() {
    const menuItems = document.querySelectorAll('.sidebar-menu > li > a, .sidebar-menu .treeview-menu > li > a');
    
    menuItems.forEach(item => {
        item.addEventListener('click', function(e) {
            createRippleEffect(e, this);
        });
    });
}

function createRippleEffect(event, element) {
    const ripple = document.createElement('span');
    const rect = element.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    const x = event.clientX - rect.left - size / 2;
    const y = event.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 linear;
        pointer-events: none;
        z-index: 1000;
    `;
    
    element.style.position = 'relative';
    element.style.overflow = 'hidden';
    element.appendChild(ripple);
    
    setTimeout(() => {
        ripple.remove();
    }, 600);
}

// Initialize submenu functionality
function initSubmenuFunctionality() {
    const treeviewItems = document.querySelectorAll('.sidebar-menu > li.treeview');
    
    treeviewItems.forEach(item => {
        const link = item.querySelector('a');
        const submenu = item.querySelector('.treeview-menu');
        
        if (link && submenu) {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                
                // Close other open menus
                const otherOpenMenus = document.querySelectorAll('.sidebar-menu > li.treeview.menu-open');
                otherOpenMenus.forEach(openMenu => {
                    if (openMenu !== item) {
                        openMenu.classList.remove('menu-open');
                        const otherSubmenu = openMenu.querySelector('.treeview-menu');
                        if (otherSubmenu) {
                            otherSubmenu.style.maxHeight = '0';
                            otherSubmenu.style.display = 'none';
                        }
                    }
                });
                
                // Toggle current menu
                item.classList.toggle('menu-open');
                
                if (item.classList.contains('menu-open')) {
                    submenu.style.display = 'block';
                    submenu.style.maxHeight = '500px';
                    submenu.style.opacity = '1';
                    submenu.style.transform = 'translateX(0)';
                    playSubmenuSound(true);
                } else {
                    submenu.style.maxHeight = '0';
                    submenu.style.opacity = '0';
                    submenu.style.transform = 'translateX(-20px)';
                    setTimeout(() => {
                        submenu.style.display = 'none';
                    }, 400);
                    playSubmenuSound(false);
                }
            });
        }
    });
}

// Play submenu sound
function playSubmenuSound(isOpen) {
    if (window.AudioContext || window.webkitAudioContext) {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        const frequency = isOpen ? 600 : 400;
        oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.02, audioContext.currentTime + 0.01);
        gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 0.1);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.1);
    }
}

// Initialize sidebar collapse functionality
function initSidebarCollapse() {
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const body = document.body;
    
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function() {
            body.classList.toggle('sidebar-collapse');
            
            // Save state to localStorage
            const isCollapsed = body.classList.contains('sidebar-collapse');
            localStorage.setItem('sidebar-collapsed', isCollapsed);
        });
    }
    
    // Restore state from localStorage
    const savedState = localStorage.getItem('sidebar-collapsed');
    if (savedState === 'true') {
        body.classList.add('sidebar-collapse');
    }
}

// Add loading animation
function addLoadingAnimation() {
    const menuItems = document.querySelectorAll('.sidebar-menu > li');
    
    menuItems.forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateY(20px)';
        
        setTimeout(() => {
            item.style.transition = 'all 0.5s ease';
            item.style.opacity = '1';
            item.style.transform = 'translateY(0)';
        }, index * 100);
    });
}

// Add parallax effect
function initParallaxEffect() {
    const sidebar = document.querySelector('.main-sidebar, .main-sidebar2');
    
    if (sidebar) {
        window.addEventListener('scroll', function() {
            const scrolled = window.pageYOffset;
            const rate = scrolled * -0.5;
            
            sidebar.style.transform = `translateY(${rate}px)`;
        });
    }
}

// Initialize hover sounds
function initHoverSounds() {
    const menuItems = document.querySelectorAll('.sidebar-menu > li > a, .sidebar-menu .treeview-menu > li > a');
    
    menuItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
            playHoverSound();
        });
    });
}

// Optimize scroll performance
function optimizeScrollPerformance() {
    const sidebarMenu = document.querySelector('.sidebar-menu');
    
    if (sidebarMenu) {
        let ticking = false;
        
        sidebarMenu.addEventListener('scroll', function() {
            if (!ticking) {
                requestAnimationFrame(function() {
                    // Disable heavy animations during scroll
                    sidebarMenu.style.setProperty('--scrolling', '1');
                    ticking = false;
                });
                ticking = true;
            }
        });
        
        sidebarMenu.addEventListener('scrollend', function() {
            // Re-enable animations after scroll
            sidebarMenu.style.setProperty('--scrolling', '0');
        });
    }
}

// Add CSS for ripple animation
const style = document.createElement('style');
style.textContent = `
    @keyframes ripple {
        to {
            transform: scale(4);
            opacity: 0;
        }
    }
    
    @keyframes iconBounce {
        0%, 100% {
            transform: scale(1.1) rotate(5deg);
        }
        50% {
            transform: scale(1.2) rotate(10deg);
        }
    }
    
    @keyframes clickPulse {
        0% {
            transform: scale(1);
        }
        50% {
            transform: scale(0.95);
        }
        100% {
            transform: scale(1);
        }
    }
`;
document.head.appendChild(style); 