/* ===================================
   ORTIZ PHOTOGRAPHY TEMPLATE
   Custom JavaScript
   =================================== */

(function() {
    'use strict';

    // Template-specific theme key for localStorage
    window.RSL_THEME_KEY = 'ortiz-photography-theme';

    /**
     * Initialize template when DOM is ready
     */
    document.addEventListener('DOMContentLoaded', function() {
        initFooterYear();
        initSmoothScroll();
        initMobileNav();
        initAnimateOnScroll();
        initNavbarActiveState();
    });

    /**
     * Set current year in footer
     */
    function initFooterYear() {
        var yearEl = document.getElementById('ortiz-year');
        if (yearEl) {
            yearEl.textContent = new Date().getFullYear();
        }
    }

    /**
     * Smooth scroll for anchor links
     */
    function initSmoothScroll() {
        var anchors = document.querySelectorAll('a[href^="#"]');

        anchors.forEach(function(anchor) {
            anchor.addEventListener('click', function(e) {
                var targetId = this.getAttribute('href');

                // Skip if it's just "#"
                if (targetId === '#') return;

                var target = document.querySelector(targetId);

                if (target) {
                    e.preventDefault();

                    // Get navbar height for offset
                    var navbar = document.querySelector('.ortiz-nav');
                    var navHeight = navbar ? navbar.offsetHeight : 0;

                    // Calculate scroll position
                    var targetPosition = target.getBoundingClientRect().top + window.pageYOffset - navHeight - 20;

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

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

                    // Set focus to target for accessibility
                    target.setAttribute('tabindex', '-1');
                    target.focus({ preventScroll: true });
                }
            });
        });
    }

    /**
     * Mobile navigation handling
     */
    function initMobileNav() {
        var toggle = document.querySelector('.ortiz-nav .rsl-navbar-toggle');
        var menu = document.querySelector('.ortiz-nav .rsl-navbar-menu');

        if (!toggle || !menu) return;

        // Close menu when clicking a link
        var links = menu.querySelectorAll('.rsl-navbar-link');
        links.forEach(function(link) {
            link.addEventListener('click', function() {
                menu.classList.remove('active');
                toggle.setAttribute('aria-expanded', 'false');
            });
        });

        // Close menu when clicking outside
        document.addEventListener('click', function(e) {
            if (!toggle.contains(e.target) && !menu.contains(e.target)) {
                menu.classList.remove('active');
                toggle.setAttribute('aria-expanded', 'false');
            }
        });
    }

    /**
     * Initialize animate on scroll
     * Uses IntersectionObserver for performance
     */
    function initAnimateOnScroll() {
        // Respect user preference for reduced motion
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            // Show all elements immediately
            document.querySelectorAll('[data-animate]').forEach(function(el) {
                el.classList.add('animate-in');
            });
            return;
        }

        var elements = document.querySelectorAll('[data-animate]');

        if ('IntersectionObserver' in window) {
            var observer = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        var delay = entry.target.getAttribute('data-animate-delay') || 0;
                        setTimeout(function() {
                            entry.target.classList.add('animate-in');
                        }, parseInt(delay, 10));
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.1,
                rootMargin: '0px 0px -50px 0px'
            });

            elements.forEach(function(el) {
                observer.observe(el);
            });
        } else {
            // Fallback for older browsers
            elements.forEach(function(el) {
                el.classList.add('animate-in');
            });
        }
    }

    /**
     * Update navbar active state on scroll
     */
    function initNavbarActiveState() {
        var sections = document.querySelectorAll('section[id]');
        var navLinks = document.querySelectorAll('.ortiz-nav .rsl-navbar-link[href^="#"]');

        if (sections.length === 0 || navLinks.length === 0) return;

        function updateActiveLink() {
            var scrollPos = window.scrollY + 150;

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

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

        // Throttle scroll events for performance
        var ticking = false;
        window.addEventListener('scroll', function() {
            if (!ticking) {
                window.requestAnimationFrame(function() {
                    updateActiveLink();
                    ticking = false;
                });
                ticking = true;
            }
        });

        // Initial call
        updateActiveLink();
    }

})();
