/**
 * Meridian Collective - Custom Template JavaScript
 * Heritage Artisan Goods Brand Experience
 */

(function() {
    'use strict';

    // =========================================
    // Theme Toggle with Custom Storage Key
    // =========================================
    function initThemeToggle() {
        const toggle = document.querySelector('.rsl-theme-toggle');
        if (!toggle) return;

        const THEME_KEY = window.RSL_THEME_KEY || 'meridian-theme';

        // Get current theme
        function getTheme() {
            return localStorage.getItem(THEME_KEY) || 'light';
        }

        // Set theme
        function setTheme(theme) {
            localStorage.setItem(THEME_KEY, theme);
            document.documentElement.setAttribute('data-theme', theme);
        }

        // Toggle handler
        toggle.addEventListener('click', function() {
            const currentTheme = getTheme();
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            setTheme(newTheme);
        });
    }

    // =========================================
    // Smooth Scroll for Anchor Links
    // =========================================
    function initSmoothScroll() {
        const links = document.querySelectorAll('a[href^="#"]');

        links.forEach(function(link) {
            link.addEventListener('click', function(e) {
                const href = this.getAttribute('href');
                if (href === '#') return;

                const target = document.querySelector(href);
                if (!target) return;

                e.preventDefault();

                // Account for sticky navbar
                const navbarHeight = document.querySelector('.mc-navbar')?.offsetHeight || 0;
                const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - navbarHeight - 20;

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

                // Update URL without jumping
                history.pushState(null, null, href);
            });
        });
    }

    // =========================================
    // Navbar Scroll Effects
    // =========================================
    function initNavbarEffects() {
        const navbar = document.querySelector('.mc-navbar');
        if (!navbar) return;

        let lastScrollY = window.scrollY;
        let ticking = false;

        function updateNavbar() {
            const scrollY = window.scrollY;

            // Add/remove scrolled class
            if (scrollY > 50) {
                navbar.classList.add('mc-navbar-scrolled');
            } else {
                navbar.classList.remove('mc-navbar-scrolled');
            }

            // Hide/show on scroll direction (optional - uncomment if desired)
            /*
            if (scrollY > lastScrollY && scrollY > 200) {
                navbar.style.transform = 'translateY(-100%)';
            } else {
                navbar.style.transform = 'translateY(0)';
            }
            lastScrollY = scrollY;
            */

            ticking = false;
        }

        window.addEventListener('scroll', function() {
            if (!ticking) {
                window.requestAnimationFrame(updateNavbar);
                ticking = true;
            }
        }, { passive: true });
    }

    // =========================================
    // Chapter Progress Indicator (Optional)
    // =========================================
    function initChapterProgress() {
        const sections = document.querySelectorAll('.mc-section[id]');
        if (sections.length === 0) return;

        const navLinks = document.querySelectorAll('.rsl-navbar-link[href^="#"]');

        function updateActiveSection() {
            const scrollPosition = window.scrollY + 150;

            sections.forEach(function(section) {
                const sectionTop = section.offsetTop;
                const sectionHeight = section.offsetHeight;
                const sectionId = section.getAttribute('id');

                if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
                    navLinks.forEach(function(link) {
                        link.classList.remove('mc-nav-active');
                        if (link.getAttribute('href') === '#' + sectionId) {
                            link.classList.add('mc-nav-active');
                        }
                    });
                }
            });
        }

        // Throttled scroll handler
        let scrollTimeout;
        window.addEventListener('scroll', function() {
            if (scrollTimeout) return;
            scrollTimeout = setTimeout(function() {
                updateActiveSection();
                scrollTimeout = null;
            }, 100);
        }, { passive: true });

        // Initial check
        updateActiveSection();
    }

    // =========================================
    // Parallax Effect for Hero (Reduced Motion Aware)
    // =========================================
    function initParallax() {
        // Check for reduced motion preference
        const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        if (prefersReducedMotion) return;

        const hero = document.querySelector('.mc-hero');
        if (!hero) return;

        let ticking = false;

        function updateParallax() {
            const scrollY = window.scrollY;
            const heroHeight = hero.offsetHeight;

            if (scrollY < heroHeight) {
                const parallaxValue = scrollY * 0.3;
                hero.style.setProperty('--parallax-offset', parallaxValue + 'px');
            }

            ticking = false;
        }

        window.addEventListener('scroll', function() {
            if (!ticking) {
                window.requestAnimationFrame(updateParallax);
                ticking = true;
            }
        }, { passive: true });
    }

    // =========================================
    // Newsletter Form Enhancement
    // =========================================
    function initNewsletterForm() {
        const form = document.querySelector('.mc-newsletter-form');
        if (!form) return;

        form.addEventListener('submit', function(e) {
            e.preventDefault();

            const emailInput = form.querySelector('input[type="email"]');
            const submitBtn = form.querySelector('button[type="submit"]');
            const email = emailInput.value.trim();

            if (!email) return;

            // Disable button and show loading state
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span>Subscribing...</span><i class="fas fa-spinner fa-spin"></i>';

            // Simulate API call (replace with actual endpoint)
            setTimeout(function() {
                // Success state
                submitBtn.innerHTML = '<span>Subscribed!</span><i class="fas fa-check"></i>';
                submitBtn.classList.add('mc-btn-success');
                emailInput.value = '';

                // Reset after 3 seconds
                setTimeout(function() {
                    submitBtn.disabled = false;
                    submitBtn.classList.remove('mc-btn-success');
                    submitBtn.innerHTML = '<span>Subscribe</span><i class="fas fa-arrow-right"></i>';
                }, 3000);

            }, 1500);
        });
    }

    // =========================================
    // Intersection Observer for Reveal Animations
    // =========================================
    function initRevealAnimations() {
        // Check for reduced motion preference
        const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        if (prefersReducedMotion) return;

        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('mc-revealed');
                    observer.unobserve(entry.target);
                }
            });
        }, observerOptions);

        // Observe elements with data-animate attribute that RSL's animate-on-scroll might miss
        const elementsToReveal = document.querySelectorAll('[data-mc-reveal]');
        elementsToReveal.forEach(function(el) {
            observer.observe(el);
        });
    }

    // =========================================
    // Lazy Load Images (Enhancement)
    // =========================================
    function initLazyLoad() {
        // Native lazy loading is already used via loading="lazy"
        // This is an enhancement for older browsers

        if ('loading' in HTMLImageElement.prototype) {
            // Native lazy loading supported
            return;
        }

        // Fallback for older browsers
        const lazyImages = document.querySelectorAll('img[loading="lazy"]');

        if ('IntersectionObserver' in window) {
            const imageObserver = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src || img.src;
                        imageObserver.unobserve(img);
                    }
                });
            });

            lazyImages.forEach(function(img) {
                imageObserver.observe(img);
            });
        }
    }

    // =========================================
    // Accessibility Enhancements
    // =========================================
    function initAccessibility() {
        // Focus visible polyfill behavior
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Tab') {
                document.body.classList.add('mc-keyboard-nav');
            }
        });

        document.addEventListener('mousedown', function() {
            document.body.classList.remove('mc-keyboard-nav');
        });

        // Escape key closes any open modals/menus
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                // Close mobile menu if open
                const mobileToggle = document.querySelector('.rsl-navbar-toggle[aria-expanded="true"]');
                if (mobileToggle) {
                    mobileToggle.click();
                }
            }
        });
    }

    // =========================================
    // Counter Animation for Stats (if KPI cards need enhancement)
    // =========================================
    function initCounterAnimation() {
        const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        if (prefersReducedMotion) return;

        const counters = document.querySelectorAll('[data-mc-counter]');

        const observerOptions = {
            threshold: 0.5
        };

        const observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    animateCounter(entry.target);
                    observer.unobserve(entry.target);
                }
            });
        }, observerOptions);

        counters.forEach(function(counter) {
            observer.observe(counter);
        });

        function animateCounter(element) {
            const target = parseInt(element.dataset.mcCounter, 10);
            const duration = 2000;
            const start = 0;
            const startTime = performance.now();

            function updateCounter(currentTime) {
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);
                const easeProgress = 1 - Math.pow(1 - progress, 3); // Ease out cubic
                const current = Math.floor(start + (target - start) * easeProgress);

                element.textContent = current.toLocaleString();

                if (progress < 1) {
                    requestAnimationFrame(updateCounter);
                } else {
                    element.textContent = target.toLocaleString();
                }
            }

            requestAnimationFrame(updateCounter);
        }
    }

    // =========================================
    // Initialize All Functions
    // =========================================
    function init() {
        initThemeToggle();
        initSmoothScroll();
        initNavbarEffects();
        initChapterProgress();
        initParallax();
        initNewsletterForm();
        initRevealAnimations();
        initLazyLoad();
        initAccessibility();
        initCounterAnimation();

        // Log initialization
        console.log('Meridian Collective: Template initialized');
    }

    // Run on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
