$(function () {
    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');
    }

    const paginacion = {
        events: {
            itemsPerPage: 1,
            start: 0,
            end: 1,
            length: 0
        },
        videos: {
            itemsPerPage: 2,
            start: 0,
            end: 2,
            length: 0
        },
        galleries: {
            itemsPerPage: 3,
            start: 0,
            end: 3,
            length: 0
        }
    };

    function fetchData(url, data, success, error) {
        $.ajax({
            url,
            type: 'POST',
            data,
            success,
            error
        });
    }

    function renderVideos(start, end) {
        fetchData('./sistema/routes/web.php', {
            REQUEST_URI: '/videos/list/active'
        }, (response) => {
            const videos = response.videos;
            paginacion.videos.length = videos.length;
            const $divVideos = $('#videosVal').empty();
            if (!videos.length) {
                $divVideos.append(`
                    <div class="col-12 col-md-6 offset-md-3 text-center py-5">
                        <i class="fa-regular fa-clock fa-2x mb-2 text-info"></i>
                        <div class="text-muted">Próximamente videos disponibles</div>
                    </div>
                `);
                return;
            }
            videos.slice(start, end).forEach(v => {
                $divVideos.append(`
                    <div class="col">
                        <div class="ratio ratio-16x9">
                            <iframe src="${getYoutubeEmbedUrl(v.link)}" title="YouTube video player" frameborder="0"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                referrerpolicy="strict-origin-when-cross-origin" allowfullscreen loading="lazy"></iframe>
                        </div>
                    </div>
                `);
            });
        });
    }

    function renderEvents(start, end) {
        fetchData('./sistema/routes/web.php', {
            REQUEST_URI: '/events/list/active'
        }, (response) => {
            const events = response.events;
            paginacion.events.length = events.length;
            const $eventDate = $('#event_date');
            const $eventName = $('#event_name');
            const $eventPlace = $('#event_place');
            const $eventImage = $('.bg-image');
            const $containerEvents = $('.container-events');

            if (!events.length) {
                $containerEvents.html(`
                    <div class="w-100 text-center py-5 m-0">
                        <i class="fa-regular fa-calendar-xmark fa-2x mb-2 text-info"></i>
                        <div class="text-muted">Próximamente eventos disponibles</div>
                    </div>
                `);
                $eventDate.text('');
                $eventName.text('');
                $eventImage.css('background-image', '');
                $eventPlace.text('');
                return;
            }

            events.slice(start, end).forEach(e => {
                $eventDate.text(formatearFecha(e.date));
                $eventName.text(truncateText(e.name, 28));
                $eventImage.css('background-image', `url('./sistema/resources/images/events/${e.banner}')`);
                $eventPlace.text(truncateText(e.place, 18));
            });
        });
    }

    function renderGalleries(start, end) {
        fetchData('./sistema/routes/web.php', {
            REQUEST_URI: '/galleries/recent'
        }, (response) => {
            const recentEvents = response.galleries_recent;
            paginacion.galleries.length = recentEvents.length;
            const $divRecentEvents = $('#recent_events').empty();

            if (!recentEvents.length) {
                $divRecentEvents.html(`
                    <div class="d-flex justify-content-center align-items-center py-5 w-100">
                        <div class="text-center" style="min-width:250px;max-width:350px;">
                            <i class="fa-regular fa-images fa-2x mb-2 text-info"></i>
                            <div class="text-muted">Próximamente eventos en galería</div>
                        </div>
                    </div>
                `);
                return;
            }

            // Renderiza los eventos en la vista previa
            recentEvents.slice(start, end).forEach(er => {
                $divRecentEvents.append(`
                    <div class="col">
                        <div class="container-img p-4 d-flex justify-content-start align-items-end"
                            style="background-image: url('./sistema/resources/images/galleries/${er.img}'); cursor:pointer;"
                            id="er${er.id}" data-id="${er.id}">
                            <div class="d-flex flex-column justify-content-center align-items-start">
                                <span class="fw-bold fs-5">${truncateText(er.name, 18)}</span>
                                <span class="fw-bold fs-5">${er.date}</span>
                                <span class="fw-bold fs-5">${truncateText(er.place, 18)}</span>
                            </div>
                        </div>
                    </div>
                `);
            });

            // Configura el comportamiento al hacer clic en un evento
            recentEvents.slice(start, end).forEach(er => {
                $(`#er${er.id}`).off('click').on('click', function () {
                    const eventId = this.dataset.id;

                    // Abre el modal/carrusel
                    $('.gallery-images').addClass('active');

                    // Limpia vistas previas y detalles
                    $('#gallery_detail').empty();
                    $('#gallery_carousel_inner').empty();

                    fetchData('./sistema/routes/web.php', {
                        REQUEST_URI: '/galleries/find-by-id/post',
                        id: eventId
                    }, (response) => {
                        const gallery = response.gallery;
                        const images = gallery.images;

                        // Agrega los detalles del evento
                        $('#gallery_detail').html(`
                            <div class="fw-bold text-white fs-3">${gallery.name}</div>
                            <div class="fw-bold text-white fs-3">${gallery.date}</div>
                            <div class="fw-bold text-white fs-3">${gallery.place}</div>
                        `);

                        // Renderiza el carrusel
                        images.forEach((img, idx) => {
                            $('#gallery_carousel_inner').append(`
                                <div class="carousel-item${idx === 0 ? ' active' : ''}">
                                    <img src="./sistema/resources/images/galleries/${img.name}"
                                         class="d-block w-100"
                                         alt="Evento"
                                         style="object-fit:cover; border-radius:25px; max-height:500px; margin:auto;"
                                         loading="lazy">
                                </div>
                            `);
                        });

                        // Mostrar u ocultar botones si hay solo una imagen
                        if (images.length <= 1) {
                            $('#carousel-prev, #carousel-next').hide();
                        } else {
                            $('#carousel-prev, #carousel-next').show();
                        }
                    });
                });
            });
        });
    }


    function formatearFecha(fechaStr) {
        const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
        if (/^\d{4}-\d{2}-\d{2}$/.test(fechaStr)) {
            const [anio, mes, dia] = fechaStr.split('-');
            return `${parseInt(dia)} ${meses[parseInt(mes) - 1]}`;
        }
        const fecha = new Date(fechaStr);

        return `${fecha.getDate()} ${meses[fecha.getMonth()]}`;
    }

    function getYoutubeEmbedUrl(link) {
        const matchShort = link.match(/youtu\.be\/([a-zA-Z0-9_-]+)/);
        if (matchShort) return `https://www.youtube.com/embed/${matchShort[1]}`;
        const matchLong = link.match(/v=([a-zA-Z0-9_-]+)/);
        if (matchLong) return `https://www.youtube.com/embed/${matchLong[1]}`;
        if (link.includes('youtube.com/embed/')) return link;
        return link;
    }

    function truncateText(text, maxLength) {
        return text.length > maxLength ? text.slice(0, maxLength - 3) + '...' : text;
    }

    renderGalleries(paginacion.galleries.start, paginacion.galleries.end);
    renderEvents(paginacion.events.start, paginacion.events.end);
    renderVideos(paginacion.videos.start, paginacion.videos.end);

    fetchData('./sistema/routes/web.php', {
        REQUEST_URI: '/blogs/list/active'
    }, (response) => {
        const blogs = response.blogs;
        const $divBlogs = $('#blogs').empty();
        const $divAlert = $('#alert');
        const $divRecentBlog = $('#recent_blog').empty();

        if (!blogs.length) {
            if ($divAlert.length) {
                $divAlert.html(`
                    <div class="col-12 text-center py-5">
                        <i class="fa-regular fa-newspaper fa-2x mb-2 text-info"></i>
                        <div class="text-muted">Próximamente artículos disponibles</div>
                    </div>
                `);
            }
            return;
        }

        blogs.slice(0, 5).forEach((b, i) => {
            if (i === 0 && $divRecentBlog.length) {
                $divRecentBlog.html(`
                    <img src="./sistema/resources/images/blogs/${b.img}" class="rounded-4 w-100 mb-3" style="aspect-ratio: 4/3; object-fit: cover;" alt="Inteligencia Espiritual" loading="lazy">
                    <div class="d-flex justify-content-between align-items-center blog-recent-responsive">
                        <span class="fw-bold title blog-title-ellipsis my-2 subtitle-size">${b.title}</span>
                        <a href="?page=detailBlog&id=${b.id}" class="btn btn-light rounded-pill px-4 mt-2">Ver más</a>
                    </div>
                `);
            } else {
                $divBlogs.append(`
                    <div class="col-12 col-lg-6">
                        <div>
                            <img src="./sistema/resources/images/blogs/${b.img}" class="rounded-4 w-100 mb-2" style="aspect-ratio: 16/9; object-fit: cover;" alt="Inteligencia Corporal" loading="lazy">
                            <div class="d-flex flex-column justify-content-between">
                               <span class="fw-bold title blog-title-ellipsis my-2 subtitle-size">${b.title}</span>
                                <a href="?page=detailBlog&id=${b.id}" class="btn btn-light rounded-pill px-4 mb-2">Ver más</a>
                            </div>
                        </div>
                    </div>
                `);
            }
        });
    });

    $('#prev').on('click', function () {
        if (paginacion.galleries.start > 0) {
            paginacion.galleries.start -= paginacion.galleries.itemsPerPage;
            paginacion.galleries.end -= paginacion.galleries.itemsPerPage;
            renderGalleries(paginacion.galleries.start, paginacion.galleries.end);
        }
    });
    $('#next').on('click', function () {
        if (paginacion.galleries.end < paginacion.galleries.length) {
            paginacion.galleries.start += paginacion.galleries.itemsPerPage;
            paginacion.galleries.end += paginacion.galleries.itemsPerPage;
            renderGalleries(paginacion.galleries.start, paginacion.galleries.end);
        }
    });

    $('#prev_videos').on('click', function () {
        if (paginacion.videos.start > 0) {
            paginacion.videos.start -= paginacion.videos.itemsPerPage;
            paginacion.videos.end -= paginacion.videos.itemsPerPage;
            renderVideos(paginacion.videos.start, paginacion.videos.end);
        }
    });
    $('#next_videos').on('click', function () {
        if (paginacion.videos.end < paginacion.videos.length) {
            paginacion.videos.start += paginacion.videos.itemsPerPage;
            paginacion.videos.end += paginacion.videos.itemsPerPage;
            renderVideos(paginacion.videos.start, paginacion.videos.end);
        }
    });

    $('#prev_events').on('click', function () {
        if (paginacion.events.start > 0) {
            paginacion.events.start -= paginacion.events.itemsPerPage;
            paginacion.events.end -= paginacion.events.itemsPerPage;
            renderEvents(paginacion.events.start, paginacion.events.end);
        }
    });
    $('#next_events').on('click', function () {
        if (paginacion.events.end < paginacion.events.length) {
            paginacion.events.start += paginacion.events.itemsPerPage;
            paginacion.events.end += paginacion.events.itemsPerPage;
            renderEvents(paginacion.events.start, paginacion.events.end);
        }
    });

    $(document).on('mousedown', function (e) {
        const $galleryImages = $('.gallery-images');
        const $carousel = $('#galleryCarousel');
        const $prev = $('#carousel-prev');
        const $next = $('#carousel-next');

        if ($galleryImages.hasClass('active')) {
            const isClickInsideGallery =
                $carousel.is(e.target) ||
                $carousel.has(e.target).length > 0 ||
                $prev.is(e.target) ||
                $prev.has(e.target).length > 0 ||
                $next.is(e.target) ||
                $next.has(e.target).length > 0;

            if (!isClickInsideGallery) {
                $galleryImages.removeClass('active');
            }
        }
    });

    $('#enviar').on('click', function (e) {
        e.preventDefault();
        const nameInput = $('#form [name="name"]');
        const phoneInput = $('#form [name="phone"]');
        const emailInput = $('#form [name="email"]');

        const name = nameInput.val().trim();
        const phone = phoneInput.val().trim();
        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 = /[áéíóúÁÉÍÓÚñÑüÜ]/;
        const phoneRegex = /^[\d\s\-\+\(\)]{7,15}$/;

        // Validar nombre
        if (!name) {
            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 nombre.
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Cerrar"></button>
                </div>
            `);
            return;
        }

        // Validar correo
        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;
        }

        // Validar teléfono (solo si se proporciona)
        if (phone && !phoneRegex.test(phone)) {
            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>📱 Teléfono no válido:</strong> Ingresa un número de teléfono válido (7-15 dígitos).
                    <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',
            name,
            phone,
            email
        })
            .done(function (response) {
                nameInput.val('');
                phoneInput.val('');
                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>
                `);
            });
    });

    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.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);
});