/**
 * assets/js/index.js
 * Premium Emehama Village Community — Main Script
 */

(function () {
    'use strict';

    // ---------- PRELOADER ----------
    const preloader = document.getElementById('preloader');
    if (preloader) {
        // Fade out after page fully loaded (plus a small delay for smoothness)
        window.addEventListener('load', function () {
            setTimeout(function () {
                preloader.classList.add('hide');
                // Remove from DOM after transition to free resources
                setTimeout(function () {
                    preloader.style.display = 'none';
                }, 800);
            }, 400); // small delay to ensure everything is painted
        });

        // Fallback: if load event already fired (e.g., cached), hide immediately
        if (document.readyState === 'complete') {
            setTimeout(function () {
                preloader.classList.add('hide');
                setTimeout(function () {
                    preloader.style.display = 'none';
                }, 800);
            }, 200);
        }
    }

    // ---------- NAVBAR: STICKY SHRINK ----------
    const header = document.getElementById('siteHeader');
    window.addEventListener('scroll', () => {
        if (window.scrollY > 40) {
            header.classList.add('scrolled');
        } else {
            header.classList.remove('scrolled');
        }
    }, { passive: true });

    // ---------- NEW MOBILE MENU ----------
    const hamburger = document.getElementById('hamburger');
    const mobileMenu = document.getElementById('mobileMenu');
    const menuOverlay = document.getElementById('menuOverlay');
    const menuClose = document.getElementById('mobileMenuClose');
    const mobileLinks = document.querySelectorAll('.mobile-nav-links a');
    let isMenuOpen = false;

    function openMenu() {
        if (isMenuOpen) return;
        isMenuOpen = true;
        mobileMenu.classList.add('active');
        menuOverlay.classList.add('active');
        hamburger.classList.add('active');
        hamburger.setAttribute('aria-expanded', 'true');
        document.body.style.overflow = 'hidden';
        // Focus management: trap focus inside menu? We'll just set focus to first link.
        const firstLink = mobileMenu.querySelector('.mobile-nav-links a');
        if (firstLink) {
            setTimeout(() => firstLink.focus(), 100);
        }
    }

    function closeMenu() {
        if (!isMenuOpen) return;
        isMenuOpen = false;
        mobileMenu.classList.remove('active');
        menuOverlay.classList.remove('active');
        hamburger.classList.remove('active');
        hamburger.setAttribute('aria-expanded', 'false');
        document.body.style.overflow = '';
        // Return focus to hamburger
        hamburger.focus();
    }

    function toggleMenu() {
        if (isMenuOpen) {
            closeMenu();
        } else {
            openMenu();
        }
    }

    // Hamburger click
    hamburger.addEventListener('click', (e) => {
        e.stopPropagation();
        toggleMenu();
    });

    // Close button
    menuClose.addEventListener('click', closeMenu);

    // Overlay click
    menuOverlay.addEventListener('click', closeMenu);

    // Link clicks – close menu
    mobileLinks.forEach(link => {
        link.addEventListener('click', closeMenu);
    });

    // Escape key closes menu
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && isMenuOpen) {
            closeMenu();
        }
    });

    // Resize: if window becomes desktop size, close menu and reset
    let lastWidth = window.innerWidth;
    window.addEventListener('resize', () => {
        const newWidth = window.innerWidth;
        if (newWidth > 768 && lastWidth <= 768) {
            // Switched from mobile to desktop – close menu if open
            if (isMenuOpen) closeMenu();
        }
        lastWidth = newWidth;
    });

    // ---------- EXECUTIVE CAROUSEL ----------
    const executives = [
        { name: 'Aisha Sharma', position: 'President' },
        { name: 'Marcus Chen', position: 'Vice President' },
        { name: 'Elena Rodriguez', position: 'Treasurer' },
        { name: 'James Okafor', position: 'Secretary' },
        { name: 'Priya Patel', position: 'Membership Director' },
        { name: 'Liam O\'Brien', position: 'Events Lead' },
        { name: 'Sophia Kim', position: 'Communications' },
        { name: 'Carlos Mendez', position: 'Community Outreach' },
        { name: 'Amina Diallo', position: 'Diversity & Inclusion' },
        { name: 'Ethan Brooks', position: 'Technology Lead' },
        { name: 'Yuki Tanaka', position: 'Partnerships' }
    ];

    const track = document.getElementById('carouselTrack');
    if (track) {
        let html = '';
        const tripled = [...executives, ...executives, ...executives];
        tripled.forEach(exec => {
            html += `
                <div class="executive-card">
                    <span class="exec-name">${exec.name}</span>
                    <span class="exec-position">${exec.position}</span>
                </div>
            `;
        });
        track.innerHTML = html;

        let isPaused = false;
        let autoScrollTimeout = null;
        let animationId = null;
        const scrollSpeed = 0.8;
        let setWidth = 0;
        let isInitialized = false;

        function getSetWidth() {
            const cards = track.querySelectorAll('.executive-card');
            if (cards.length === 0) return 0;
            const totalCards = executives.length;
            let totalWidth = 0;
            const gap = 24;
            for (let i = 0; i < totalCards; i++) {
                const card = cards[i];
                if (card) {
                    totalWidth += card.offsetWidth + (i < totalCards - 1 ? gap : 0);
                }
            }
            return totalWidth;
        }

        function initCarousel() {
            setWidth = getSetWidth();
            if (setWidth > 0) {
                isInitialized = true;
                track.scrollLeft = setWidth;
            }
        }

        function handleScroll() {
            if (!isInitialized || setWidth === 0) return;
            const currentScroll = track.scrollLeft;
            if (currentScroll >= setWidth * 2) {
                track.scrollLeft = setWidth;
            } else if (currentScroll <= 0) {
                track.scrollLeft = setWidth;
            }
        }

        function step() {
            if (!isInitialized || setWidth === 0) {
                animationId = requestAnimationFrame(step);
                return;
            }
            if (!isPaused) {
                track.scrollLeft += scrollSpeed;
                if (track.scrollLeft >= setWidth * 2) {
                    track.scrollLeft = setWidth;
                }
            }
            animationId = requestAnimationFrame(step);
        }

        function startAnimation() {
            if (animationId) cancelAnimationFrame(animationId);
            step();
        }

        function resetAutoScrollTimer() {
            isPaused = true;
            clearTimeout(autoScrollTimeout);
            autoScrollTimeout = setTimeout(() => {
                isPaused = false;
            }, 3000);
        }

        track.addEventListener('scroll', () => {
            resetAutoScrollTimer();
            handleScroll();
        }, { passive: true });

        track.addEventListener('mouseenter', () => {
            isPaused = true;
            clearTimeout(autoScrollTimeout);
        });

        track.addEventListener('mouseleave', () => {
            clearTimeout(autoScrollTimeout);
            autoScrollTimeout = setTimeout(() => {
                isPaused = false;
            }, 1500);
        });

        track.addEventListener('touchstart', () => {
            isPaused = true;
            clearTimeout(autoScrollTimeout);
        }, { passive: true });

        track.addEventListener('touchend', () => {
            clearTimeout(autoScrollTimeout);
            autoScrollTimeout = setTimeout(() => {
                isPaused = false;
            }, 3000);
        }, { passive: true });

        window.addEventListener('load', () => {
            initCarousel();
            startAnimation();
        });

        let resizeTimeout;
        window.addEventListener('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                const oldSetWidth = setWidth;
                initCarousel();
                if (oldSetWidth > 0 && setWidth > 0) {
                    const ratio = setWidth / oldSetWidth;
                    track.scrollLeft = track.scrollLeft * ratio;
                }
            }, 200);
        });

        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                isPaused = true;
            } else {
                isPaused = false;
            }
        });
    }

    // ---------- ACTIVE NAV LINK (scroll spy) ----------
    const sections = document.querySelectorAll('section[id]');
    const navLinksAll = document.querySelectorAll('.nav-link:not(.nav-login)');

    function updateActiveLink() {
        let current = '';
        const scrollPos = window.scrollY + 150;

        sections.forEach(section => {
            const top = section.offsetTop;
            const height = section.offsetHeight;
            if (scrollPos >= top && scrollPos < top + height) {
                current = section.getAttribute('id');
            }
        });

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

    window.addEventListener('scroll', updateActiveLink, { passive: true });
    window.addEventListener('load', updateActiveLink);
})();