// Horizontal Subcategory Navigation with Smooth Scrolling
class SubcategoryNavigation {
    constructor() {
        this.navContainer = document.querySelector('.subcategory-nav');
        this.navButtons = [];
        this.productSections = [];
        this.activeSection = null;
        this.isScrolling = false;
        this.observer = null;
        
        this.init();
    }
    
    init() {
        if (!this.navContainer) return;
        
        this.navButtons = Array.from(document.querySelectorAll('.subcategory-nav-btn'));
        this.productSections = Array.from(document.querySelectorAll('.product-section'));
        
        this.setupEventListeners();
        this.setupTouchNavigation();
        this.setupDesktopScrollButtons();
        this.setupIntersectionObserver();
        this.updateActiveButton();
    }
    
    setupEventListeners() {
        // Button click handlers
        this.navButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                const target = button.getAttribute('data-target');
                this.scrollToSection(target);
            });
        });
        
        // Handle scroll events
        let scrollTimer = null;
        window.addEventListener('scroll', () => {
            if (scrollTimer) {
                clearTimeout(scrollTimer);
            }
            
            scrollTimer = setTimeout(() => {
                this.isScrolling = false;
            }, 150);
            
            if (!this.isScrolling) {
                this.updateActiveButton();
            }
        });
        
        // Handle window resize
        window.addEventListener('resize', () => {
            this.updateActiveButton();
        });
        
        // Touch/swipe support for horizontal navigation
        this.setupTouchNavigation();
    }
    
    setupDesktopScrollButtons() {
        const container = document.querySelector('.subcategory-nav-container');
        if (!container || window.innerWidth <= 768) return;
        
        // Create scroll buttons
        const leftBtn = document.createElement('button');
        leftBtn.className = 'scroll-btn left';
        leftBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
        leftBtn.setAttribute('aria-label', 'Scroll left');
        
        const rightBtn = document.createElement('button');
        rightBtn.className = 'scroll-btn right';
        rightBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
        rightBtn.setAttribute('aria-label', 'Scroll right');
        
        // Add buttons to container
        container.appendChild(leftBtn);
        container.appendChild(rightBtn);
        
        // Add click handlers
        leftBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            this.scrollHorizontal(-200);
        });
        
        rightBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            this.scrollHorizontal(200);
        });
        
        // Update button states on scroll
        this.navContainer.addEventListener('scroll', () => {
            this.updateScrollButtons(leftBtn, rightBtn);
        });
        
        // Initial button state
        this.updateScrollButtons(leftBtn, rightBtn);
        
        // Add keyboard navigation
        container.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowLeft') {
                e.preventDefault();
                this.scrollHorizontal(-200);
            } else if (e.key === 'ArrowRight') {
                e.preventDefault();
                this.scrollHorizontal(200);
            }
        });
        
        // Make container focusable for keyboard navigation
        container.setAttribute('tabindex', '0');
    }
    
    updateScrollButtons(leftBtn, rightBtn) {
        if (!this.navContainer || !leftBtn || !rightBtn) return;
        
        const scrollLeft = this.navContainer.scrollLeft;
        const maxScroll = this.navContainer.scrollWidth - this.navContainer.clientWidth;
        
        // Disable left button if at start
        leftBtn.disabled = scrollLeft <= 0;
        
        // Disable right button if at end
        rightBtn.disabled = scrollLeft >= maxScroll - 5; // 5px tolerance
    }
    
    scrollHorizontal(distance) {
        if (!this.navContainer) return;
        
        this.navContainer.scrollBy({
            left: distance,
            behavior: 'smooth'
        });
    }
    
    setupTouchNavigation() {
        if (!this.navContainer) return;
        
        let startX = 0;
        let scrollLeft = 0;
        let isDown = false;
        
        this.navContainer.addEventListener('mousedown', (e) => {
            isDown = true;
            startX = e.pageX - this.navContainer.offsetLeft;
            scrollLeft = this.navContainer.scrollLeft;
            this.navContainer.style.cursor = 'grabbing';
        });
        
        this.navContainer.addEventListener('mouseleave', () => {
            isDown = false;
            this.navContainer.style.cursor = 'grab';
        });
        
        this.navContainer.addEventListener('mouseup', () => {
            isDown = false;
            this.navContainer.style.cursor = 'grab';
        });
        
        this.navContainer.addEventListener('mousemove', (e) => {
            if (!isDown) return;
            e.preventDefault();
            const x = e.pageX - this.navContainer.offsetLeft;
            const walk = (x - startX) * 2;
            this.navContainer.scrollLeft = scrollLeft - walk;
        });
        
        // Touch events
        this.navContainer.addEventListener('touchstart', (e) => {
            startX = e.touches[0].pageX - this.navContainer.offsetLeft;
            scrollLeft = this.navContainer.scrollLeft;
        });
        
        this.navContainer.addEventListener('touchmove', (e) => {
            const x = e.touches[0].pageX - this.navContainer.offsetLeft;
            const walk = (x - startX) * 2;
            this.navContainer.scrollLeft = scrollLeft - walk;
        });
    }
    
    setupIntersectionObserver() {
        if (!('IntersectionObserver' in window)) {
            return;
        }
        
        const options = {
            root: null,
            rootMargin: '-20% 0px -70% 0px',
            threshold: 0.1
        };
        
        this.observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    this.activeSection = entry.target.id;
                    this.updateActiveButton();
                    
                    // Add visible class for animations
                    entry.target.classList.add('visible');
                }
            });
        }, options);
        
        this.productSections.forEach(section => {
            this.observer.observe(section);
        });
    }
    
    scrollToSection(targetId) {
        const targetSection = document.getElementById(targetId);
        if (!targetSection) return;
        
        this.isScrolling = true;
        this.activeSection = targetId;
        this.updateActiveButton();
        
        // Add loading state
        const activeButton = this.navButtons.find(btn => 
            btn.getAttribute('data-target') === targetId
        );
        if (activeButton) {
            activeButton.classList.add('loading');
        }
        
        // Calculate offset to account for sticky header and nav
        const headerHeight = document.querySelector('.modern-header')?.offsetHeight || 0;
        const navHeight = document.querySelector('.subcategory-nav-wrapper')?.offsetHeight || 0;
        const offset = headerHeight + navHeight + 20;
        
        const targetPosition = targetSection.offsetTop - offset;
        
        // Smooth scroll with custom easing
        this.smoothScrollTo(targetPosition, 800, () => {
            // Remove loading state
            if (activeButton) {
                activeButton.classList.remove('loading');
            }
            this.isScrolling = false;
        });
    }
    
    smoothScrollTo(targetPosition, duration, callback) {
        const startPosition = window.pageYOffset;
        const distance = targetPosition - startPosition;
        let startTime = null;
        
        function animation(currentTime) {
            if (startTime === null) startTime = currentTime;
            const timeElapsed = currentTime - startTime;
            const run = easeInOutCubic(timeElapsed, startPosition, distance, duration);
            window.scrollTo(0, run);
            
            if (timeElapsed < duration) {
                requestAnimationFrame(animation);
            } else {
                if (callback) callback();
            }
        }
        
        function easeInOutCubic(t, b, c, d) {
            t /= d / 2;
            if (t < 1) return c / 2 * t * t * t + b;
            t -= 2;
            return c / 2 * (t * t * t + 2) + b;
        }
        
        requestAnimationFrame(animation);
    }
    
    updateActiveButton() {
        if (!this.activeSection) {
            // Determine active section based on scroll position
            let closestSection = null;
            let closestDistance = Infinity;
            
            this.productSections.forEach(section => {
                const rect = section.getBoundingClientRect();
                const distance = Math.abs(rect.top - 200); // 200px offset from top
                
                if (distance < closestDistance) {
                    closestDistance = distance;
                    closestSection = section.id;
                }
            });
            
            this.activeSection = closestSection;
        }
        
        // Update button states
        this.navButtons.forEach(button => {
            const target = button.getAttribute('data-target');
            if (target === this.activeSection) {
                button.classList.add('active');
                this.scrollButtonIntoView(button);
            } else {
                button.classList.remove('active');
            }
        });
    }
    
    scrollButtonIntoView(button) {
        if (!this.navContainer || !button) return;
        
        const containerRect = this.navContainer.getBoundingClientRect();
        const buttonRect = button.getBoundingClientRect();
        
        const isVisible = (
            buttonRect.left >= containerRect.left &&
            buttonRect.right <= containerRect.right
        );
        
        if (!isVisible) {
            const scrollOffset = buttonRect.left - containerRect.left - 
                (containerRect.width / 2) + (buttonRect.width / 2);
            
            this.navContainer.scrollBy({
                left: scrollOffset,
                behavior: 'smooth'
            });
        }
    }
    
    destroy() {
        if (this.observer) {
            this.observer.disconnect();
        }
    }
}

// Global scroll function for backward compatibility
function scrollToSection(sectionId) {
    if (window.subcategoryNav) {
        window.subcategoryNav.scrollToSection(sectionId);
    } else {
        // Fallback scroll
        const section = document.getElementById(sectionId);
        if (section) {
            section.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    window.subcategoryNav = new SubcategoryNavigation();
});

// Clean up on page unload
window.addEventListener('beforeunload', () => {
    if (window.subcategoryNav) {
        window.subcategoryNav.destroy();
    }
});

// Handle browser back/forward navigation
window.addEventListener('popstate', () => {
    if (window.subcategoryNav) {
        window.subcategoryNav.updateActiveButton();
    }
});

// Performance optimization: Debounced resize handler
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { SubcategoryNavigation, scrollToSection };
}