/**
 * Tech Magazine Template - JavaScript
 * Handles off-canvas filters and smooth scrolling
 */

(function() {
    'use strict';

    // Initialize Off-Canvas Filters
    const openFiltersBtn = document.getElementById('openFiltersBtn');
    const offCanvasOverlay = document.getElementById('offCanvasOverlay');
    const themeToggleBtn = document.getElementById('theme-toggle');

    if (openFiltersBtn) {
        openFiltersBtn.addEventListener('click', function() {
            // Close mobile menu if open
            const navbar = document.querySelector('.rsl-navbar');
            const toggle = navbar?.querySelector('.rsl-navbar-toggle');
            const menu = navbar?.querySelector('.rsl-navbar-menu');

            if (menu?.classList.contains('mobile-open')) {
                toggle?.click();
            }

            // Open off-canvas
            window.toggleOffCanvas('filtersPanel');
        });
    }

    // Close off-canvas when clicking close button
    document.querySelectorAll('.off-canvas-close').forEach(btn => {
        btn.addEventListener('click', function() {
            window.closeAllOffCanvas();
        });
    });

    // Close off-canvas when clicking overlay
    if (offCanvasOverlay) {
        offCanvasOverlay.addEventListener('click', function() {
            window.closeAllOffCanvas();
        });
    }

    // Theme toggle in navbar
    if (themeToggleBtn) {
        themeToggleBtn.addEventListener('click', function() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('rsl-theme', newTheme);
        });
    }

    // Smooth scroll for anchor links (but not for mega menu toggles)
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            const href = this.getAttribute('href');

            // Skip if this is a mega menu toggle (has aria-haspopup)
            if (this.getAttribute('aria-haspopup') === 'true') {
                return;
            }

            // Only handle anchor links, not just "#"
            if (href !== '#' && href.length > 1) {
                const targetId = href.substring(1);
                const targetElement = document.getElementById(targetId);

                if (targetElement) {
                    e.preventDefault();

                    const navHeight = document.querySelector('.tech-nav').offsetHeight;
                    const targetPosition = targetElement.offsetTop - navHeight - 20;

                    window.scrollTo({
                        top: targetPosition,
                        behavior: 'smooth'
                    });

                    // Close mobile menu if open
                    const navbarMenu = document.querySelector('.rsl-navbar-menu');
                    if (navbarMenu && navbarMenu.classList.contains('mobile-open')) {
                        navbarMenu.classList.remove('mobile-open');
                    }
                }
            }
        });
    });

    // Newsletter form handler
    const newsletterForm = document.querySelector('.newsletter-form');
    if (newsletterForm) {
        newsletterForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const email = this.querySelector('input[type="email"]').value;
            alert(`Thanks for subscribing with ${email}! This is a demo.`);
            this.reset();
        });
    }

    // Add scroll animations for cards
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);

    // Observe featured cards, tutorial cards, and news cards
    const cards = document.querySelectorAll('.featured-card, .tutorial-card, .news-card, .community-card');
    cards.forEach(card => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(30px)';
        card.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(card);
    });

    // Update active nav link on scroll
    function updateActiveNavLink() {
        const sections = document.querySelectorAll('section[id]');
        const navLinks = document.querySelectorAll('.rsl-navbar-link[href^="#"]');
        const navHeight = document.querySelector('.tech-nav').offsetHeight;

        let currentSection = '';

        sections.forEach(section => {
            const sectionTop = section.offsetTop - navHeight - 100;
            const sectionHeight = section.offsetHeight;

            if (window.scrollY >= sectionTop && window.scrollY < sectionTop + sectionHeight) {
                currentSection = section.getAttribute('id');
            }
        });

        navLinks.forEach(link => {
            link.classList.remove('active');
            const href = link.getAttribute('href');
            if (href === `#${currentSection}`) {
                link.classList.add('active');
            }
        });
    }

    // Throttle function for scroll event
    function throttle(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    window.addEventListener('scroll', throttle(updateActiveNavLink, 100));
    updateActiveNavLink();

})();
