/**
 * 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)';
            }
        });
    });
}
