/**
 * Photography Portfolio Template - Custom JavaScript
 * Sarah Mitchell Photography
 *
 * Features:
 * - Mobile navigation toggle
 * - Testimonial slider
 * - Gallery category filter
 * - Lightbox gallery viewer
 * - Smooth scroll for anchor links
 * - FAQ accordion
 * - Hero parallax effect
 * - Animation on scroll
 */

(function() {
    'use strict';

    // ============================================
    // Mobile Navigation Toggle
    // ============================================
    function initNavigation() {
        const navToggle = document.querySelector('.nav-toggle');
        const navMenu = document.querySelector('.nav-menu');

        if (!navToggle || !navMenu) return;

        navToggle.addEventListener('click', function() {
            const isExpanded = this.getAttribute('aria-expanded') === 'true';
            this.setAttribute('aria-expanded', String(!isExpanded));
            this.classList.toggle('active');
            navMenu.classList.toggle('active');
            document.body.classList.toggle('nav-open');
        });

        // Close menu when clicking a link
        navMenu.querySelectorAll('.nav-link').forEach(function(link) {
            link.addEventListener('click', function() {
                navToggle.setAttribute('aria-expanded', 'false');
                navToggle.classList.remove('active');
                navMenu.classList.remove('active');
                document.body.classList.remove('nav-open');
            });
        });

        // Close menu on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && navMenu.classList.contains('active')) {
                navToggle.setAttribute('aria-expanded', 'false');
                navToggle.classList.remove('active');
                navMenu.classList.remove('active');
                document.body.classList.remove('nav-open');
                navToggle.focus();
            }
        });
    }

    // ============================================
    // Testimonial Slider
    // ============================================
    function initTestimonialSlider() {
        const testimonials = document.querySelectorAll('.testimonial');
        const dots = document.querySelectorAll('.testimonial-dot');

        if (testimonials.length === 0 || dots.length === 0) return;

        let currentIndex = 0;
        let autoSlideInterval;

        function showTestimonial(index) {
            testimonials.forEach(function(t, i) {
                t.classList.toggle('active', i === index);
            });
            dots.forEach(function(d, i) {
                d.classList.toggle('active', i === index);
                d.setAttribute('aria-selected', String(i === index));
            });
            currentIndex = index;
        }

        function nextTestimonial() {
            const next = (currentIndex + 1) % testimonials.length;
            showTestimonial(next);
        }

        // Dot click handlers
        dots.forEach(function(dot, index) {
            dot.addEventListener('click', function() {
                showTestimonial(index);
                resetAutoSlide();
            });

            dot.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    showTestimonial(index);
                    resetAutoSlide();
                }
            });
        });

        // Auto-advance
        function startAutoSlide() {
            autoSlideInterval = setInterval(nextTestimonial, 6000);
        }

        function resetAutoSlide() {
            clearInterval(autoSlideInterval);
            startAutoSlide();
        }

        startAutoSlide();

        // Pause on hover
        const slider = document.querySelector('.testimonials-slider');
        if (slider) {
            slider.addEventListener('mouseenter', function() {
                clearInterval(autoSlideInterval);
            });
            slider.addEventListener('mouseleave', startAutoSlide);
        }
    }

    // ============================================
    // Gallery Filter
    // ============================================
    function initGalleryFilter() {
        const filterButtons = document.querySelectorAll('.filter-btn');
        const galleryItems = document.querySelectorAll('.gallery-item');
        const statusRegion = document.getElementById('gallery-status');

        if (filterButtons.length === 0 || galleryItems.length === 0) return;

        function activateFilter(button) {
            const filter = button.dataset.filter;

            // Update active button
            filterButtons.forEach(function(btn) {
                btn.classList.remove('active');
                btn.setAttribute('aria-selected', 'false');
                btn.setAttribute('tabindex', '-1');
            });
            button.classList.add('active');
            button.setAttribute('aria-selected', 'true');
            button.setAttribute('tabindex', '0');

            // Filter items with animation
            let visibleCount = 0;
            galleryItems.forEach(function(item) {
                const category = item.dataset.category;
                const shouldShow = filter === 'all' || category === filter;

                if (shouldShow) {
                    visibleCount++;
                    item.style.display = '';
                    item.style.animation = 'fadeIn 0.4s ease forwards';
                } else {
                    item.style.animation = 'fadeOut 0.3s ease forwards';
                    setTimeout(function() {
                        if (!item.classList.contains('filtered-in')) {
                            item.style.display = 'none';
                        }
                    }, 300);
                }

                item.classList.toggle('filtered-in', shouldShow);
            });

            // Announce to screen readers
            if (statusRegion) {
                const categoryName = filter === 'all' ? 'all categories' : filter;
                statusRegion.textContent = 'Showing ' + visibleCount + ' photos in ' + categoryName;
            }
        }

        // Click handlers
        filterButtons.forEach(function(button) {
            button.addEventListener('click', function() {
                activateFilter(this);
            });
        });

        // Keyboard navigation (arrow keys for tab-like behavior)
        filterButtons.forEach(function(button, index) {
            button.addEventListener('keydown', function(e) {
                let targetIndex = index;

                switch (e.key) {
                    case 'ArrowRight':
                    case 'ArrowDown':
                        e.preventDefault();
                        targetIndex = (index + 1) % filterButtons.length;
                        break;
                    case 'ArrowLeft':
                    case 'ArrowUp':
                        e.preventDefault();
                        targetIndex = (index - 1 + filterButtons.length) % filterButtons.length;
                        break;
                    case 'Home':
                        e.preventDefault();
                        targetIndex = 0;
                        break;
                    case 'End':
                        e.preventDefault();
                        targetIndex = filterButtons.length - 1;
                        break;
                    default:
                        return;
                }

                filterButtons[targetIndex].focus();
                activateFilter(filterButtons[targetIndex]);
            });
        });

        // Set initial tabindex
        filterButtons.forEach(function(btn, i) {
            btn.setAttribute('tabindex', i === 0 ? '0' : '-1');
        });
    }

    // ============================================
    // Lightbox Gallery
    // ============================================
    function initLightbox() {
        const galleryLinks = document.querySelectorAll('[data-lightbox="gallery"]');
        const lightbox = document.getElementById('lightbox');

        if (galleryLinks.length === 0 || !lightbox) return;

        const lightboxImage = lightbox.querySelector('.lightbox-image');
        const lightboxTitle = lightbox.querySelector('.lightbox-title');
        const lightboxMeta = lightbox.querySelector('.lightbox-meta');
        const closeBtn = lightbox.querySelector('.lightbox-close');
        const prevBtn = lightbox.querySelector('.lightbox-prev');
        const nextBtn = lightbox.querySelector('.lightbox-next');
        const currentCounter = lightbox.querySelector('.current');
        const totalCounter = lightbox.querySelector('.total');

        let currentIndex = 0;
        let visibleItems = [];
        let lastFocusedElement = null;

        function updateVisibleItems() {
            visibleItems = Array.from(galleryLinks).filter(function(link) {
                return link.closest('.gallery-item').style.display !== 'none';
            });
            if (totalCounter) {
                totalCounter.textContent = visibleItems.length;
            }
        }

        function openLightbox(index) {
            updateVisibleItems();
            if (index < 0 || index >= visibleItems.length) return;

            lastFocusedElement = document.activeElement;
            currentIndex = index;

            const link = visibleItems[index];
            const item = link.closest('.gallery-item');
            const title = item.querySelector('.gallery-title');
            const meta = item.querySelector('.gallery-meta');

            lightboxImage.src = link.href;
            lightboxImage.alt = item.querySelector('img').alt;
            lightboxTitle.textContent = title ? title.textContent : '';
            lightboxMeta.textContent = meta ? meta.textContent : '';

            if (currentCounter) {
                currentCounter.textContent = index + 1;
            }

            lightbox.hidden = false;
            document.body.style.overflow = 'hidden';
            closeBtn.focus();

            // Trap focus in lightbox
            lightbox.addEventListener('keydown', trapFocus);
        }

        function closeLightbox() {
            lightbox.hidden = true;
            document.body.style.overflow = '';
            lightbox.removeEventListener('keydown', trapFocus);

            if (lastFocusedElement) {
                lastFocusedElement.focus();
            }
        }

        function showPrev() {
            updateVisibleItems();
            currentIndex = (currentIndex - 1 + visibleItems.length) % visibleItems.length;
            openLightbox(currentIndex);
        }

        function showNext() {
            updateVisibleItems();
            currentIndex = (currentIndex + 1) % visibleItems.length;
            openLightbox(currentIndex);
        }

        function trapFocus(e) {
            const focusableElements = lightbox.querySelectorAll(
                'button, [href], [tabindex]:not([tabindex="-1"])'
            );
            const firstElement = focusableElements[0];
            const lastElement = focusableElements[focusableElements.length - 1];

            if (e.key === 'Tab') {
                if (e.shiftKey && document.activeElement === firstElement) {
                    e.preventDefault();
                    lastElement.focus();
                } else if (!e.shiftKey && document.activeElement === lastElement) {
                    e.preventDefault();
                    firstElement.focus();
                }
            }
        }

        // Event listeners
        galleryLinks.forEach(function(link, index) {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                updateVisibleItems();
                const visibleIndex = visibleItems.indexOf(link);
                openLightbox(visibleIndex >= 0 ? visibleIndex : 0);
            });
        });

        closeBtn.addEventListener('click', closeLightbox);
        prevBtn.addEventListener('click', showPrev);
        nextBtn.addEventListener('click', showNext);

        // Keyboard navigation
        document.addEventListener('keydown', function(e) {
            if (lightbox.hidden) return;

            switch (e.key) {
                case 'Escape':
                    closeLightbox();
                    break;
                case 'ArrowLeft':
                    showPrev();
                    break;
                case 'ArrowRight':
                    showNext();
                    break;
            }
        });

        // Close on background click
        lightbox.addEventListener('click', function(e) {
            if (e.target === lightbox || e.target.classList.contains('lightbox-content')) {
                closeLightbox();
            }
        });
    }

    // ============================================
    // Smooth Scroll for Anchor Links
    // ============================================
    function initSmoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(function(anchor) {
            anchor.addEventListener('click', function(e) {
                const targetId = this.getAttribute('href');
                if (targetId === '#') return;

                const target = document.querySelector(targetId);
                if (target) {
                    e.preventDefault();
                    const navHeight = document.querySelector('.site-nav').offsetHeight;
                    const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - navHeight - 20;

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

                    // Update URL without scrolling
                    history.pushState(null, '', targetId);
                }
            });
        });
    }

    // ============================================
    // Sticky Navigation on Scroll
    // ============================================
    function initStickyNav() {
        const nav = document.querySelector('.site-nav');
        if (!nav) return;

        let lastScroll = 0;

        window.addEventListener('scroll', function() {
            const currentScroll = window.pageYOffset;

            if (currentScroll > 100) {
                nav.classList.add('scrolled');
            } else {
                nav.classList.remove('scrolled');
            }

            // Hide/show on scroll direction
            if (currentScroll > lastScroll && currentScroll > 400) {
                nav.classList.add('nav-hidden');
            } else {
                nav.classList.remove('nav-hidden');
            }

            lastScroll = currentScroll;
        }, { passive: true });
    }

    // ============================================
    // Animation on Scroll
    // ============================================
    function initScrollAnimations() {
        const animatedElements = document.querySelectorAll('.animate-fade-up, .service-card, .philosophy-card');

        if ('IntersectionObserver' in window) {
            const observer = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('animated');
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.1,
                rootMargin: '0px 0px -50px 0px'
            });

            animatedElements.forEach(function(el) {
                observer.observe(el);
            });
        } else {
            // Fallback for older browsers
            animatedElements.forEach(function(el) {
                el.classList.add('animated');
            });
        }
    }

    // ============================================
    // Hero Parallax Effect (Subtle)
    // ============================================
    function initHeroParallax() {
        const hero = document.querySelector('.hero');
        const heroBg = document.querySelector('.hero-bg img');

        if (!hero || !heroBg) return;

        // Check for reduced motion preference
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

        window.addEventListener('scroll', function() {
            const scrolled = window.pageYOffset;
            const heroHeight = hero.offsetHeight;

            if (scrolled < heroHeight) {
                const parallax = scrolled * 0.3;
                heroBg.style.transform = 'translateY(' + parallax + 'px) scale(1.1)';
            }
        }, { passive: true });
    }

    // ============================================
    // Form Validation Enhancement
    // ============================================
    function initFormValidation() {
        const form = document.querySelector('.contact-form');
        if (!form) return;

        form.addEventListener('submit', function(e) {
            const requiredFields = form.querySelectorAll('[required]');
            let hasErrors = false;

            requiredFields.forEach(function(field) {
                const errorClass = 'field-error';
                field.classList.remove(errorClass);

                if (!field.value.trim()) {
                    field.classList.add(errorClass);
                    hasErrors = true;
                }

                // Email validation
                if (field.type === 'email' && field.value) {
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(field.value)) {
                        field.classList.add(errorClass);
                        hasErrors = true;
                    }
                }
            });

            if (hasErrors) {
                e.preventDefault();
                const firstError = form.querySelector('.field-error');
                if (firstError) {
                    firstError.focus();
                }
            }
        });

        // Clear error on input
        form.querySelectorAll('input, textarea, select').forEach(function(field) {
            field.addEventListener('input', function() {
                this.classList.remove('field-error');
            });
        });
    }

    // ============================================
    // Theme Toggle - Handled by RSL theme-toggle.js
    // ============================================
    // Note: Theme toggle functionality is provided by javascript/theme-toggle.js
    // which automatically attaches click handlers to .rsl-theme-toggle buttons
    // and manages localStorage persistence. No duplicate code needed here.

    // ============================================
    // Initialize All Features
    // ============================================
    function init() {
        // Theme toggle handled by RSL theme-toggle.js
        initNavigation();
        initTestimonialSlider();
        initGalleryFilter();
        initLightbox();
        initSmoothScroll();
        initStickyNav();
        initScrollAnimations();
        initHeroParallax();
        initFormValidation();
    }

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

})();
