/**
 * El Captain — Public Website Interactivity
 * Section animations, counters, navbar transitions, gallery lightbox
 */

document.addEventListener('DOMContentLoaded', () => {
    initNavbar();
    initSectionAnimations();
    initRevealAnimations();
    initCounterAnimations();
    initSmoothScroll();
    initGalleryLightbox();
    initFAQAccordion();
});

function initNavbar() {
    const nav = document.querySelector('.site-nav');
    if (!nav) return;

    const onScroll = () => {
        if (window.scrollY > 60) {
            nav.classList.add('site-nav--scrolled');
        } else {
            nav.classList.remove('site-nav--scrolled');
        }
    };

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

function initSectionAnimations() {
    const body = document.body;
    if (body.dataset.animations === 'false') return;

    const sections = document.querySelectorAll('[data-animation]');
    if (!sections.length) return;

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

    sections.forEach((el, i) => {
        el.style.transitionDelay = `${i * 0.08}s`;
        observer.observe(el);
    });
}

function initRevealAnimations() {
    const elements = document.querySelectorAll('.reveal');
    if (!elements.length) return;

    const observer = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('reveal--visible');
                    observer.unobserve(entry.target);
                }
            });
        },
        { threshold: 0.15, rootMargin: '0px 0px -50px 0px' }
    );

    elements.forEach((el) => observer.observe(el));
}

function initCounterAnimations() {
    const counters = document.querySelectorAll('[data-counter]');
    if (!counters.length) return;

    const observer = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    animateCounter(entry.target);
                    observer.unobserve(entry.target);
                }
            });
        },
        { threshold: 0.5 }
    );

    counters.forEach((el) => observer.observe(el));
}

function animateCounter(el) {
    const target = parseInt(el.dataset.counter, 10);
    const duration = 2000;
    const start = performance.now();
    const suffix = el.dataset.suffix || '';

    function update(now) {
        const elapsed = now - start;
        const progress = Math.min(elapsed / duration, 1);
        const eased = 1 - Math.pow(1 - progress, 4);
        const current = Math.floor(eased * target);

        el.textContent = current.toLocaleString('ar-EG') + suffix;

        if (progress < 1) {
            requestAnimationFrame(update);
        }
    }

    requestAnimationFrame(update);
}

function initSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach((link) => {
        link.addEventListener('click', (e) => {
            const targetId = link.getAttribute('href').slice(1);
            if (!targetId) return;
            const target = document.getElementById(targetId);
            if (target) {
                e.preventDefault();
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });
}

function initGalleryLightbox() {
    const items = document.querySelectorAll('.gallery-item[data-src]');
    if (!items.length) return;

    let lightbox = null;

    items.forEach((item) => {
        item.addEventListener('click', () => {
            const src = item.dataset.src;
            if (!src) return;

            if (!lightbox) {
                lightbox = document.createElement('div');
                lightbox.className = 'fixed inset-0 z-[200] bg-black/90 flex items-center justify-center p-4 cursor-pointer opacity-0 transition-opacity duration-300';
                lightbox.innerHTML = '<img class="max-w-full max-h-[90vh] rounded-lg object-contain transform scale-95 transition-transform duration-300" />';
                lightbox.addEventListener('click', () => {
                    lightbox.classList.remove('opacity-100');
                    lightbox.querySelector('img').classList.remove('scale-100');
                    lightbox.querySelector('img').classList.add('scale-95');
                    setTimeout(() => lightbox.remove(), 300);
                    lightbox = null;
                });
                document.body.appendChild(lightbox);
            }

            lightbox.querySelector('img').src = src;
            requestAnimationFrame(() => {
                lightbox.classList.add('opacity-100');
                lightbox.querySelector('img').classList.remove('scale-95');
                lightbox.querySelector('img').classList.add('scale-100');
            });
        });
    });
}

function initFAQAccordion() {
    const items = document.querySelectorAll('.faq-item');
    if (!items.length) return;

    items.forEach((item) => {
        const trigger = item.querySelector('[data-faq-trigger]');
        const content = item.querySelector('[data-faq-content]');
        const icon = item.querySelector('[data-faq-icon]');
        if (!trigger || !content) return;

        trigger.addEventListener('click', () => {
            const isOpen = item.dataset.open === 'true';

            items.forEach((other) => {
                if (other !== item) {
                    other.dataset.open = 'false';
                    const otherContent = other.querySelector('[data-faq-content]');
                    const otherIcon = other.querySelector('[data-faq-icon]');
                    if (otherContent) otherContent.style.maxHeight = '0';
                    if (otherIcon) otherIcon.style.transform = '';
                }
            });

            if (isOpen) {
                item.dataset.open = 'false';
                content.style.maxHeight = '0';
                if (icon) icon.style.transform = '';
            } else {
                item.dataset.open = 'true';
                content.style.maxHeight = content.scrollHeight + 'px';
                if (icon) icon.style.transform = 'rotate(180deg)';
            }
        });
    });
}

/* ============================================================
   Website Builder v3 — stagger + parallax
   Complements the existing [data-animation] observer.
   ============================================================ */
(function () {
    const motionAllowed = () =>
        document.body?.dataset.animations !== 'false' &&
        !window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    /**
     * Tags the direct children of a staggered block with an index so CSS can
     * cascade their transition-delay without hard-coding a child count.
     */
    function initStagger() {
        document.querySelectorAll('[data-animation-stagger]').forEach((block) => {
            const step = parseInt(block.dataset.animationStagger || '0', 10);
            if (!step) return;

            block.style.setProperty('--stagger-step', `${step}ms`);

            const targets = block.querySelectorAll('.ec-stagger-item');
            targets.forEach((el, i) => el.style.setProperty('--stagger-index', i));
        });
    }

    /**
     * Background parallax. Uses rAF-throttled scroll rather than a scroll
     * handler doing layout work on every event.
     */
    function initParallax() {
        const layers = Array.from(document.querySelectorAll('[data-parallax="true"]'));
        if (!layers.length || !motionAllowed()) return;

        let ticking = false;

        const update = () => {
            const viewportH = window.innerHeight;

            layers.forEach((layer) => {
                const host = layer.parentElement;
                if (!host) return;

                const rect = host.getBoundingClientRect();
                if (rect.bottom < 0 || rect.top > viewportH) return;

                // -1..1 across the viewport, scaled to a gentle offset.
                const progress = (rect.top + rect.height / 2 - viewportH / 2) / viewportH;
                layer.style.setProperty('--parallax-offset', `${(progress * -40).toFixed(2)}px`);
            });

            ticking = false;
        };

        const onScroll = () => {
            if (ticking) return;
            ticking = true;
            window.requestAnimationFrame(update);
        };

        window.addEventListener('scroll', onScroll, { passive: true });
        window.addEventListener('resize', onScroll, { passive: true });
        update();
    }

    function init() {
        initStagger();
        initParallax();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
