document.addEventListener('DOMContentLoaded', function () {
    const sliderEl = document.querySelector('.etn-egr-slider');

    if (sliderEl && typeof Swiper !== 'undefined') {
        const autoplayEnabled = parseInt(etnEgrSettings.autoplay, 10) === 1;
        const arrowsEnabled   = parseInt(etnEgrSettings.arrows, 10) === 1;
        const dotsEnabled     = parseInt(etnEgrSettings.dots, 10) === 1;
        const speed           = parseInt(etnEgrSettings.speed, 10) || 3000;
        const columns         = parseInt(etnEgrSettings.columns, 10) || 3;
        const cardGap         = parseInt(etnEgrSettings.card_gap, 10);
        const spaceBetween    = (cardGap >= 0 && cardGap <= 40) ? cardGap : 12;

        new Swiper('.etn-egr-slider', {
            slidesPerView: 1, // Móvil
            spaceBetween: spaceBetween,
            loop: true,
            autoplay: autoplayEnabled ? {
                delay: speed,
                disableOnInteraction: false,
            } : false,
            navigation: arrowsEnabled ? {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            } : false,
            pagination: dotsEnabled ? {
                el: '.swiper-pagination',
                clickable: true,
            } : false,
            // BREAKPOINTS PARA TABLET / PC
            breakpoints: {
                768: { slidesPerView: 2 },
                1024: { slidesPerView: columns } // vinculado al breakpoint de 1024px
            }
        });
    }

    // Modal "Leer más" - para carrusel y sidebar
    const readMoreBtns = document.querySelectorAll('.etn-egr-read-more[data-full-text-b64]');
    const modal        = document.getElementById('etn-egr-modal');
    const modalContent = document.getElementById('etn-egr-modal-body');
    const closeBtn     = document.querySelector('.etn-egr-modal-close');

    if (modal && modalContent && readMoreBtns.length) {
        const decodeB64Utf8 = (b64) => {
            try {
                const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
                return new TextDecoder('utf-8').decode(bytes);
            } catch (e) {
                return '';
            }
        };

        readMoreBtns.forEach(function (btn) {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                const b64 = this.getAttribute('data-full-text-b64') || '';
                const fullText = decodeB64Utf8(b64);
                // Mostrar como texto plano preservando saltos de línea
                modalContent.textContent = fullText;
                modal.style.display = 'flex';
                document.body.style.overflow = 'hidden';
            });
        });
    }

    if (closeBtn && modal) {
        closeBtn.addEventListener('click', function () {
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
        });

        window.addEventListener('click', function (event) {
            if (event.target === modal) {
                modal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });
    }

    // Panel lateral (Sidebar) - mostrar/ocultar al hacer clic en el badge
    const badgeClickable = document.querySelector('.etn-egr-badge-clickable');
    const sidebarPanel = document.querySelector('.etn-egr-sidebar-panel');
    const sidebarOverlay = document.querySelector('.etn-egr-sidebar-overlay');
    const sidebarClose = document.querySelector('.etn-egr-sidebar-close');

    if (badgeClickable && sidebarPanel && sidebarOverlay) {
        // Abrir panel al hacer clic en el badge (no abrir si se hace clic en el enlace "Escribir reseña")
        badgeClickable.addEventListener('click', function (e) {
            if (e.target.closest('.etn-egr-badge-write-review')) {
                return;
            }
            e.preventDefault();
            sidebarOverlay.style.display = 'block';
            var layout = sidebarPanel.getAttribute('data-panel-layout') || 'block';
            sidebarPanel.style.display = layout === 'flex' ? 'flex' : 'block';
            sidebarPanel.offsetHeight;
            sidebarPanel.style.transform = 'translateX(0)';
            document.body.style.overflow = 'hidden';
            if (sidebarClose) {
                sidebarClose.focus();
            }
        });

        // Cerrar panel al hacer clic en el overlay
        sidebarOverlay.addEventListener('click', function () {
            closeSidebar();
        });

        // Cerrar panel al hacer clic en el botón cerrar
        if (sidebarClose) {
            sidebarClose.addEventListener('click', function (e) {
                e.stopPropagation();
                closeSidebar();
            });
        }

        function closeSidebar() {
            sidebarPanel.style.transform = 'translateX(-100%)';
            setTimeout(function () {
                sidebarPanel.style.display = 'none';
                sidebarOverlay.style.display = 'none';
                document.body.style.overflow = 'auto';
                if (badgeClickable) {
                    badgeClickable.focus();
                }
            }, 300);
        }

        // Mantener foco dentro del panel (accesibilidad)
        sidebarPanel.addEventListener('keydown', function (e) {
            if (e.key !== 'Tab' || sidebarPanel.style.display === 'none') {
                return;
            }
            var focusables = sidebarPanel.querySelectorAll('a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])');
            if (focusables.length === 0) {
                return;
            }
            var first = focusables[0];
            var last = focusables[focusables.length - 1];
            if (e.shiftKey) {
                if (document.activeElement === first) {
                    e.preventDefault();
                    last.focus();
                }
            } else {
                if (document.activeElement === last) {
                    e.preventDefault();
                    first.focus();
                }
            }
        });

        // Cerrar con tecla ESC
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && sidebarPanel.style.display !== 'none') {
                closeSidebar();
            }
        });

        // Swipe hacia la izquierda para cerrar el panel (móvil)
        var touchStartX = 0;
        sidebarPanel.addEventListener('touchstart', function (e) {
            touchStartX = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
        }, { passive: true });
        sidebarPanel.addEventListener('touchend', function (e) {
            var touchEndX = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
            if (touchStartX - touchEndX > 60) {
                closeSidebar();
            }
        }, { passive: true });
    }
});