// Contacto overlay (abrir/cerrar de forma robusta)
const overlay = document.getElementById('contacto-overlay');

// Bloqueo de scroll cuando sidebar u overlay estén activos
function updateBodyScroll() {
    const lock = (sidebar?.classList.contains('active') || overlay?.classList.contains('active'));
    document.documentElement.style.overflowY = lock ? 'hidden' : '';
    document.body.style.overflow = lock ? 'hidden' : '';
}

function openContacto(e) {
    e?.preventDefault();
    if (!overlay) return;
    overlay.style.display = 'flex';
    // Espera al siguiente frame para aplicar la animación
    requestAnimationFrame(() => {
        overlay.classList.add('active');
        // Enfocar botón de cierre para accesibilidad
        document.getElementById('close-contacto')?.focus();
        updateBodyScroll();
    });
    // Cierra el sidebar si estuviera abierto
    closeSidebar();
}

function closeContacto(e) {
    e?.preventDefault?.();
    if (!overlay) return;
    overlay.classList.remove('active');
    setTimeout(() => {
        overlay.style.display = 'none';
        updateBodyScroll();
    }, 500);
}

// Abridores: enlaces "Contáctanos" del navbar (a.nav-a.ca) y del sidebar (href="contacto.php")
document.querySelectorAll('a.nav-a.ca, .sidebar-menu a[href="contacto.php"], .footer a[href="contacto.php"]').forEach((el) => {
    el.addEventListener('click', openContacto);
});

// Botón de cierre del modal
document.getElementById('close-contacto')?.addEventListener('click', closeContacto);

// Cierre haciendo clic fuera del contenido (en el fondo del overlay)
overlay?.addEventListener('click', (e) => {
    if (e.target === overlay) closeContacto();
});

// Mostrar el botón cuando se baja del nav
window.addEventListener('scroll', function () {
    const btn = document.getElementById('btn-nav-top');
    if (!btn) return;
    if (window.scrollY > 100) {
        btn.style.display = 'flex';
    } else {
        btn.style.display = 'none';
    }
}, { passive: true });

// Scroll suave al nav
document.getElementById('btn-nav-top')?.addEventListener('click', function () {
    window.scrollTo({ top: 0, behavior: 'smooth' });
});

const openBtn = document.getElementById('open-sidebar');
const closeBtn = document.getElementById('close-sidebar');
const sidebar = document.getElementById('sidebar');
const sbOverlay = document.getElementById('sidebar-overlay');

function openSidebar() {
    sidebar?.classList.add('active');
    sbOverlay?.classList.add('active');
    updateBodyScroll();
}
function closeSidebar() {
    sidebar?.classList.remove('active');
    sbOverlay?.classList.remove('active');
    updateBodyScroll();
}

openBtn?.addEventListener('click', (e) => {
    e.stopPropagation();
    openSidebar();
});
closeBtn?.addEventListener('click', closeSidebar);
sbOverlay?.addEventListener('click', closeSidebar);

// Cerrar sidebar al pulsar cualquier enlace dentro del sidebar (incluye menú e idiomas)
sidebar?.addEventListener('click', (e) => {
    const link = e.target.closest('a');
    if (link) closeSidebar();
});

// Cerrar con ESC (sidebar y contacto)
document.addEventListener('keydown', (e) => {
    if (e.key !== 'Escape') return;
    if (sidebar?.classList.contains('active')) closeSidebar();
    if (overlay?.classList.contains('active')) closeContacto();
});

