document.addEventListener('DOMContentLoaded', function () {
    // Swiper Init
    var swiperElement = document.querySelector(".iwp__gallery-slider");
    if (swiperElement) {
        var swiperMain = new Swiper(".iwp__gallery-slider", {
            spaceBetween: 10,
            loop: true,
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
            on: {
                slideChange: function () {
                    var index = this.realIndex + 1;
                    var total = this.slides.length - this.loopedSlides * 2;

                    if (!this.loopedSlides) {
                        total = this.slides.length;
                    } else {
                        total = document.querySelectorAll('.iwp__gallery-slider .swiper-slide:not(.swiper-slide-duplicate)').length;
                    }

                    var counters = document.querySelectorAll('.iwp__slide-counter');
                    counters.forEach(function (c) {
                        c.innerText = index + ' / ' + total;
                    });
                }
            }
        });
    }

    // PhotoSwipe Init
    if (typeof immowp_single_params !== 'undefined' && immowp_single_params.photoswipe_lightbox_url) {
        var galleryLinks = document.querySelectorAll('a.iwp__gallery-lightbox-link');
        if (galleryLinks.length > 0) {
            var galleryId = swiperElement ? swiperElement.id : 'pswp-gallery';

            import(immowp_single_params.photoswipe_lightbox_url).then(function (module) {
                const PhotoSwipeLightbox = module.default;
                const lightbox = new PhotoSwipeLightbox({
                    gallery: '#' + galleryId,
                    children: 'a.iwp__gallery-lightbox-link',
                    pswpModule: () => import(immowp_single_params.photoswipe_module_url),
                });
                lightbox.init();
            }).catch(function (err) {
                console.error('Failed to load PhotoSwipe:', err);
            });
        }
    }
});
