jQuery(document).ready(function($) {
    
    // Mobile menu toggle - vertical dropdown
    $('#mobile-menu-checkbox').on('change', function() {
        if (this.checked) {
            $('body').addClass('menu-open');
        } else {
            $('body').removeClass('menu-open');
        }
    });
    
    // Mobile submenu toggle - all levels including nested
    $(document).on('click', '.nav-menu li.menu-item-has-children > a', function(e) {
        if ($(window).width() <= 768) {
            e.preventDefault();
            e.stopPropagation();
            
            var $parent = $(this).parent();
            $parent.toggleClass('active');
            
            console.log('Submenu toggled:', $(this).text().trim(), 'Active:', $parent.hasClass('active'));
        }
    });
    
    // Dark mode toggle functionality
    const themeToggle = $('.theme-toggle');

    const currentTheme = localStorage.getItem('theme') || 'light';
    document.documentElement.setAttribute('data-theme', currentTheme);

    requestAnimationFrame(function() {
        requestAnimationFrame(function() {
            document.documentElement.classList.remove('theme-no-transition');
        });
    });

    // Toggle theme on button click
    themeToggle.on('click', function() {
        let theme = document.documentElement.getAttribute('data-theme');
        
        if (theme === 'light') {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
        } else {
            document.documentElement.setAttribute('data-theme', 'light');
            localStorage.setItem('theme', 'light');
        }
    });
    
    // Slider functionality (warezdl-theme style)
    let currentIndex = 0;
    let autoplayInterval = null;
    let cardsToShow = 7;
    
    const sliderTrack = $('#sliderTrack');
    const sliderItems = sliderTrack.children('.slider-item');
    const prevBtn = $('#prevBtn');
    const nextBtn = $('#nextBtn');
    
    // Calculate cards to show based on screen width
    function updateCardsToShow() {
        const width = $(window).width();
        if (width <= 600) {
            cardsToShow = 2;
        } else if (width <= 900) {
            cardsToShow = 3;
        } else if (width <= 1200) {
            cardsToShow = 4;
        } else {
            cardsToShow = 7;
        }
    }
    
    function updateSliderPosition() {
        if (sliderItems.length === 0) return;
        
        const cardWidth = sliderItems.first().outerWidth();
        const gap = parseFloat(sliderTrack.css('gap')) || 15; // Get gap from CSS
        const offset = currentIndex * (cardWidth + gap);
        
        sliderTrack.css('transform', 'translateX(-' + offset + 'px)');
        
        // Keep buttons always enabled for infinite loop
        prevBtn.prop('disabled', false);
        nextBtn.prop('disabled', false);
    }
    
    function nextSlide() {
        if (currentIndex < sliderItems.length - cardsToShow) {
            currentIndex++;
        } else {
            // Loop back to start
            currentIndex = 0;
        }
        updateSliderPosition();
    }
    
    function prevSlide() {
        if (currentIndex > 0) {
            currentIndex--;
        } else {
            // Loop back to end
            currentIndex = Math.max(0, sliderItems.length - cardsToShow);
        }
        updateSliderPosition();
    }
    
    // Next button click
    nextBtn.on('click', function() {
        stopAutoplay();
        nextSlide();
        startAutoplay();
    });
    
    // Previous button click
    prevBtn.on('click', function() {
        stopAutoplay();
        prevSlide();
        startAutoplay();
    });
    
    // Autoplay functionality
    function startAutoplay() {
        const sliderWrapper = $('.slider-wrapper');
        const autoplayEnabled = sliderWrapper.data('autoplay') === '1' || sliderWrapper.data('autoplay') === 1;
        const interval = parseInt(sliderWrapper.data('interval')) || 5;
        
        if (autoplayEnabled && sliderItems.length > cardsToShow) {
            autoplayInterval = setInterval(nextSlide, interval * 1000);
        }
    }
    
    function stopAutoplay() {
        if (autoplayInterval) {
            clearInterval(autoplayInterval);
            autoplayInterval = null;
        }
    }
    
    // Pause autoplay on hover
    $('.slider-wrapper').on('mouseenter', stopAutoplay);
    $('.slider-wrapper').on('mouseleave', startAutoplay);
    
    // Update on window resize
    let resizeTimeout;
    $(window).on('resize', function() {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function() {
            updateCardsToShow();
            currentIndex = Math.min(currentIndex, Math.max(0, sliderItems.length - cardsToShow));
            updateSliderPosition();
        }, 250);
    });
    
    // Initialize
    if (sliderItems.length > 0) {
        updateCardsToShow();
        updateSliderPosition();
        startAutoplay();
    }
    
    // Search filters functionality
    $('.filter-btn').on('click', function() {
        var filter = $(this).data('filter');
        
        // Update active button
        $('.filter-btn').removeClass('active');
        $(this).addClass('active');
        
        // Filter posts by category or tag classes
        if (filter === 'all') {
            $('.post-item, .search-result-item, .archive-item').show();
        } else {
            $('.post-item, .search-result-item, .archive-item').hide();
            $('.post-item.' + filter + ', .search-result-item.' + filter + ', .archive-item.' + filter).show();
        }
    });
    
    // Smooth scroll for anchor links
    $('a[href^="#"]').on('click', function(event) {
        var target = $(this.getAttribute('href'));
        if (target.length) {
            event.preventDefault();
            $('html, body').stop().animate({
                scrollTop: target.offset().top - 100
            }, 1000);
        }
    });
    
    // Mobile search toggle
    $('.mobile-search-toggle').on('click', function() {
        $('#mobileSearchBar').addClass('active');
        // Focus on input after bar expands
        setTimeout(function() {
            $('.mobile-search-input').focus();
        }, 300);
    });
    
    // Close mobile search bar
    $('#mobileSearchClose').on('click', function() {
        $('#mobileSearchBar').removeClass('active');
        $('.mobile-search-input').val('');
    });
    
    // Close search bar with ESC key
    $(document).on('keydown', function(event) {
        if (event.key === 'Escape' && $('#mobileSearchBar').hasClass('active')) {
            $('#mobileSearchBar').removeClass('active');
            $('.mobile-search-input').val('');
        }
    });
    
    // Search form enhancements
    $('.search-input').on('focus', function() {
        $(this).parent().addClass('focused');
    }).on('blur', function() {
        $(this).parent().removeClass('focused');
    });
    
    // Lazy loading for images (basic implementation)
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    imageObserver.unobserve(img);
                }
            });
        });
        
        document.querySelectorAll('img[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    }
    
    // Post grid hover effects
    $('.post-item').hover(
        function() {
            $(this).addClass('hovered');
        },
        function() {
            $(this).removeClass('hovered');
        }
    );
    
    // WordPress handles comment replies automatically with comment-reply.js
    // No custom JavaScript needed for comment threading
    
    // Back to top button
    $(window).scroll(function() {
        if ($(this).scrollTop() > 300) {
            $('.back-to-top').addClass('show');
        } else {
            $('.back-to-top').removeClass('show');
        }
    });
    
    $('.back-to-top').on('click', function(e) {
        e.preventDefault();
        $('html, body').animate({scrollTop: 0}, 600, 'swing');
    });
    
    // Full Width Slider functionality with arrow navigation
    const fullwidthSlider = $('#fullwidthSlides');
    const fullwidthPrevBtn = $('#fullwidthPrevBtn');
    const fullwidthNextBtn = $('#fullwidthNextBtn');
    
    if (fullwidthSlider.length) {
        const fullwidthSlides = fullwidthSlider.find('.fullwidth-slide');
        const slideCount = fullwidthSlides.length;
        
        if (slideCount > 0) {
            let fullwidthCurrentSlide = 0;
            let fullwidthAutoplayInterval;
            
            function goToFullwidthSlide(index) {
                // Wrap around
                if (index >= slideCount) {
                    fullwidthCurrentSlide = 0;
                } else if (index < 0) {
                    fullwidthCurrentSlide = slideCount - 1;
                } else {
                    fullwidthCurrentSlide = index;
                }
                
                fullwidthSlider.css('transform', 'translateX(-' + (fullwidthCurrentSlide * 100) + '%)');
                resetFullwidthAutoplay();
            }
            
            function nextFullwidthSlide() {
                goToFullwidthSlide(fullwidthCurrentSlide + 1);
            }
            
            function prevFullwidthSlide() {
                goToFullwidthSlide(fullwidthCurrentSlide - 1);
            }
            
            // Arrow button clicks
            fullwidthNextBtn.on('click', function() {
                nextFullwidthSlide();
            });
            
            fullwidthPrevBtn.on('click', function() {
                prevFullwidthSlide();
            });
            
            function startFullwidthAutoplay() {
                const autoScroll = fullwidthSlider.data('autoplay') === '1' || fullwidthSlider.data('autoplay') === 1;
                const speed = parseInt(fullwidthSlider.data('interval')) || 5;
                
                if (autoScroll && slideCount > 1) {
                    fullwidthAutoplayInterval = setInterval(nextFullwidthSlide, speed * 1000);
                }
            }
            
            function resetFullwidthAutoplay() {
                clearInterval(fullwidthAutoplayInterval);
                startFullwidthAutoplay();
            }
            
            // Start autoplay
            startFullwidthAutoplay();
            
            // Pause on hover
            fullwidthSlider.on('mouseenter', function() {
                clearInterval(fullwidthAutoplayInterval);
            });
            
            fullwidthSlider.on('mouseleave', function() {
                startFullwidthAutoplay();
            });
        }
    }
    
});
