(function () {
    function activateSlider(shell) {
        if (!(shell instanceof HTMLElement)) {
            return;
        }
        if (shell.dataset.h4bsSliderInit === "1") {
            return;
        }

        const slides = Array.prototype.slice.call(shell.querySelectorAll(".h4bs-slide"));
        if (!slides.length) {
            return;
        }

        const transition = String(shell.getAttribute("data-transition") || "slide")
            .trim()
            .toLowerCase();
        const motion = String(shell.getAttribute("data-motion") || "none")
            .trim()
            .toLowerCase();
        const motionForce = shell.getAttribute("data-motion-force") === "1";
        const motionDuration = Math.max(
            2000,
            Math.min(30000, parseInt(shell.getAttribute("data-motion-duration") || "9000", 10) || 9000)
        );
        const fit = String(shell.getAttribute("data-fit") || "contain")
            .trim()
            .toLowerCase();
        const snapshotFit = String(
            shell.getAttribute("data-snapshot-fit") ||
                shell.getAttribute("data-siteshot-fit") ||
                fit ||
                "contain"
        )
            .trim()
            .toLowerCase();
        const sliderBg = String(shell.getAttribute("data-bg") || "")
            .trim();
        const keyboardEnabled = shell.getAttribute("data-keyboard") !== "0";
        const swipeEnabled = shell.getAttribute("data-swipe") !== "0";
        const pauseOnHover = shell.getAttribute("data-pause-on-hover") !== "0";
        const reducedMotion =
            window.matchMedia &&
            window.matchMedia("(prefers-reduced-motion: reduce)").matches;

        shell.classList.add("is-enhanced");

        const allowedTransition = ["slide", "fade", "zoom", "flip", "stack", "none"];
        const allowedMotion = ["none", "zoom_in", "zoom_out", "pan_left", "pan_right", "pan_up", "pan_down"];
        const allowedFit = ["cover", "contain", "fill", "none"];
        const transitionMode = reducedMotion
            ? "none"
            : (allowedTransition.indexOf(transition) >= 0 ? transition : "slide");
        const motionMode = reducedMotion
            ? "none"
            : (allowedMotion.indexOf(motion) >= 0 ? motion : "none");
        const fitMode = fit === "stretch"
            ? "fill"
            : (allowedFit.indexOf(fit) >= 0 ? fit : "contain");
        const snapshotFitMode = snapshotFit === "stretch"
            ? "fill"
            : (allowedFit.indexOf(snapshotFit) >= 0 ? snapshotFit : fitMode);
        let effectiveMotion = motionMode;
        shell.classList.remove("h4bs-motion-suppressed");
        if (!motionForce && fitMode === "contain" && effectiveMotion !== "none") {
            effectiveMotion = "none";
            shell.classList.add("h4bs-motion-suppressed");
        }

        shell.classList.remove("h4bs-transition-slide", "h4bs-transition-fade", "h4bs-transition-zoom", "h4bs-transition-flip", "h4bs-transition-stack", "h4bs-transition-none");
        shell.classList.add("h4bs-transition-" + transitionMode);
        shell.classList.remove(
            "h4bs-motion-none",
            "h4bs-motion-zoom_in",
            "h4bs-motion-zoom_out",
            "h4bs-motion-pan_left",
            "h4bs-motion-pan_right",
            "h4bs-motion-pan_up",
            "h4bs-motion-pan_down"
        );
        shell.classList.add("h4bs-motion-" + effectiveMotion);
        shell.style.setProperty("--h4bs-motion-duration", String(motionDuration) + "ms");
        shell.style.setProperty("--h4bs-slider-fit", fitMode);
        shell.style.setProperty("--h4bs-snapshot-fit", snapshotFitMode);
        shell.style.setProperty("--h4bs-siteshot-fit", snapshotFitMode);
        const transitionDuration = Math.max(0, Math.min(5000, parseInt(shell.getAttribute("data-transition-duration") || "600", 10) || 600));
        const easingToken = String(shell.getAttribute("data-easing") || "ease").trim().toLowerCase();
        const easingMap = {
            linear: "linear",
            ease: "ease",
            ease_in: "cubic-bezier(.42,0,1,1)",
            ease_out: "cubic-bezier(0,0,.58,1)",
            ease_in_out: "cubic-bezier(.42,0,.58,1)",
            spring: "cubic-bezier(.2,1.35,.35,1)",
        };
        shell.style.setProperty("--h4bs-slider-transition-duration", String(transitionDuration) + "ms");
        shell.style.setProperty("--h4bs-slider-easing", easingMap[easingToken] || "ease");
        const bgToken = sliderBg.replace(/\s+/g, "");
        if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(bgToken)) {
            shell.style.setProperty("--h4bs-slider-bg", bgToken);
        }

        let activeIndex = Math.max(0, Math.min(slides.length - 1, parseInt(shell.getAttribute("data-start-index") || "0", 10) || 0));
        const autoplay = parseInt(shell.getAttribute("data-autoplay") || "0", 10);
        const loopEnabled = shell.getAttribute("data-loop") !== "0";
        const pauseOutOfView = shell.getAttribute("data-pause-out-of-view") !== "0";
        let timer = null;
        let rafId = null;
        let rafLastTs = 0;
        let transitionTimer = null;
        let pausedByUser = false;
        let pausedByViewport = false;
        let pausedByHover = false;
        let pausedByFocus = false;
        let pausedByDocument = document.hidden;
        let touchStartX = 0;
        let touchStartY = 0;
        let pointerStartX = null;
        let pointerStartY = null;
        const dots = Array.prototype.slice.call(shell.querySelectorAll(".h4bs-slide-dot"));
        const thumbnails = Array.prototype.slice.call(shell.querySelectorAll(".h4bs-slide-thumbnail"));
        const pauseButton = shell.querySelector(".h4bs-slide-pause");
        const progressBar = shell.querySelector(".h4bs-slide-progress span");
        const status = shell.querySelector(".h4bs-slide-status");
        const focusableSelector = "a[href], area[href], button, input, select, textarea, iframe, audio[controls], video[controls], [contenteditable], [tabindex]";

        function autoplayIsPaused() {
            return reducedMotion || pausedByUser || pausedByViewport || pausedByHover || pausedByFocus || pausedByDocument;
        }

        function syncPauseControl() {
            shell.classList.toggle("is-paused", pausedByUser || reducedMotion);
            if (!pauseButton) return;
            pauseButton.disabled = reducedMotion;
            pauseButton.setAttribute("aria-pressed", pausedByUser ? "true" : "false");
            pauseButton.setAttribute(
                "aria-label",
                reducedMotion
                    ? "Autoplay disabled because reduced motion is enabled"
                    : (pausedByUser ? "Play slider" : "Pause slider")
            );
        }

        function setSlideFocusable(slide, active) {
            if (!(slide instanceof HTMLElement)) return;
            if (active) {
                slide.removeAttribute("inert");
            } else {
                slide.setAttribute("inert", "");
            }
            slide.querySelectorAll(focusableSelector).forEach(function (element) {
                if (!(element instanceof HTMLElement)) return;
                if (active) {
                    if (element.dataset.h4bsSliderTabindex === "") {
                        element.removeAttribute("tabindex");
                    } else if (Object.prototype.hasOwnProperty.call(element.dataset, "h4bsSliderTabindex")) {
                        element.setAttribute("tabindex", element.dataset.h4bsSliderTabindex);
                    }
                    delete element.dataset.h4bsSliderTabindex;
                    return;
                }
                if (!Object.prototype.hasOwnProperty.call(element.dataset, "h4bsSliderTabindex")) {
                    element.dataset.h4bsSliderTabindex = element.getAttribute("tabindex") || "";
                }
                element.setAttribute("tabindex", "-1");
            });
        }

        function announceSlide(slide) {
            if (!status || !(slide instanceof HTMLElement)) return;
            status.textContent = "";
            window.requestAnimationFrame(function () {
                status.textContent = slide.getAttribute("aria-label") || "Slide changed";
            });
        }

        function currentInterval() {
            const slide = slides[activeIndex];
            const custom = slide ? parseInt(slide.getAttribute("data-slide-duration") || "0", 10) || 0 : 0;
            return custom > 0 ? custom : autoplay;
        }

        function resetProgress() {
            if (!progressBar) return;
            progressBar.style.transition = "none";
            progressBar.style.transform = "scaleX(0)";
            window.requestAnimationFrame(function () {
                if (autoplayIsPaused() || currentInterval() <= 0) return;
                progressBar.style.transition = "transform " + String(currentInterval()) + "ms linear";
                progressBar.style.transform = "scaleX(1)";
            });
        }

        function activateLayers(slide) {
            if (!(slide instanceof HTMLElement)) return;
            slide.querySelectorAll(".h4bs-slide-layer").forEach(function (layer) {
                layer.classList.remove("is-layer-active");
                if (reducedMotion) {
                    layer.classList.add("is-layer-active");
                    return;
                }
                void layer.offsetWidth;
                layer.classList.add("is-layer-active");
                const counter = layer.querySelector("[data-h4-layer-counter]") || (layer.hasAttribute("data-h4-layer-counter") ? layer : null);
                if (counter instanceof HTMLElement) {
                    const output = counter.querySelector("strong");
                    const target = Number(counter.getAttribute("data-h4-layer-counter") || "0");
                    if (output instanceof HTMLElement) {
                        output.textContent = "0";
                        const started = performance.now();
                        const duration = Math.max(300, Math.min(5000, parseInt(getComputedStyle(layer).getPropertyValue("--h4-layer-duration"), 10) || 900));
                        const animate = function (now) {
                            const ratio = Math.min(1, (now - started) / duration);
                            output.textContent = String(Math.round(target * (1 - Math.pow(1 - ratio, 3))));
                            if (ratio < 1) window.requestAnimationFrame(animate);
                        };
                        window.requestAnimationFrame(animate);
                    }
                }
            });
        }

        function syncMedia() {
            slides.forEach(function (slide, index) {
                slide.querySelectorAll("video").forEach(function (video) {
                    if (index === activeIndex && video.muted) {
                        const promise = video.play();
                        if (promise && typeof promise.catch === "function") promise.catch(function () {});
                    } else {
                        video.pause();
                    }
                });
            });
        }

        function syncBoundaryControls() {
            const prevButton = shell.querySelector(".h4bs-slide-prev");
            const nextButton = shell.querySelector(".h4bs-slide-next");
            if (prevButton) prevButton.disabled = !loopEnabled && activeIndex <= 0;
            if (nextButton) nextButton.disabled = !loopEnabled && activeIndex >= slides.length - 1;
        }

        function setActive(index, direction, userInitiated) {
            const previousIndex = activeIndex;
            const previousSlide =
                previousIndex >= 0 && previousIndex < slides.length
                    ? slides[previousIndex]
                    : null;
            slides.forEach(function (slide, i) {
                slide.classList.toggle("is-active", i === index);
                slide.setAttribute("aria-hidden", i === index ? "false" : "true");
                setSlideFocusable(slide, i === index);
                if (i !== index) {
                    slide.classList.remove("is-enter-from-right", "is-enter-from-left");
                }
            });
            dots.forEach(function (dot, i) {
                dot.classList.toggle("is-active", i === index);
                dot.setAttribute("aria-current", i === index ? "true" : "false");
            });
            thumbnails.forEach(function (thumbnail, i) {
                thumbnail.classList.toggle("is-active", i === index);
                thumbnail.setAttribute("aria-current", i === index ? "true" : "false");
            });
            const nextSlide = slides[index];
            if (nextSlide && transitionMode === "slide") {
                nextSlide.classList.add(direction < 0 ? "is-enter-from-left" : "is-enter-from-right");
                window.requestAnimationFrame(function () {
                    nextSlide.classList.remove("is-enter-from-right", "is-enter-from-left");
                });
            }
            if (transitionMode !== "none" && previousSlide && previousSlide !== nextSlide) {
                previousSlide.classList.add("is-leaving");
                if (transitionTimer) {
                    window.clearTimeout(transitionTimer);
                }
                transitionTimer = window.setTimeout(function () {
                    previousSlide.classList.remove("is-leaving");
                    transitionTimer = null;
                }, transitionDuration + 40);
            }
            activeIndex = index;
            activateLayers(nextSlide);
            syncMedia();
            syncBoundaryControls();
            resetProgress();
            if (userInitiated) {
                announceSlide(nextSlide);
                if (previousSlide && previousSlide.contains(document.activeElement)) {
                    shell.focus({ preventScroll: true });
                }
            }
        }

        function goTo(index, userInitiated) {
            if (index === activeIndex || index < 0 || index >= slides.length) {
                return;
            }
            setActive(index, index > activeIndex ? 1 : -1, Boolean(userInitiated));
        }

        function next(userInitiated) {
            if (!loopEnabled && activeIndex >= slides.length - 1) {
                stopAutoplay();
                return;
            }
            setActive((activeIndex + 1) % slides.length, 1, Boolean(userInitiated));
        }

        function prev(userInitiated) {
            if (!loopEnabled && activeIndex <= 0) {
                return;
            }
            setActive((activeIndex - 1 + slides.length) % slides.length, -1, Boolean(userInitiated));
        }

        function healActiveState() {
            if (!slides || slides.length < 1) {
                return;
            }
            let activeCount = 0;
            let activeFromClass = -1;
            slides.forEach(function (slide, i) {
                if (slide.classList.contains("is-active")) {
                    activeCount += 1;
                    if (activeFromClass < 0) {
                        activeFromClass = i;
                    }
                }
            });

            if (activeCount === 1 && activeFromClass >= 0) {
                if (activeIndex !== activeFromClass) {
                    activeIndex = activeFromClass;
                }
                return;
            }

            let fallbackIndex = activeFromClass;
            if (fallbackIndex < 0) {
                slides.forEach(function (slide, i) {
                    if (fallbackIndex >= 0) {
                        return;
                    }
                    if (slide.getAttribute("aria-hidden") === "false") {
                        fallbackIndex = i;
                    }
                });
            }
            if (fallbackIndex < 0 || fallbackIndex >= slides.length) {
                fallbackIndex =
                    activeIndex >= 0 && activeIndex < slides.length ? activeIndex : 0;
            }
            setActive(fallbackIndex, 1, false);
        }

        function startAutoplay() {
            if (autoplayIsPaused() || currentInterval() <= 0 || slides.length <= 1) {
                return;
            }
            stopAutoplay();
            const useRaf = typeof window.requestAnimationFrame === "function";
            if (useRaf) {
                const tick = function (timestamp) {
                    if (autoplayIsPaused() || currentInterval() <= 0 || slides.length <= 1) {
                        rafId = null;
                        return;
                    }
                    if (!rafLastTs) {
                        rafLastTs = timestamp;
                    } else if (timestamp - rafLastTs >= currentInterval()) {
                        next();
                        rafLastTs = timestamp;
                    }
                    rafId = window.requestAnimationFrame(tick);
                };
                rafLastTs = 0;
                rafId = window.requestAnimationFrame(tick);
                return;
            }
            timer = window.setInterval(next, currentInterval());
            resetProgress();
        }

        function stopAutoplay() {
            if (timer) {
                window.clearInterval(timer);
                timer = null;
            }
            if (rafId && typeof window.cancelAnimationFrame === "function") {
                window.cancelAnimationFrame(rafId);
            }
            rafId = null;
            rafLastTs = 0;
            if (progressBar) {
                progressBar.style.transition = "none";
            }
        }

        function setPaused(paused) {
            pausedByUser = paused;
            syncPauseControl();
            if (paused) {
                stopAutoplay();
            } else {
                startAutoplay();
            }
        }

        const prevButton = shell.querySelector(".h4bs-slide-prev");
        const nextButton = shell.querySelector(".h4bs-slide-next");
        if (prevButton) {
            prevButton.addEventListener("click", function (event) {
                event.preventDefault();
                event.stopPropagation();
                setPaused(true);
                prev(true);
            });
        }
        if (nextButton) {
            nextButton.addEventListener("click", function (event) {
                event.preventDefault();
                event.stopPropagation();
                setPaused(true);
                next(true);
            });
        }
        dots.forEach(function (dot) {
            dot.addEventListener("click", function (event) {
                event.preventDefault();
                const index = parseInt(dot.getAttribute("data-slide-index") || "0", 10) || 0;
                setPaused(true);
                goTo(index, true);
            });
        });
        thumbnails.forEach(function (thumbnail) {
            thumbnail.addEventListener("click", function (event) {
                event.preventDefault();
                const index = parseInt(thumbnail.getAttribute("data-slide-index") || "0", 10) || 0;
                setPaused(true);
                goTo(index, true);
            });
        });
        if (pauseButton) {
            pauseButton.addEventListener("click", function (event) {
                event.preventDefault();
                if (pausedByUser) {
                    /* An explicit Play command wins until a new hover/focus event occurs. */
                    pausedByHover = false;
                    pausedByFocus = false;
                    setPaused(false);
                } else {
                    setPaused(true);
                }
            });
        }
        shell.addEventListener("pointerdown", function (event) {
            if (pauseButton && event.target instanceof Element && event.target.closest(".h4bs-slide-pause")) {
                return;
            }
            if (autoplay > 0) {
                setPaused(true);
            }
        });
        if (keyboardEnabled) {
            shell.setAttribute("tabindex", shell.getAttribute("tabindex") || "0");
            shell.addEventListener("keydown", function (event) {
                const target = event.target;
                const isFormControl = target && target !== shell && /^(INPUT|SELECT|TEXTAREA|BUTTON|A)$/.test(target.tagName || "");
                if (isFormControl) return;
                if (event.key === "ArrowLeft") {
                    event.preventDefault();
                    setPaused(true);
                    prev(true);
                } else if (event.key === "ArrowRight") {
                    event.preventDefault();
                    setPaused(true);
                    next(true);
                } else if (event.key === " " || event.key === "Spacebar") {
                    event.preventDefault();
                    setPaused(!pausedByUser);
                }
            });
        }
        if (swipeEnabled) {
            shell.addEventListener(
                "touchstart",
                function (event) {
                    const touch = event.touches && event.touches[0];
                    if (!touch) {
                        return;
                    }
                    touchStartX = touch.clientX;
                    touchStartY = touch.clientY;
                },
                { passive: true }
            );
            shell.addEventListener(
                "touchend",
                function (event) {
                    const touch = event.changedTouches && event.changedTouches[0];
                    if (!touch) {
                        return;
                    }
                    const dx = touch.clientX - touchStartX;
                    const dy = touch.clientY - touchStartY;
                    if (Math.abs(dx) < 42 || Math.abs(dx) < Math.abs(dy) * 1.4) {
                        return;
                    }
                    if (dx > 0) {
                        setPaused(true);
                        prev(true);
                    } else {
                        setPaused(true);
                        next(true);
                    }
                },
                { passive: true }
            );
            shell.addEventListener("pointerdown", function (event) {
                if (event.pointerType === "mouse" && event.button !== 0) return;
                pointerStartX = event.clientX;
                pointerStartY = event.clientY;
            });
            shell.addEventListener("pointerup", function (event) {
                if (pointerStartX === null || pointerStartY === null) return;
                const dx = event.clientX - pointerStartX;
                const dy = event.clientY - pointerStartY;
                pointerStartX = null;
                pointerStartY = null;
                if (Math.abs(dx) < 42 || Math.abs(dx) < Math.abs(dy) * 1.4) return;
                setPaused(true);
                if (dx > 0) prev(true); else next(true);
            });
        }

        if (!reducedMotion) {
            shell.addEventListener("pointermove", function (event) {
                const bounds = shell.getBoundingClientRect();
                if (!bounds.width || !bounds.height) return;
                const px = ((event.clientX - bounds.left) / bounds.width - 0.5) * 2;
                const py = ((event.clientY - bounds.top) / bounds.height - 0.5) * 2;
                shell.style.setProperty("--h4-slider-pointer-x", px.toFixed(4));
                shell.style.setProperty("--h4-slider-pointer-y", py.toFixed(4));
            });
            shell.addEventListener("pointerleave", function () {
                shell.style.setProperty("--h4-slider-pointer-x", "0");
                shell.style.setProperty("--h4-slider-pointer-y", "0");
            });
        }

        if (!reducedMotion && autoplay > 0 && slides.length > 1) {
            startAutoplay();
            shell.addEventListener("mouseenter", function () {
                if (pauseOnHover) {
                    pausedByHover = true;
                    stopAutoplay();
                }
            });
            shell.addEventListener("mouseleave", function () {
                pausedByHover = false;
                if (pauseOnHover) {
                    startAutoplay();
                }
            });

            shell.addEventListener("focusin", function () {
                pausedByFocus = true;
                stopAutoplay();
            });
            shell.addEventListener("focusout", function (event) {
                if (event.relatedTarget && shell.contains(event.relatedTarget)) return;
                pausedByFocus = false;
                startAutoplay();
            });

            document.addEventListener("visibilitychange", function () {
                pausedByDocument = document.hidden;
                if (pausedByDocument) {
                    stopAutoplay();
                    return;
                }
                startAutoplay();
            });
        }

        if (pauseOutOfView && "IntersectionObserver" in window) {
            const viewportObserver = new IntersectionObserver(function (entries) {
                pausedByViewport = !entries[0].isIntersecting;
                if (pausedByViewport) {
                    stopAutoplay();
                } else {
                    startAutoplay();
                }
            }, { threshold: 0.08 });
            viewportObserver.observe(shell);
        }

        syncPauseControl();
        setActive(activeIndex, 1, false);
        healActiveState();
        window.setInterval(healActiveState, 5000);
        shell.dataset.h4bsSliderInit = "1";
    }

    function initSliders(root) {
        const scope =
            root && root.querySelectorAll
                ? root
                : document;
        scope.querySelectorAll(".h4bs-slider").forEach(activateSlider);
    }

    window.h4bsInitSliders = initSliders;

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", function () {
            initSliders(document);
        });
    } else {
        initSliders(document);
    }
})();
