// Responsive Sidebar Navigation JavaScript
document.addEventListener('DOMContentLoaded', function() {
    initializeSidebarNavigation();
    handleActiveNavigation();
    setupSidebarInteractions();
    initializeHamburgerToggle();
});

function openSidebar() {
    const sidebar = document.querySelector('.mobile-sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    if (!sidebar || !overlay) return;
    sidebar.classList.add('show');
    overlay.classList.add('show');
    document.body.classList.add('sidebar-open');
    const hamburgerIcon = document.querySelector('.hamburger-toggle i');
    if (hamburgerIcon) hamburgerIcon.className = 'fas fa-times';
}

function closeSidebar() {
    const sidebar = document.querySelector('.mobile-sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    if (!sidebar || !overlay) return;
    sidebar.classList.remove('show');
    overlay.classList.remove('show');
    document.body.classList.remove('sidebar-open');
    const hamburgerIcon = document.querySelector('.hamburger-toggle i');
    if (hamburgerIcon) hamburgerIcon.className = 'fas fa-bars';
}

function initializeHamburgerToggle() {
    const hamburgerBtn = document.querySelector('.hamburger-toggle');
    const overlay = document.querySelector('.sidebar-overlay');
    const closeBtn = document.querySelector('.sidebar-close-btn');

    // Hamburger toggle (header)
    if (hamburgerBtn) {
        hamburgerBtn.addEventListener('click', function() {
            const sidebar = document.querySelector('.mobile-sidebar');
            if (sidebar && sidebar.classList.contains('show')) {
                closeSidebar();
            } else {
                openSidebar();
            }
        });
    }

    // Close button in sidebar
    if (closeBtn) {
        closeBtn.addEventListener('click', closeSidebar);
    }

    // Mobile bottom-nav "Categories" button
    const categoriesBtn = document.getElementById('mobileCategoriesBtn');
    if (categoriesBtn) {
        categoriesBtn.addEventListener('click', function() {
            openSidebar();
        });
    }

    // Close on overlay click
    if (overlay) {
        overlay.addEventListener('click', closeSidebar);
    }

    // Close on Escape
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeSidebar();
    });

    // Close on nav item click
    const navItems = document.querySelectorAll('.sidebar-nav-item');
    navItems.forEach(item => {
        item.addEventListener('click', closeSidebar);
    });
}

function initializeSidebarNavigation() {
    const sidebar = document.querySelector('.mobile-sidebar');
    const sidebarItems = document.querySelectorAll('.sidebar-nav-item');
    
    if (!sidebar || !sidebarItems.length) return;
    
    // Add smooth scroll behavior
    sidebar.style.scrollBehavior = 'smooth';
    
    // Set initial active state based on current page
    setActiveNavItem();
    
    // Add click handlers for navigation items
    sidebarItems.forEach(item => {
        item.addEventListener('click', function(e) {
            // Remove active class from all items
            sidebarItems.forEach(navItem => navItem.classList.remove('active'));
            
            // Add active class to clicked item
            this.classList.add('active');
            
            // Add loading state for better UX
            addLoadingState(this);
        });
    });
}

function setActiveNavItem() {
    const currentPath = window.location.pathname;
    const sidebarItems = document.querySelectorAll('.sidebar-nav-item');
    
    sidebarItems.forEach(item => {
        const href = item.getAttribute('href');
        
        // Check if current path matches the nav item
        if (href === currentPath || 
            (currentPath === '/' && href.includes('index')) ||
            (currentPath.includes('/products') && href.includes('/products')) ||
            (currentPath.includes('/cart') && href.includes('/cart')) ||
            (currentPath.includes('/signin') && href.includes('/signin'))) {
            
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
}

function addLoadingState(navItem) {
    const icon = navItem.querySelector('i');
    const originalClass = icon.className;
    
    // Add spinner
    icon.className = 'fas fa-spinner fa-spin';
    
    // Restore original icon after navigation
    setTimeout(() => {
        icon.className = originalClass;
    }, 500);
}

function setupSidebarInteractions() {
    const sidebar = document.querySelector('.mobile-sidebar');
    if (!sidebar) return;
    
    // Add hover effects for better user feedback
    const navItems = sidebar.querySelectorAll('.sidebar-nav-item');
    
    navItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(10px)';
        });
        
        item.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0)';
        });
    });
    
    // Handle cart count updates
    updateSidebarCartCount();
}

function updateSidebarCartCount() {
    // Function to update cart count in sidebar
    function refreshCartCount() {
        fetch('/cart/count')
            .then(response => response.json())
            .then(data => {
                const cartBadge = document.querySelector('.sidebar-nav-item .cart-badge');
                const cartNavItem = document.querySelector('.sidebar-nav-item[href*="cart"]');
                
                if (data.count > 0) {
                    if (cartBadge) {
                        cartBadge.textContent = data.count;
                    } else if (cartNavItem) {
                        // Create badge if it doesn't exist
                        const badge = document.createElement('span');
                        badge.className = 'cart-badge';
                        badge.textContent = data.count;
                        cartNavItem.appendChild(badge);
                    }
                } else {
                    // Remove badge if count is 0
                    if (cartBadge) {
                        cartBadge.remove();
                    }
                }
            })
            .catch(error => {
                console.log('Cart count update failed:', error);
            });
    }
    
    // Update cart count every 30 seconds
    setInterval(refreshCartCount, 30000);
}

function handleActiveNavigation() {
    // Update active state when page changes (for SPAs or AJAX navigation)
    window.addEventListener('popstate', setActiveNavItem);
    
    // Handle dynamic route changes
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList') {
                setActiveNavItem();
            }
        });
    });
    
    // Observe changes in the document body
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
}

// Responsive behavior management
function handleResponsiveNavigation() {
    const sidebar = document.querySelector('.mobile-sidebar');
    const bottomNav = document.querySelector('.bottom-navigation');
    
    function updateNavigationVisibility() {
        const width = window.innerWidth;
        
        if (width >= 768 && width <= 991) {
            // Tablet range - sidebar available via toggle
            if (bottomNav) bottomNav.style.display = 'none';
            
        } else if (width < 768) {
            // Mobile range - show bottom nav, sidebar available via toggle
            if (bottomNav) bottomNav.style.display = 'flex';
            
        } else {
            // Desktop range - hide bottom nav
            if (bottomNav) bottomNav.style.display = 'none';
        }
    }
    
    // Initial check
    updateNavigationVisibility();
    
    // Update on resize with debounce
    window.addEventListener('resize', debounce(updateNavigationVisibility, 150));
}

// Utility function for debouncing
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Initialize responsive navigation
handleResponsiveNavigation();

// Export functions for use in other scripts
window.SidebarNavigation = {
    setActiveNavItem,
    updateSidebarCartCount,
    handleResponsiveNavigation
};