document.addEventListener('DOMContentLoaded', function() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
            } else {
                entry.target.classList.remove('visible');
            }
        });
    }, {
        threshold: 0.2 
    });

    document.querySelectorAll('.fade-in-up, .fade-in-left, .fade-in-right').forEach(el => {
        observer.observe(el);
    });

    document.querySelectorAll('a[href^="#"], a[href^="?page=home#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            let href = this.getAttribute('href');
            let hash = '';
            if (href.startsWith('?page=home#')) {
                hash = href.split('#')[1];
                if (window.location.search.indexOf('page=home') === -1 && window.location.pathname !== '/' && window.location.pathname !== '/index.php') {
                    localStorage.setItem('scrollToHash', hash);
                    return;
                }
            } else if (href.startsWith('#')) {
                hash = href.substring(1);
            }
            if (hash) {
                const target = document.getElementById(hash);
                if (target) {
                    e.preventDefault();
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                    const offcanvas = document.querySelector('.offcanvas.show');
                    if (offcanvas) {
                        const bsOffcanvas = bootstrap.Offcanvas.getInstance(offcanvas);
                        if (bsOffcanvas) bsOffcanvas.hide();
                    }
                }
            }
        });
    });

    const hashToScroll = localStorage.getItem('scrollToHash');
    if (hashToScroll) {
        const target = document.getElementById(hashToScroll);
        if (target) {
            setTimeout(() => {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }, 300);
        }
        localStorage.removeItem('scrollToHash');
    }
});

document.addEventListener('hidden.bs.offcanvas', function (event) {

    if (window.location.pathname === '/' || window.location.pathname.endsWith('index.php')) {
        if (window.location.hash) {
            history.replaceState(null, null, window.location.pathname + window.location.search);
        }
    }
});


document.getElementById('customMenuBtn').addEventListener('click', function() {
    document.getElementById('customOffcanvas').classList.add('open');
    document.getElementById('customOffcanvasBackdrop').classList.add('open');
    document.body.style.overflow = 'hidden';
});
document.getElementById('customCloseBtn').addEventListener('click', closeCustomOffcanvas);
document.getElementById('customOffcanvasBackdrop').addEventListener('click', closeCustomOffcanvas);
function closeCustomOffcanvas() {
    document.getElementById('customOffcanvas').classList.remove('open');
    document.getElementById('customOffcanvasBackdrop').classList.remove('open');
    document.body.style.overflow = '';
}
document.querySelectorAll('#customOffcanvas .nav-link').forEach(link => {
    link.addEventListener('click', closeCustomOffcanvas);
});

 $('#enviar').on('click', function(e) {
        e.preventDefault();
        const emailInput = $('#form [name="email"]');
        const email = emailInput.val().trim();
        const alerta = $('#alerta-suscripcion');


        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        const accentRegex = /[áéíóúÁÉÍÓÚñÑüÜ]/;


        if (!email) {
            alerta.html(`
                <div class="alert alert-warning alert-dismissible fade show mt-3" role="alert"
                     style="border-left: 5px solid #ffc107; box-shadow: 0 4px 12px rgba(255, 193, 7, 0.2); font-size: 1rem;">
                    <strong>⚠️ Atención:</strong> Por favor ingresa tu correo electrónico.
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            `);
            return;
        }

        if (!emailRegex.test(email)) {
            alerta.html(`
                <div class="alert alert-warning alert-dismissible fade show mt-3" role="alert"
                     style="border-left: 5px solid #ffc107; box-shadow: 0 4px 12px rgba(255, 193, 7, 0.2); font-size: 1rem;">
                    <strong>📧 Correo no válido:</strong> Asegúrate de ingresar un correo electrónico correcto.
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            `);
            return;
        }

        if (accentRegex.test(email)) {
            alerta.html(`
                <div class="alert alert-warning alert-dismissible fade show mt-3" role="alert"
                     style="border-left: 5px solid #ffc107; box-shadow: 0 4px 12px rgba(255, 193, 7, 0.2); font-size: 1rem;">
                    <strong>❌ Sin acentos:</strong> El correo no debe contener acentos ni caracteres especiales como "ñ".
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            `);
            return;
        }

        $.post('./sistema/routes/web.php', {
                REQUEST_URI: '/mail/send',
                email
            })
            .done(function(response) {
                emailInput.val('');
                alerta.html(`
                    <div class="alert alert-success alert-dismissible fade show mt-3" role="alert"
                         style="border-left: 5px solid #198754; box-shadow: 0 4px 12px rgba(25, 135, 84, 0.2); font-size: 1rem;">
                        <strong>✅ ¡Gracias!</strong> Te has suscrito correctamente.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                    </div>
                `);
            })
            .fail(function() {
                alerta.html(`
                    <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert"
                         style="border-left: 5px solid #dc3545; box-shadow: 0 4px 12px rgba(220, 53, 69, 0.2); font-size: 1rem;">
                        <strong>⚠️ Error:</strong> No se pudo completar la suscripción. Intenta más tarde.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                    </div>
                `);
            });
    });