// Unified Navigation System
document.addEventListener('DOMContentLoaded', function() {
    initializeBottomNavigation();
    initializeSearchFunctionality();
    updateCartCounter();
});

// Bottom Navigation Active State Management
function initializeBottomNavigation() {
    const navItems = document.querySelectorAll('.bottom-navigation .nav-item');
    const currentPath = window.location.pathname;
    
    if (!navItems || navItems.length === 0) {
        return; // No navigation items found
    }
    
    navItems.forEach(item => {
        if (!item || !item.classList) return; // Skip if element is null
        
        item.classList.remove('active');
        const href = item.getAttribute('href');
        
        if (!href) return; // Skip if no href
        
        // Set active state based on current page
        if (href === currentPath || 
            (currentPath === '/' && href.includes('index')) ||
            (currentPath.includes('products') && href.includes('products')) ||
            (currentPath.includes('cart') && href.includes('cart')) ||
            (currentPath.includes('contact') && href.includes('contact'))) {
            item.classList.add('active');
        }
        
        // Handle category-specific navigation
        if (currentPath.includes('/products/category/1') && href.includes('category_id=1')) {
            item.classList.add('active');
        }
        if (currentPath.includes('/products/category/2') && href.includes('category_id=2')) {
            item.classList.add('active');
        }
    });
}

// Search Functionality
function initializeSearchFunctionality() {
    // Initialize both mobile and desktop search inputs
    const mobileSearchInput = document.getElementById('searchInput');
    const desktopSearchInput = document.getElementById('desktopSearchInput');
    
    // Setup search for mobile input
    if (mobileSearchInput) {
        setupSearchInput(mobileSearchInput);
    }
    
    // Setup search for desktop input
    if (desktopSearchInput) {
        setupSearchInput(desktopSearchInput);
    }
}

function setupSearchInput(searchInput) {
    let searchTimeout;
    
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const query = this.value.trim();
        
        if (query.length >= 3) {
            searchTimeout = setTimeout(() => {
                performSearch(query);
            }, 300);
        }
    });
    
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            const query = this.value.trim();
            if (query.length >= 2) {
                performSearch(query);
            }
        }
    });
}

function performSearch(query) {
    // Simple client-side search implementation
    // In a real app, this would send a request to the server
    const searchResults = document.querySelector('.search-results');
    
    // For now, redirect to products page with search context
    const encodedQuery = encodeURIComponent(query);
    window.location.href = `/products?search=${encodedQuery}`;
}

// Cart Counter Update
function updateCartCounter() {
    // Safely check if fetch is available
    if (typeof fetch === 'undefined') {
        console.warn('Fetch API not available');
        return;
    }

    fetch('/cart/count', {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        const count = parseInt(data.count) || 0;
        
        // Update all cart count elements safely
        updateCartCountElements(count);
    })
    .catch(error => {
        console.warn('Cart counter update failed:', error.message);
        // Try to get count from existing elements as fallback
        fallbackCartUpdate();
    });
}

function updateCartCountElements(count) {
    // Update header cart counts (desktop and mobile)
    const cartCountElements = document.querySelectorAll('.cart-count, .cart-badge');
    cartCountElements.forEach(element => {
        if (element) {
            element.textContent = count;
            element.style.display = count > 0 ? 'inline-flex' : 'none';
        }
    });

    // Update desktop header cart icon badge
    const desktopCartLink = document.querySelector('.enhanced-header .cart-link .badge');
    if (desktopCartLink) {
        desktopCartLink.textContent = count;
        desktopCartLink.style.display = count > 0 ? 'flex' : 'none';
    }

    // Update bottom navigation cart items
    const bottomNavCartItems = document.querySelectorAll('.bottom-navigation a[href*="cart"]');
    bottomNavCartItems.forEach(item => {
        if (item) {
            if (count > 0) {
                item.setAttribute('data-cart-count', count);
            } else {
                item.removeAttribute('data-cart-count');
            }
        }
    });

    // Update any badge elements in the nav
    const navBadges = document.querySelectorAll('.nav-link .badge, .position-absolute.badge');
    navBadges.forEach(badge => {
        const parentLink = badge.closest('a[href*="cart"]');
        if (parentLink && badge) {
            badge.textContent = count;
            badge.style.display = count > 0 ? 'flex' : 'none';
        }
    });
}

function fallbackCartUpdate() {
    // Try to get count from any existing cart count element
    const existingElements = document.querySelectorAll('.cart-count, .cart-badge, .badge');
    let fallbackCount = 0;
    
    for (const element of existingElements) {
        if (element && element.textContent) {
            const parsedCount = parseInt(element.textContent);
            if (!isNaN(parsedCount)) {
                fallbackCount = parsedCount;
                break;
            }
        }
    }
    
    updateCartCountElements(fallbackCount);
}

// Smooth navigation transitions
function addNavigationTransitions() {
    const navItems = document.querySelectorAll('.bottom-navigation .nav-item');
    
    if (!navItems || navItems.length === 0) return;
    
    navItems.forEach(item => {
        if (!item || !item.addEventListener) return;
        
        item.addEventListener('click', function(e) {
            // Add loading state
            if (this.style) {
                this.style.opacity = '0.7';
                
                // Remove loading state after navigation
                setTimeout(() => {
                    if (this.style) {
                        this.style.opacity = '1';
                    }
                }, 200);
            }
        });
    });
}

// Handle page visibility changes
document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        // Page became visible, update navigation states
        initializeBottomNavigation();
        updateCartCounter();
    }
});

// Touch feedback for navigation items
function addTouchFeedback() {
    const navItems = document.querySelectorAll('.bottom-navigation .nav-item');
    
    if (!navItems || navItems.length === 0) return;
    
    navItems.forEach(item => {
        if (!item || !item.addEventListener || !item.style) return;
        
        item.addEventListener('touchstart', function() {
            if (this.style) {
                this.style.transform = 'scale(0.95)';
            }
        });
        
        item.addEventListener('touchend', function() {
            if (this.style) {
                this.style.transform = 'scale(1)';
            }
        });
        
        item.addEventListener('touchcancel', function() {
            if (this.style) {
                this.style.transform = 'scale(1)';
            }
        });
    });
}

// Initialize all navigation features
function initializeUnifiedNavigation() {
    initializeBottomNavigation();
    initializeSearchFunctionality();
    updateCartCounter();
    addNavigationTransitions();
    addTouchFeedback();
}

// Call initialization
initializeUnifiedNavigation();

// Export functions for use in other scripts
window.navigationUtils = {
    updateCartCounter,
    initializeBottomNavigation,
    performSearch
};