(function initAOS() {
    const applyMap = () => {
        // Mapea selectores -> animación y delays
        const map = [
            // Home
            { selector: '.os-p', anim: 'up', delay: 0 },
            { selector: '.os-p2', anim: 'up', delay: 120 },
            { selector: '.ts-p', anim: 'underline', delay: 0 },
            { selector: '.ts-p2', anim: 'right', delay: 60 },
            { selector: '.ts-p3', anim: 'up', delay: 0 },
            { selector: '.ts-p4', anim: 'up', delay: 80 },
            { selector: '.ths-p', anim: 'right', delay: 0 },
            { selector: '.fs-p', anim: 'up', delay: 0 },
            { selector: '.fis-p', anim: 'up', delay: 0 },
            { selector: '.fis-p2', anim: 'right', delay: 80 },
            { selector: '.ss-p', anim: 'right', delay: 0 },
            { selector: '.ns-p', anim: 'up', delay: 0 },
            { selector: '.ns-p2', anim: 'up', delay: 60 },
            { selector: '.ns-p3', anim: 'up', delay: 120 },
            { selector: '.tes-p', anim: 'up', delay: 0 },
            { selector: '.ses-p', anim: 'up', delay: 0 },
            { selector: '.es-p', anim: 'up', delay: 0 },
            { selector: '.es-p2', anim: 'right', delay: 60 },

            // Héroes de páginas internas
            { selector: '.els-p', anim: 'up', delay: 0 },
            { selector: '.els-p2', anim: 'right', delay: 60 },
            { selector: '.els-p3', anim: 'up', delay: 120 },

            // Bloques tipo "twelve-section" (proyectos, PM, simulador, etc.)
            { selector: '.tws-p', anim: 'up', delay: 0 },
            { selector: '.tws-p2', anim: 'up', delay: 60 },
            { selector: '.tws-p3', anim: 'right', delay: 80 },
            { selector: '.tws-p4', anim: 'up', delay: 120 },
            { selector: '.tws-p5', anim: 'right', delay: 0 },
            { selector: '.tws-p6', anim: 'up', delay: 0 },

            // Simulador: títulos de pasos
            { selector: '.simulator-p', anim: 'up', delay: 0 },

            // Servicios: héroe y contenido
            { selector: '.sos-p', anim: 'right', delay: 0 },
            { selector: '.sos-p2', anim: 'up', delay: 40 },
            { selector: '.sts-p', anim: 'up', delay: 0 },
            { selector: '.sts-p2', anim: 'up', delay: 60 },
            { selector: '.sts-p3', anim: 'right', delay: 0 },

            // Reclutamiento / Ingeniería bloques de texto
            { selector: '.this-p', anim: 'right', delay: 0 },
            { selector: '.this-p2', anim: 'up', delay: 40 },
            { selector: '.this-p3', anim: 'up', delay: 80 },
            { selector: '.this-p4', anim: 'up', delay: 120 },
            { selector: '.this-p5', anim: 'up', delay: 160 },
            { selector: '.this-p6', anim: 'right', delay: 0 },
            { selector: '.this-p7', anim: 'up', delay: 0 }
        ];

        map.forEach(({ selector, anim, delay = 0, duration = 600 }) => {
            document.querySelectorAll(selector).forEach(el => {
                if (!el.dataset.anim) el.dataset.anim = anim;
                if (!el.style.transitionDuration) el.style.transitionDuration = `${duration}ms`;
                if (!el.style.transitionDelay && delay) el.style.transitionDelay = `${delay}ms`;
            });
        });
    };

    const prepareElements = () => {
        document.querySelectorAll('[data-anim]').forEach(el => {
            const anim = el.dataset.anim || 'up';
            el.classList.add(`aos-${anim}`);
        });
    };

    const io = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            const el = entry.target;
            const dur = el.dataset.duration;
            const del = el.dataset.delay;
            if (dur) el.style.transitionDuration = `${parseInt(dur, 10)}ms`;
            if (del) el.style.transitionDelay = `${parseInt(del, 10)}ms`;

            const gap = parseInt(el.dataset.stagger || '0', 10);
            if (gap > 0) {
                Array.from(el.children).forEach((child, i) => {
                    child.style.transitionDelay = entry.isIntersecting ? `${i * gap}ms` : '0ms';
                });
            }

            if (entry.isIntersecting) el.classList.add('is-visible');
            else el.classList.remove('is-visible');
        });
    }, { root: null, threshold: 0.18, rootMargin: '0px 0px -8% 0px' });

    const observeAll = () => {
        document.querySelectorAll('[data-anim], [data-stagger]').forEach(el => io.observe(el));
    };

    const init = () => { applyMap(); prepareElements(); observeAll(); };

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