(function(){
    var ImpulseCarouselEffects = (function() {

        
        function drawCover(ctx, img, w, h) {
            if (!img || !img.complete || !img.naturalWidth) {
                ctx.fillStyle = '#e0e0e0'; ctx.fillRect(0, 0, w, h); return;
            }
            var iw = img.naturalWidth, ih = img.naturalHeight;
            var scale = Math.max(w / iw, h / ih);
            var dw = iw * scale, dh = ih * scale;
            ctx.drawImage(img, (w - dw) / 2, (h - dh) / 2, dw, dh);
        }

        
        function depth_rush(container, outEl, inEl, dur, done) {

            
            outEl.style.transition = 'none';
            outEl.style.transform  = 'scale(1)';
            outEl.style.opacity    = '1';
            outEl.style.zIndex     = '1';
            inEl.style.transition  = 'none';
            inEl.style.transform   = 'scale(0)';
            inEl.style.opacity     = '0';
            inEl.style.zIndex      = '2';
            inEl.offsetHeight;

            var ease = dur + 'ms ease-in-out';
            outEl.style.transition = 'transform ' + ease + ', opacity ' + ease;
            outEl.style.transform  = 'scale(1.3)';
            outEl.style.opacity    = '0';

            inEl.style.transition  = 'transform ' + ease + ', opacity ' + ease;
            inEl.style.transform   = 'scale(1)';
            inEl.style.opacity     = '1';

            setTimeout(done, dur + 50);
        }


        

        function card_flip(container, outEl, inEl, dur, done) {
            var half = dur / 2;
            
            outEl.style.transition = 'none'; outEl.style.transform = 'rotateX(0deg)'; outEl.style.opacity = '1'; outEl.style.zIndex = '2';
            inEl.style.transition  = 'none'; inEl.style.transform  = 'rotateX(90deg)'; inEl.style.opacity  = '0'; inEl.style.zIndex  = '1';
            outEl.offsetHeight; 
            
            outEl.style.transition = 'transform ' + half + 'ms ease-in-out, opacity ' + (half * 0.5) + 'ms ' + (half * 0.5) + 'ms ease-in-out';
            outEl.style.transform  = 'rotateX(-90deg)';
            outEl.style.opacity    = '0';
            
            setTimeout(function() {
                outEl.style.zIndex = '0';
                inEl.style.zIndex  = '2';
                inEl.style.transition = 'transform ' + half + 'ms ease-in-out, opacity ' + (half * 0.5) + 'ms ease-in-out';
                inEl.style.transform  = 'rotateX(0deg)';
                inEl.style.opacity    = '1';
                setTimeout(done, half + 50);
            }, half);
        }

        


        function pixel_decode(container, outEl, inEl, dur, done) {
            var w = container.offsetWidth || container.parentElement.offsetWidth || 800;
            var h = container.offsetHeight || container.parentElement.offsetHeight || 500;
            container.style.overflow = 'hidden';
            
            var STEPS = [
                { size: 48, hold: dur * 0.15 },
                { size: 24, hold: dur * 0.15 },
                { size: 12, hold: dur * 0.15 },
                { size:  6, hold: dur * 0.15 },
                { size:  3, hold: dur * 0.20 },
                { size:  1, hold: dur * 0.20 }
            ];
            var totalHold = STEPS.reduce(function(a, s) { return a + s.hold; }, 0);


            function makePixelCanvas(img, pixSize) {
                var cvs = document.createElement('canvas');
                cvs.width = w; cvs.height = h;
                var ctx = cvs.getContext('2d');
                if (pixSize <= 1) {
                    drawCover(ctx, img, w, h);
                } else {
                    
                    var sw = Math.ceil(w / pixSize), sh = Math.ceil(h / pixSize);
                    var tmp = document.createElement('canvas');
                    tmp.width = sw; tmp.height = sh;
                    var tctx = tmp.getContext('2d');
                    tctx.imageSmoothingEnabled = false;
                    drawCover(tctx, img, sw, sh);
                    ctx.imageSmoothingEnabled = false;
                    ctx.drawImage(tmp, 0, 0, sw, sh, 0, 0, w, h);
                }
                cvs.style.cssText = 'position:absolute;inset:0;z-index:6;pointer-events:none;display:block;width:100%;height:100%';
                return cvs;
            }

            var inImg = inEl.querySelector('img');
            var outImg = outEl.querySelector('img');

            
            outEl.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;opacity:0;z-index:0;transition:none;transform:none';
            inEl.style.cssText  = 'position:absolute;inset:0;width:100%;height:100%;opacity:0;z-index:0;transition:none;transform:none';


            var currentCvs = makePixelCanvas(outImg, STEPS[0].size);
            container.appendChild(currentCvs);

            var stepIdx = 0;
            function nextStep() {
                stepIdx++;
                if (stepIdx >= STEPS.length) {
                    
                    currentCvs.remove();
                    inEl.style.opacity = '1';
                    inEl.style.zIndex  = '2';
                    setTimeout(done, 60);
                    return;
                }
                var step = STEPS[stepIdx];
                var nextCvs = makePixelCanvas(inImg, step.size);
                container.appendChild(nextCvs);
                
                nextCvs.style.opacity = '0';
                nextCvs.style.transition = 'opacity 80ms linear';
                nextCvs.offsetHeight;
                nextCvs.style.opacity = '1';
                var old = currentCvs;
                currentCvs = nextCvs;
                setTimeout(function() { old.remove(); }, 120);
                setTimeout(nextStep, step.hold);
            }

            setTimeout(nextStep, STEPS[0].hold);
        }

        

        
        function fade(container, outEl, inEl, dur, done) {
            outEl.style.zIndex  = '1';
            outEl.style.opacity = '1';
            outEl.style.transition = 'none';
            inEl.style.zIndex   = '2';
            inEl.style.opacity  = '0';
            inEl.style.transition = 'none';
            inEl.offsetHeight;
            inEl.style.transition = 'opacity ' + dur + 'ms ease-in-out';
            inEl.style.opacity  = '1';
            setTimeout(function() {
                outEl.style.opacity = '0';
                done();
            }, dur);
        }

        
        function flyin(container, outEl, inEl, dur, done) {
            var imgEl = inEl.querySelector('img');
            outEl.style.zIndex = '1'; outEl.style.opacity = '1';
            inEl.style.zIndex  = '2'; inEl.style.opacity  = '1';
            
            if (imgEl) {
                imgEl.style.animation = 'none'; imgEl.offsetHeight;
                imgEl.style.transformOrigin = 'center bottom';
                imgEl.style.animation = 'impulseFlyIn ' + Math.max(dur * 1.4, 6000) + 'ms ease-in-out forwards';
            }
            
            inEl.style.transition = 'none'; inEl.style.opacity = '0'; inEl.offsetHeight;
            inEl.style.transition = 'opacity ' + dur + 'ms ease-in-out';
            inEl.style.opacity    = '1';
            setTimeout(function() { outEl.style.opacity = '0'; done(); }, dur);
        }

        
        function jackpot(container, outEl, inEl, dur, done) {
            var h = container.offsetHeight || 400;
            var spinSpeed = 28, DECAY = 0.93;
            var spinPos = 0; 
            var traveled = 0, totalDist = h * 4;
            var landTarget = null, easeSpeed = 0;
            var wrap = document.createElement('div');
            wrap.style.cssText = 'position:absolute;inset:0;overflow:hidden;z-index:5';
            
            var stripH = h * 2;
            var strip = document.createElement('div');
            strip.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:' + stripH + 'px;will-change:transform';
            var outClone = outEl.cloneNode(true);
            var inClone  = inEl.cloneNode(true);
            
            [outClone, inClone].forEach(function(cl) {
                cl.removeAttribute('data-id');
                cl.querySelectorAll('[class*="impulse-dropzone"],[class*="impulse-new-slider-dropzone"]').forEach(function(dz) {
                    dz.className = dz.className.replace(/impulse-dropzone|impulse-new-slider-dropzone/g, '').trim();
                });
            });
            outClone.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:' + h + 'px;overflow:hidden;opacity:1;z-index:1;transform:none;transition:none';
            inClone.style.cssText  = 'position:absolute;top:' + h + 'px;left:0;width:100%;height:' + h + 'px;overflow:hidden;opacity:1;z-index:1;transform:none;transition:none';
            strip.appendChild(outClone); strip.appendChild(inClone);
            wrap.appendChild(strip); container.appendChild(wrap);
            outEl.style.opacity = '0'; inEl.style.opacity = '0';

            function starColor(type,v,a){
                if(type===0) return 'rgba(255,255,255,'+a+')';
                var h,s,l;
                if     (type===1){h=210+v*15;s=55;l=88;}
                else if(type===2){h=48+v*10; s=60;l=85;}
                else if(type===3){h=25+v*10; s=65;l=82;}
                else             {h=v*10;    s=60;l=80;}
                return 'hsla('+h+','+s+'%,'+l+'%,'+a+')';
            }

            function frame() {
                if (landTarget !== null) {
                    easeSpeed *= DECAY;
                    spinPos += easeSpeed;
                    var blur = Math.min(8, easeSpeed * 0.28);
                    strip.style.filter = blur > 0.4 ? 'blur(' + blur.toFixed(1) + 'px)' : 'none';
                    strip.style.transform = 'translateY(-' + Math.round(spinPos) + 'px)';
                    if (easeSpeed < 0.4) {
                        spinPos = h; 
                        strip.style.filter = 'none';
                        strip.style.transform = 'translateY(-' + h + 'px)';
                        wrap.remove();
                        inEl.style.opacity = '1';
                        done();
                        return;
                    }
                } else {
                    spinPos += spinSpeed;
                    if (spinPos > stripH) spinPos -= stripH;
                    strip.style.transform = 'translateY(-' + Math.round(spinPos) + 'px)';
                    traveled += spinSpeed;
                    if (traveled >= totalDist) {
                        var minRunway = spinSpeed * 14;
                        landTarget = h + Math.ceil((spinPos + minRunway - h) / h) * h;
                        if (landTarget > stripH) landTarget = h;
                        easeSpeed = spinSpeed;
                    }
                }
                requestAnimationFrame(frame);
            }
            strip.style.filter = 'blur(8px)';
            requestAnimationFrame(frame);
        }

        
        function reels(container, outEl, inEl, dur, done) {
            var h = container.offsetHeight || 400;
            var steps = 5, stepDur = dur / (steps + 2);
            var wrap = document.createElement('div');
            wrap.style.cssText = 'position:absolute;inset:0;overflow:hidden;z-index:5';
            var strip = document.createElement('div');
            strip.style.cssText = 'position:absolute;top:0;left:0;width:100%;will-change:transform;transition:none';
            
            var allEls = [outEl];
            for (var i = 0; i < steps - 1; i++) {
                var ph = document.createElement('div');
                ph.style.cssText = 'width:100%;height:' + h + 'px;background:#1a1d21';
                allEls.push(ph);
            }
            allEls.push(inEl);
            var totalH = h * allEls.length;
            strip.style.height = totalH + 'px';
            allEls.forEach(function(el, i) {
                var isSlide = el.classList && el.classList.contains('impulse-carousel-slide');
                var cl = isSlide ? el.cloneNode(true) : el;
                if (isSlide) {
                    cl.removeAttribute('data-id');
                    cl.querySelectorAll('.impulse-dropzone,.impulse-new-slider-dropzone').forEach(function(dz) {
                        dz.classList.remove('impulse-dropzone','impulse-new-slider-dropzone');
                    });
                }
                cl.style.cssText = 'position:absolute;top:' + (i * h) + 'px;left:0;width:100%;height:' + h + 'px;overflow:hidden;opacity:1;transform:none;transition:none';
                strip.appendChild(cl);
            });
            wrap.appendChild(strip); container.appendChild(wrap);
            outEl.style.opacity = '0'; inEl.style.opacity = '0';
            var targetY = (allEls.length - 1) * h;
            strip.style.filter = 'blur(6px)';
            strip.style.transition = 'transform ' + (dur * 0.85) + 'ms cubic-bezier(0.12,0,0.5,1), filter ' + (dur * 0.7) + 'ms ease-in-out';
            strip.offsetHeight;
            strip.style.transform = 'translateY(-' + targetY + 'px)';
            strip.style.filter = 'none';
            setTimeout(function() {
                wrap.remove();
                inEl.style.opacity = '1';
                done();
            }, dur + 50);
        }

        return {
            depth_rush:   depth_rush,
            card_flip:    card_flip,
            pixel_decode: pixel_decode,
            fade:         fade,
            flyin:        flyin,
            jackpot:      jackpot,
            reels:        reels
        };
    })();


    
    
    function initCarousels() {
        document.querySelectorAll('.impulse-image-carousel').forEach(function(carousel) {
            if (carousel._carouselInit) return;
            carousel._carouselInit = true;
            
            var slides = carousel.querySelector('.impulse-carousel-slides');
            var slideItems = carousel.querySelectorAll('.impulse-carousel-slide');
            var mode = carousel.dataset.mode || 'scroll';

            

            if (!slides || (slideItems.length === 0 && mode !== 'slots' && mode !== 'jackpot' && mode !== 'reels' && mode !== 'table' && mode !== 'orbit' && mode !== 'depth_rush' && mode !== 'card_flip' && mode !== 'pixel_decode')) return;
            var direction = carousel.dataset.direction || 'left';
            var speed = parseInt(carousel.dataset.speed) || 20;
            var autoplay = carousel.dataset.autoplay === 'true';
            var interval = parseInt(carousel.dataset.interval) || 4000;
            var pauseOnHover = carousel.dataset.pause === 'true';
            var itemsToShow = parseInt(carousel.dataset.items) || 1;
            var gap = parseInt(carousel.dataset.gap) || 0;
            var originalCount = parseInt(carousel.dataset.slideCount) || slideItems.length;
            
            if (mode === 'scroll') {
                
                var position = 0;
                var isPaused = false;
                var animId = null;
                
                function getSetWidth() {
                    if (originalCount < 1) originalCount = slideItems.length;
                    var w = 0;
                    for (var i = 0; i < originalCount; i++) {
                        if (slideItems[i]) w += slideItems[i].offsetWidth + gap;
                    }

                    

                    var minSet = slides.parentElement ? slides.parentElement.offsetWidth : 0;
                    if (minSet > 0 && w < minSet) w = minSet;
                    return w;
                }
                
                var setWidth = 0;
                

                var _remeasureCounter = 0;
                function animate() {
                    if (!isPaused) {
                        if (setWidth === 0) setWidth = getSetWidth();
                        
                        if ((_remeasureCounter++ & 63) === 0) {
                            var _m = getSetWidth();
                            if (_m > 0 && Math.abs(_m - setWidth) > 1) setWidth = _m;
                        }
                        if (setWidth > 0) {
                            var pxPerFrame = (slides.parentElement.offsetWidth / speed) / 60;
                            if (direction === 'left') {
                                position -= pxPerFrame;

                                while (position <= -setWidth) position += setWidth;
                                while (position > 0) position -= setWidth;
                            } else {
                                position += pxPerFrame;
                                while (position >= 0) position -= setWidth;
                                while (position < -setWidth) position += setWidth;
                            }
                            slides.style.transform = 'translate3d(' + Math.round(position) + 'px,0,0)';
                        }
                    }
                    animId = requestAnimationFrame(animate);
                }
                
                if (autoplay) {
                    setTimeout(function() {
                        setWidth = getSetWidth();
                        if (direction === 'right') position = -setWidth;
                        animate();
                    }, 50);
                }


                

                function _remeasure() {
                    var next = getSetWidth();
                    if (next > 0 && Math.abs(next - setWidth) > 1) {
                        setWidth = next;
                    }
                }
                var _carouselImgs = slides.querySelectorAll('img');
                _carouselImgs.forEach(function(img) {
                    if (!img.complete) img.addEventListener('load', _remeasure, { once: true });
                });
                window.addEventListener('load', _remeasure, { once: true });
                window.addEventListener('resize', _remeasure);
                
                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { isPaused = true; });
                    carousel.addEventListener('mouseleave', function() { isPaused = false; });
                }
                
                carousel._destroyCarousel = function() {
                    if (animId) cancelAnimationFrame(animId);
                };

                
                var _dragStartPos = 0;
                attachCarouselDrag(slides,
                    function(delta, wasDrag) {
                        if (wasDrag && setWidth > 0) {
                            position = _dragStartPos + delta;
                            while (position > 0) position -= setWidth;
                            while (position < -setWidth) position += setWidth;
                        }
                        isPaused = false;
                    },
                    function(delta) {
                        slides.style.transform = 'translate3d(' + Math.round(_dragStartPos + delta) + 'px,0,0)';
                    },
                    function() { _dragStartPos = position; isPaused = true; }
                );

            } else if (mode === 'slots') {

                var reels = carousel.querySelectorAll('.impulse-slot-reel');
                if (reels.length === 0) return;
                var autoplayTimer = null;
                var isPaused = false;
                var reelHeight = reels[0].offsetHeight;
                var reelStates = [];
                var slotSpinning = false;
                var slotSpinningCount = 0;
                
                var SPIN_CYCLES = 2;
                var SPIN_DUR_MS = 2000;
                var SPIN_BLUR_PX = 5;
                var SPIN_EASING  = 'cubic-bezier(0.4, 0, 0.2, 1)';

                reels.forEach(function(reel, ri) {
                    var strip = reel.querySelector('.impulse-slot-strip');
                    var count = parseInt(reel.dataset.count) || originalCount;
                    var totalItems = strip.querySelectorAll('.impulse-slot-item').length;
                    strip.style.transition = 'none';
                    strip.style.transform = 'translateY(0)';
                    strip.style.filter = 'none';
                    reelStates.push({ strip: strip, pos: 0, count: count, totalItems: totalItems });
                });

                function spinReel(ri) {
                    var state = reelStates[ri];
                    var strip = state.strip;
                    var nextPos = (state.pos + 1) % state.count;
                    var startY  = state.pos * reelHeight;
                    var spinDist = (SPIN_CYCLES * state.count + 1) * reelHeight;
                    var endY = startY + spinDist;
                    strip.style.transition = 'none';
                    strip.style.transform  = 'translateY(-' + startY + 'px)';
                    strip.style.filter     = 'blur(' + SPIN_BLUR_PX + 'px)';
                    strip.offsetHeight;
                    strip.style.transition = 'transform ' + SPIN_DUR_MS + 'ms ' + SPIN_EASING + ', filter 350ms ease-in-out ' + (SPIN_DUR_MS - 350) + 'ms';
                    strip.style.filter     = 'none';
                    strip.style.transform  = 'translateY(-' + endY + 'px)';
                    slotSpinningCount++;
                    setTimeout(function() {
                        strip.style.transition = 'none';
                        strip.style.transform  = 'translateY(-' + (nextPos * reelHeight) + 'px)';
                        state.pos = nextPos;
                        slotSpinningCount--;
                        if (slotSpinningCount === 0) slotSpinning = false;
                    }, SPIN_DUR_MS + 60);
                }

                function spinReels() {
                    if (slotSpinning) return;
                    slotSpinning = true;
                    reels.forEach(function(reel, ri) {
                        setTimeout(function() { spinReel(ri); }, ri * 180);
                    });
                }

                if (autoplay) {
                    setTimeout(function(){ if (!isPaused) spinReels(); }, 300);
                    autoplayTimer = setInterval(function() {
                        if (!isPaused) spinReels();
                    }, interval);
                }

                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { isPaused = true; });
                    carousel.addEventListener('mouseleave', function() { isPaused = false; });
                }

                carousel._destroyCarousel = function() {
                    if (autoplayTimer) clearInterval(autoplayTimer);
                };
                
            } else if (mode === 'jackpot') {
                
                var reels = carousel.querySelectorAll('.impulse-slot-reel');
                if (reels.length === 0) return;
                var autoplayTimer = null;
                var isPaused = false;
                var reelHeight = reels[0].offsetHeight;
                var spinning = false;
                var reelStates = [];
                
                reels.forEach(function(reel, ri) {
                    var strip = reel.querySelector('.impulse-slot-strip');
                    var count = parseInt(reel.dataset.count) || originalCount;
                    var totalItems = strip.querySelectorAll('.impulse-slot-item').length;
                    reelStates.push({ strip: strip, pos: 0, count: count, totalItems: totalItems });
                });
                
                var spinningCount = 0;

                
                
                var JP_SPIN_CYCLES = 4;
                var JP_SPIN_DUR_MS = 3500;
                var JP_ANTICIP_MS = 280;
                var JP_ANTICIP_PX = 28;
                var JP_BLUR_PX = 9;
                var JP_EASING = 'cubic-bezier(0.45,0,0.2,1)';

                
                reelStates.forEach(function(s){
                    s.strip.style.transition = 'none';
                    s.strip.style.transform = 'translateY(0)';
                    s.strip.style.filter = 'none';
                });

                function jackpotSpinReel(ri) {
                    var state = reelStates[ri];
                    var strip = state.strip;
                    var nextPos = (state.pos + 1) % state.count;
                    var startY = state.pos * reelHeight;
                    var spinDist = (JP_SPIN_CYCLES * state.count + 1) * reelHeight;
                    var endY = startY + spinDist;
                    var dur = JP_SPIN_DUR_MS + ri * 250;
                    
                    strip.style.transition = 'none';
                    strip.style.transform  = 'translateY(-' + startY + 'px)';
                    strip.style.filter     = 'none';
                    strip.offsetHeight;
                    strip.style.transition = 'transform ' + JP_ANTICIP_MS + 'ms cubic-bezier(0.4,0,0.6,1)';
                    strip.style.transform  = 'translateY(-' + (startY - JP_ANTICIP_PX) + 'px)';
                    spinningCount++;
                    setTimeout(function() {
                        strip.style.transition = 'transform ' + dur + 'ms ' + JP_EASING + ', filter 500ms ease-in-out ' + (dur - 500) + 'ms';
                        strip.style.filter     = 'blur(' + JP_BLUR_PX + 'px)';
                        strip.style.transform  = 'translateY(-' + endY + 'px)';
                        setTimeout(function(){ strip.style.filter = 'none'; }, dur - 480);
                        setTimeout(function() {
                            strip.style.transition = 'none';
                            strip.style.transform  = 'translateY(-' + (nextPos * reelHeight) + 'px)';
                            state.pos = nextPos;
                            spinningCount--;
                            if (spinningCount === 0) spinning = false;
                        }, dur + 60);
                    }, JP_ANTICIP_MS + 20);
                }

                function jackpotSpin() {
                    if (spinning) return;
                    spinning = true;
                    reels.forEach(function(reel, ri) { jackpotSpinReel(ri); });
                }
                
                if (autoplay) {
                    setTimeout(function(){ if (!isPaused && !spinning) jackpotSpin(); }, 300);
                    autoplayTimer = setInterval(function() {
                        if (!isPaused && !spinning) jackpotSpin();
                    }, interval);
                }
                
                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { isPaused = true; });
                    carousel.addEventListener('mouseleave', function() { isPaused = false; });
                }
                
                carousel._destroyCarousel = function() {
                    if (autoplayTimer) clearInterval(autoplayTimer);
                };
                
            } else if (mode === 'reels') {

                

                var reels = carousel.querySelectorAll('.impulse-slot-reel');
                if (reels.length === 0) return;
                var autoplayTimer = null;
                var isPaused = false;
                var reelHeight = reels[0].offsetHeight;
                var spinning = false;
                var spinningCount = 0;
                var reelStates = [];

                var R_SPIN_CYCLES = 3;
                var R_SPIN_DUR_MS = 1500;
                var R_SPIN_BLUR_PX = 12;
                var R_SPIN_EASING  = 'cubic-bezier(0.35,0,0.05,1)';

                reels.forEach(function(reel, ri) {
                    var strip = reel.querySelector('.impulse-slot-strip');
                    var count = parseInt(reel.dataset.count) || originalCount;
                    var totalItems = strip.querySelectorAll('.impulse-slot-item').length;
                    strip.style.transition = 'none';
                    strip.style.transform = 'translateY(0)';
                    strip.style.filter = 'none';
                    reelStates.push({ strip: strip, pos: 0, count: count, totalItems: totalItems });
                });

                function reelsSpinReel(ri) {
                    var state = reelStates[ri];
                    var strip = state.strip;
                    var nextPos = (state.pos + 1) % state.count;
                    var startY = state.pos * reelHeight;
                    var spinDist = (R_SPIN_CYCLES * state.count + 1) * reelHeight;
                    var endY = startY + spinDist;
                    var dur = R_SPIN_DUR_MS + ri * 220;
                    strip.style.transition = 'none';
                    strip.style.transform  = 'translateY(-' + startY + 'px)';
                    strip.style.filter     = 'blur(' + R_SPIN_BLUR_PX + 'px)';
                    strip.offsetHeight;
                    strip.style.transition = 'transform ' + dur + 'ms ' + R_SPIN_EASING + ', filter 280ms ease-in-out ' + (dur - 280) + 'ms';
                    strip.style.filter     = 'none';
                    strip.style.transform  = 'translateY(-' + endY + 'px)';
                    spinningCount++;
                    setTimeout(function() {
                        strip.style.transition = 'none';
                        strip.style.transform  = 'translateY(-' + (nextPos * reelHeight) + 'px)';
                        state.pos = nextPos;
                        spinningCount--;
                        if (spinningCount === 0) spinning = false;
                    }, dur + 60);
                }

                function reelsSpin() {
                    if (spinning) return;
                    spinning = true;
                    reels.forEach(function(reel, ri) { reelsSpinReel(ri); });
                }

                if (autoplay) {
                    setTimeout(function(){ if (!isPaused && !spinning) reelsSpin(); }, 300);
                    autoplayTimer = setInterval(function() {
                        if (!isPaused && !spinning) reelsSpin();
                    }, interval);
                }

                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { isPaused = true; });
                    carousel.addEventListener('mouseleave', function() { isPaused = false; });
                }

                carousel._destroyCarousel = function() {
                    if (autoplayTimer) clearInterval(autoplayTimer);
                };
                
            } else if (mode === 'table' || mode === 'orbit') {
                
                var items = slides.querySelectorAll('.impulse-turntable-item');
                if (items.length === 0) { console.warn('[impulse carousel] orbit/table mode but no .impulse-turntable-item found'); return; }

                
                slides.style.position = 'relative';
                slides.style.width = '100%';
                slides.style.height = '100%';
                slides.style.overflow = 'visible';
                var totalItems = items.length;
                var isPaused = false;
                var animId = null;
                var containerW = slides.offsetWidth;
                var containerH = slides.offsetHeight;
                var TWO_PI = Math.PI * 2;

                var xSpread, yOffsetFactor, scaleMin, scaleMax, blurMax;
                if (mode === 'orbit') {
                    
                    xSpread = 0.40; yOffsetFactor = 0.20; scaleMin = 0.32; scaleMax = 1.0; blurMax = 18;
                } else {

                    
                    xSpread = 0.45; yOffsetFactor = 0; scaleMin = 0.45; scaleMax = 1.0; blurMax = 14;
                }

                var angles = [];
                for (var i = 0; i < totalItems; i++) {
                    angles.push((i / totalItems) * TWO_PI);
                }


                

                var radiansPerFrame = 0.012;
                var dirMult = (direction === 'right') ? -1 : 1;


                
                
                var tiltSens = parseInt(carousel.getAttribute('data-tilt-sens') || '5', 10);
                if (isNaN(tiltSens)) tiltSens = 5;
                var sensMult = Math.max(0, Math.min(10, tiltSens)) / 10;
                var biasTarget = 0, biasCurrent = 0;
                var swipeBias = 0; 
                var mouseBiasTarget = 0, gyroBiasTarget = 0;
                function recomputeBiasTarget() {
                    
                    var b = mouseBiasTarget + gyroBiasTarget;
                    if (b > 1) b = 1; else if (b < -1) b = -1;
                    biasTarget = b;
                }

                function updatePositions() {
                    containerW = slides.offsetWidth;
                    containerH = slides.offsetHeight;

                    for (var i = 0; i < totalItems; i++) {
                        var angle = angles[i];
                        var sinA = Math.sin(angle);
                        var cosA = Math.cos(angle);
                        var depth = (cosA + 1) / 2;
                        var x = sinA * xSpread * containerW;
                        var y = yOffsetFactor > 0 ? -cosA * yOffsetFactor * containerH : 0;
                        var sc = scaleMin + (scaleMax - scaleMin) * depth;
                        var bl = blurMax * (1 - depth) * (1 - depth);
                        var item = items[i];

                        if (mode === 'table') {
                            var scX = cosA;
                            item.style.transform = 'translateX(calc(-50% + ' + x.toFixed(1) + 'px)) translateY(' + y.toFixed(1) + 'px) scale(' + sc.toFixed(3) + ') scaleX(' + scX.toFixed(3) + ')';
                        } else {
                            item.style.transform = 'translateX(calc(-50% + ' + x.toFixed(1) + 'px)) translateY(' + y.toFixed(1) + 'px) scale(' + sc.toFixed(3) + ')';
                        }
                        item.style.filter = bl > 0.3 ? 'blur(' + bl.toFixed(1) + 'px)' : 'none';
                        item.style.opacity = '1';
                        item.style.zIndex = Math.round(depth * 1000);
                    }
                }

                function animate() {
                    if (!isPaused) {
                        
                        biasCurrent += (biasTarget - biasCurrent) * 0.1;

                        var biasRad = biasCurrent * sensMult * radiansPerFrame * 2;
                        
                        swipeBias *= 0.92;
                        var totalRad = (radiansPerFrame * dirMult) + biasRad + swipeBias;
                        for (var i = 0; i < totalItems; i++) {
                            angles[i] = (angles[i] + totalRad) % TWO_PI;
                            if (angles[i] < 0) angles[i] += TWO_PI;
                        }
                        updatePositions();
                    }
                    animId = requestAnimationFrame(animate);
                }

                
                if (sensMult > 0) {
                    carousel.addEventListener('mousemove', function(e) {
                        var r = carousel.getBoundingClientRect();
                        mouseBiasTarget = ((e.clientX - r.left) / r.width) * 2 - 1;
                        recomputeBiasTarget();
                    });
                    carousel.addEventListener('mouseleave', function() {
                        mouseBiasTarget = 0;
                        recomputeBiasTarget();
                    });


                    
                    var bindGyro = function() {
                        window.addEventListener('deviceorientation', function(e) {
                            var g = e.gamma || 0;
                            
                            var v = g / 45;
                            if (v > 1) v = 1; else if (v < -1) v = -1;
                            gyroBiasTarget = v;
                            recomputeBiasTarget();
                        });
                    };
                    if (typeof DeviceOrientationEvent !== 'undefined' &&
                        typeof DeviceOrientationEvent.requestPermission === 'function') {
                        var onFirstTap = function() {
                            DeviceOrientationEvent.requestPermission().then(function(r) {
                                if (r === 'granted') bindGyro();
                            }).catch(function() {});
                        };
                        document.addEventListener('touchstart', onFirstTap, { once: true });
                    } else if ('ontouchstart' in window) {
                        bindGyro();
                    }
                }


                
                
                attachCarouselDrag(
                    slides,
                    function onRelease(delta, didDrag) {
                        if (!didDrag) return;
                        
                        var fullCircle = TWO_PI;
                        var denom = Math.max(1, xSpread * slides.offsetWidth * totalItems);
                        var flick = -(delta / denom) * fullCircle * 0.08;
                        swipeBias += flick;
                    },
                    function onDragMove(delta) {

                        var diff = delta - (onDragMove._prev || 0);
                        onDragMove._prev = delta;
                        var fullCircle = TWO_PI;
                        var denom = Math.max(1, xSpread * slides.offsetWidth * totalItems);
                        var da = -(diff / denom) * fullCircle;
                        for (var i = 0; i < totalItems; i++) {
                            angles[i] = (angles[i] + da) % TWO_PI;
                            if (angles[i] < 0) angles[i] += TWO_PI;
                        }
                        updatePositions();
                    },
                    function onDragStart() { onDragMove._prev = 0; }
                );

                updatePositions();
                animId = requestAnimationFrame(animate);


                
                
                if (pauseOnHover && sensMult <= 0) {
                    carousel.addEventListener('mouseenter', function() { isPaused = true; });
                    carousel.addEventListener('mouseleave', function() { isPaused = false; });
                }

                carousel._destroyCarousel = function() {
                    if (animId) cancelAnimationFrame(animId);
                };

            } else if (mode === 'cube') {

                

                var cuSlides = slides.querySelectorAll('.impulse-carousel-slide');
                var cuTotal = cuSlides.length;
                if (cuTotal < 2) return;
                slides.style.position = 'relative';
                slides.style.overflow = 'visible';
                slides.style.display = 'block';
                slides.style.height = '100%';
                slides.style.transformStyle = 'preserve-3d';
                
                slides.style.transition = 'none';
                var cuTrack = slides.parentElement;
                if (cuTrack) { cuTrack.style.perspective = '1600px'; cuTrack.style.perspectiveOrigin = 'center center'; cuTrack.style.overflow = 'visible'; }
                var cuFaceAngle = 360 / cuTotal;
                var cuApothem = 0;
                function cuCalc() {
                    var w = slides.offsetWidth || (cuTrack ? cuTrack.offsetWidth : 600);
                    cuApothem = (w / 2) / Math.max(Math.tan((cuFaceAngle / 2) * Math.PI / 180), 0.01);
                }
                cuCalc();
                cuSlides.forEach(function(s, i) {
                    s.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;transform-style:preserve-3d;backface-visibility:hidden;transition:none';
                    s.style.transform = 'rotateY(' + (i * cuFaceAngle) + 'deg) translateZ(' + cuApothem + 'px)';
                });

                var cuCurrent = 0;
                var cuAngleDeg = 0;
                function cuWrite() {
                    slides.style.transform = 'translateZ(-' + cuApothem + 'px) rotateY(' + cuAngleDeg.toFixed(2) + 'deg)';

                    

                    for (var _ci = 0; _ci < cuSlides.length; _ci++) {
                        var _ca = ((_ci * cuFaceAngle + cuAngleDeg) % 360 + 540) % 360 - 180;
                        cuSlides[_ci].style.opacity = (Math.abs(_ca) < cuFaceAngle * 0.6) ? '1' : '0';
                        cuSlides[_ci].style.transition = 'opacity 0.25s ease-in-out';
                    }
                }
                cuWrite();
                
                var cuTiltSens = parseInt(carousel.getAttribute('data-tilt-sens') || '5', 10);
                if (isNaN(cuTiltSens)) cuTiltSens = 5;
                var cuSensMult = Math.max(0, Math.min(10, cuTiltSens)) / 10;
                var cuMouseBias = 0, cuGyroBias = 0;
                var cuBiasCurrent = 0;
                var cuSwipeDeg = 0;      
                var cuDragging = false;  
                var cuPaused = false;
                
                var cuBaseDegPerFrame = (cuFaceAngle / Math.max(1, interval / 1000 * 60));
                var cuDirMult = (direction === 'right') ? -1 : 1;

                function cuFrame() {
                    if (!cuPaused && !cuDragging) {
                        cuBiasCurrent += ((cuMouseBias + cuGyroBias) - cuBiasCurrent) * 0.1;

                        

                        
                        var baseStep = cuBaseDegPerFrame * cuDirMult;
                        var biasDeg = cuBiasCurrent * cuSensMult * cuBaseDegPerFrame * 0.6 * cuDirMult;
                        cuSwipeDeg *= 0.92;
                        cuAngleDeg += baseStep + biasDeg + cuSwipeDeg;
                        
                        cuCurrent = ((Math.round(-cuAngleDeg / cuFaceAngle) % cuTotal) + cuTotal) % cuTotal;
                        cuWrite();
                    }
                    cuFrameId = requestAnimationFrame(cuFrame);
                }
                var cuFrameId = requestAnimationFrame(cuFrame);

                if (cuSensMult > 0) {
                    carousel.addEventListener('mousemove', function(e) {
                        var r = carousel.getBoundingClientRect();
                        var v = ((e.clientX - r.left) / r.width) * 2 - 1;
                        cuMouseBias = v;
                    });
                    carousel.addEventListener('mouseleave', function() { cuMouseBias = 0; });
                    var cuBindGyro = function() {
                        window.addEventListener('deviceorientation', function(e) {
                            var g = e.gamma || 0;
                            var v = g / 45;
                            if (v > 1) v = 1; else if (v < -1) v = -1;
                            cuGyroBias = v;
                        });
                    };
                    if (typeof DeviceOrientationEvent !== 'undefined' &&
                        typeof DeviceOrientationEvent.requestPermission === 'function') {
                        var cuFirstTap = function() {
                            DeviceOrientationEvent.requestPermission().then(function(r) {
                                if (r === 'granted') cuBindGyro();
                            }).catch(function() {});
                        };
                        document.addEventListener('touchstart', cuFirstTap, { once: true });
                    } else if ('ontouchstart' in window) {
                        cuBindGyro();
                    }
                }

                
                attachCarouselDrag(
                    slides,
                    function onRelease(delta, didDrag) {
                        cuDragging = false;
                        if (!didDrag) return;
                        
                        var w = slides.offsetWidth || 600;
                        cuSwipeDeg += -(delta / w) * cuFaceAngle * 0.5;
                    },
                    function onDragMove(delta) {
                        var diff = delta - (onDragMove._prev || 0);
                        onDragMove._prev = delta;
                        var w = slides.offsetWidth || 600;
                        cuAngleDeg += -(diff / w) * cuFaceAngle;
                        cuWrite();
                    },
                    function onDragStart() { onDragMove._prev = 0; cuDragging = true; }
                );


                if (pauseOnHover && cuSensMult <= 0) {
                    carousel.addEventListener('mouseenter', function() { cuPaused = true; });
                    carousel.addEventListener('mouseleave', function() { cuPaused = false; });
                }
                window.addEventListener('resize', function() {
                    cuCalc();
                    cuSlides.forEach(function(s, i) { s.style.transform = 'rotateY(' + (i * cuFaceAngle) + 'deg) translateZ(' + cuApothem + 'px)'; });
                    cuWrite();
                });
                carousel._destroyCarousel = function() { if (cuFrameId) cancelAnimationFrame(cuFrameId); };

            } else if (mode === 'conveyor') {

                var cvSlides = slides.querySelectorAll('.impulse-carousel-slide');
                var cvTotal = cvSlides.length;
                if (cvTotal < 1) return;
                slides.style.position = 'relative';
                slides.style.overflow = 'visible';
                slides.style.display = 'block';
                slides.style.height = '100%';
                slides.style.transformStyle = 'preserve-3d';
                slides.style.transform = 'rotateX(0deg)';
                slides.style.willChange = 'transform';
                var cvTrack = slides.parentElement;
                if (cvTrack) { cvTrack.style.perspective = '1400px'; cvTrack.style.perspectiveOrigin = 'center 25%'; cvTrack.style.overflow = 'visible'; }
                cvSlides.forEach(function(s) {
                    s.style.cssText = 'position:absolute;top:50%;left:50%;width:50%;height:80%;transform-style:preserve-3d;backface-visibility:hidden;transition:transform 0.6s cubic-bezier(0.4, 0, 0.2, 1),opacity 0.6s ease-in-out,filter 0.35s ease-in-out;cursor:pointer;will-change:transform,filter';
                });
                var cvCurrent = 0;
                var cvMx = 0, cvMy = 0;
                function cvUpdate() {
                    for (var i = 0; i < cvTotal; i++) {
                        var dist = i - cvCurrent;
                        if (dist >  cvTotal / 2) dist -= cvTotal;
                        if (dist < -cvTotal / 2) dist += cvTotal;
                        var abs = Math.abs(dist);
                        var sign = dist > 0 ? 1 : (dist < 0 ? -1 : 0);
                        var tx = sign * Math.min(abs, 5) * 55;
                        var tz = -abs * 160;
                        var sc = Math.max(0.55, 1 - abs * 0.1);
                        var op = abs > 4 ? 0 : Math.max(0.3, 1 - abs * 0.18);
                        var s = cvSlides[i];
                        s.style.transform = 'translate(-50%,-50%) translateX(' + tx.toFixed(1) + '%) translateZ(' + tz.toFixed(0) + 'px) scale(' + sc.toFixed(3) + ')';
                        s.style.opacity = op.toFixed(3);
                        s.style.zIndex = String(100 - abs);
                        s.style.pointerEvents = abs > 4 ? 'none' : 'auto';
                        var bl = (abs === 0) ? 0 : Math.min(14, abs * 5);
                        s.style.filter = bl > 0 ? 'blur(' + bl.toFixed(1) + 'px)' : 'none';
                    }
                }

                

                var cvRx = 0, cvRy = 0, cvRxT = 0, cvRyT = 0, cvEaseId = null;
                function cvWriteBelt() {
                    slides.style.transform = 'rotateX(' + cvRx.toFixed(2) + 'deg) rotateY(' + cvRy.toFixed(2) + 'deg)';
                }
                function cvEase() {

                    cvRxT = cvMy * 14;
                    cvRyT = cvMx * 4;
                    var dx = cvRxT - cvRx, dy = cvRyT - cvRy;
                    if (Math.abs(dx) < 0.03 && Math.abs(dy) < 0.03) {
                        cvRx = cvRxT; cvRy = cvRyT; cvWriteBelt(); cvEaseId = null; return;
                    }
                    
                    cvRx += dx * 0.04; cvRy += dy * 0.04; cvWriteBelt();
                    cvEaseId = requestAnimationFrame(cvEase);
                }
                function cvKickEase() { if (!cvEaseId) cvEaseId = requestAnimationFrame(cvEase); }
                cvWriteBelt();
                cvUpdate();
                cvSlides.forEach(function(s, i) {
                    s.addEventListener('click', function(e) { e.preventDefault(); if (i !== cvCurrent) { cvCurrent = i; } else { cvCurrent = (cvCurrent + 1) % cvTotal; } cvUpdate(); });
                });
                carousel.addEventListener('mousemove', function(e) {
                    var r = carousel.getBoundingClientRect();
                    cvMx = ((e.clientX - r.left) / r.width) * 2 - 1;
                    cvMy = ((e.clientY - r.top) / r.height) * 2 - 1;
                    cvKickEase();
                });
                carousel.addEventListener('mouseleave', function() {
                    cvMx = 0; cvMy = 0; cvKickEase();
                });
                var cvAutoplay = null, cvPaused = false;
                if (autoplay) {
                    setTimeout(function(){ if (!cvPaused) { cvCurrent = (cvCurrent + 1) % cvTotal; cvUpdate(); } }, 300);
                    cvAutoplay = setInterval(function() { if (!cvPaused) { cvCurrent = (cvCurrent + 1) % cvTotal; cvUpdate(); } }, interval);
                }
                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { cvPaused = true; });
                    carousel.addEventListener('mouseleave', function() { cvPaused = false; });
                }
                carousel._destroyCarousel = function() { if (cvAutoplay) clearInterval(cvAutoplay); };

                
                carousel._relayout = function() {
                    cvUpdate(); cvWriteBelt();
                    if (autoplay && !cvAutoplay) cvAutoplay = setInterval(function() { if (!cvPaused) { cvCurrent = (cvCurrent + 1) % cvTotal; cvUpdate(); } }, interval);
                };

            } else if (mode === 'portal') {

                

                var ptSlides = slides.querySelectorAll('.impulse-carousel-slide');
                var ptTotal = ptSlides.length;
                if (ptTotal < 1) return;
                slides.style.position = 'relative';
                slides.style.overflow = 'visible';
                slides.style.display = 'block';
                slides.style.height = '100%';
                slides.style.transformStyle = 'preserve-3d';
                var ptTrack = slides.parentElement;
                if (ptTrack) { ptTrack.style.perspective = '1200px'; ptTrack.style.perspectiveOrigin = 'center center'; ptTrack.style.overflow = 'visible'; }
                var PT_DUR = 1100;
                ptSlides.forEach(function(s) {
                    s.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;transform-style:preserve-3d;backface-visibility:hidden;will-change:transform,clip-path,opacity;transition:clip-path ' + PT_DUR + 'ms cubic-bezier(0.4, 0, 0.2, 1),transform ' + PT_DUR + 'ms cubic-bezier(0.4, 0, 0.2, 1),opacity ' + (PT_DUR - 200) + 'ms ease-in-out;clip-path:circle(0% at 50% 50%);transform:translateZ(-800px) scale(0.6) rotateZ(-30deg);opacity:0';
                });
                
                ptSlides[0].style.clipPath = 'circle(140% at 50% 50%)';
                ptSlides[0].style.transform = 'translateZ(0px) scale(1) rotateZ(0deg)';
                ptSlides[0].style.opacity = '1';
                ptSlides[0].style.zIndex = '10';
                var ptCurrent = 0;
                var ptBusy = false;
                function ptGoTo(next) {
                    var prev = ptCurrent;
                    ptCurrent = ((next % ptTotal) + ptTotal) % ptTotal;
                    if (prev === ptCurrent || ptBusy) return;
                    ptBusy = true;
                    var outS = ptSlides[prev];
                    var inS  = ptSlides[ptCurrent];
                    
                    inS.style.transition = 'none';
                    inS.style.clipPath   = 'circle(0% at 50% 50%)';
                    inS.style.transform  = 'translateZ(-800px) scale(0.6) rotateZ(-30deg)';
                    inS.style.opacity    = '0';
                    inS.style.zIndex     = '11';
                    
                    void inS.offsetHeight;
                    inS.style.transition = 'clip-path ' + PT_DUR + 'ms cubic-bezier(0.4, 0, 0.2, 1),transform ' + PT_DUR + 'ms cubic-bezier(0.4, 0, 0.2, 1),opacity ' + (PT_DUR - 200) + 'ms ease-in-out';
                    
                    outS.style.zIndex    = '9';
                    outS.style.clipPath  = 'circle(0% at 50% 50%)';
                    outS.style.transform = 'translateZ(400px) scale(1.4) rotateZ(25deg)';
                    outS.style.opacity   = '0';
                    
                    inS.style.clipPath   = 'circle(140% at 50% 50%)';
                    inS.style.transform  = 'translateZ(0px) scale(1) rotateZ(0deg)';
                    inS.style.opacity    = '1';
                    setTimeout(function() { inS.style.zIndex = '10'; ptBusy = false; }, PT_DUR + 50);
                }
                
                ptSlides.forEach(function(s) {
                    s.addEventListener('click', function(e) {
                        if (e.target.closest('a,button')) return;
                        ptGoTo(ptCurrent + 1);
                    });
                });
                var ptAutoplay = null, ptPaused = false;
                if (autoplay) {
                    setTimeout(function(){ if (!ptPaused) ptGoTo(ptCurrent + 1); }, 300);
                    ptAutoplay = setInterval(function() { if (!ptPaused) ptGoTo(ptCurrent + 1); }, Math.max(interval, PT_DUR + 500));
                }
                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { ptPaused = true; });
                    carousel.addEventListener('mouseleave', function() { ptPaused = false; });
                }
                carousel._destroyCarousel = function() { if (ptAutoplay) clearInterval(ptAutoplay); };

            } else if (mode === 'coverflow') {

                
                var cfSlides = slides.querySelectorAll('.impulse-carousel-slide');
                var cfTotal = cfSlides.length;
                if (cfTotal < 1) return;
                slides.style.position = 'relative';
                slides.style.overflow = 'visible';
                slides.style.display  = 'block';
                slides.style.height   = '100%';
                var cfTrack = slides.parentElement;
                if (cfTrack) {
                    cfTrack.style.perspective = '1400px';
                    cfTrack.style.perspectiveOrigin = 'center 50%';
                    cfTrack.style.overflow = 'hidden';

                    
                    
                    var _cfMask = 'linear-gradient(90deg, transparent 0%, rgba(0,0,0,0.15) 11%, #000 20%, #000 80%, rgba(0,0,0,0.15) 89%, transparent 100%)';
                    cfTrack.style.webkitMaskImage = _cfMask;
                    cfTrack.style.maskImage = _cfMask;
                }
                
                var cfSlideWPct = 60;
                cfSlides.forEach(function(s) {
                    s.style.cssText = 'position:absolute;top:0;left:50%;width:' + cfSlideWPct + '%;height:100%;transform-style:preserve-3d;backface-visibility:hidden;will-change:transform,opacity,filter;transition:transform 0.55s cubic-bezier(0.4, 0, 0.2, 1),opacity 0.55s ease-in-out,filter 0.55s ease-in-out;cursor:pointer';
                });

                var cfCurrent = 0;
                var cfAutoplayTimer = null;
                var cfPaused = false;

                function cfUpdate() {
                    for (var i = 0; i < cfTotal; i++) {
                        var dist = i - cfCurrent;
                        
                        if (dist >  cfTotal / 2) dist -= cfTotal;
                        if (dist < -cfTotal / 2) dist += cfTotal;
                        var abs = Math.abs(dist);
                        var sign = dist > 0 ? 1 : (dist < 0 ? -1 : 0);
                        
                        var tx = sign * Math.min(abs, 4) * 38;
                        
                        var tz = -abs * 180;
                        
                        var ry = abs === 0 ? 0 : sign * -55;
                        
                        var sc = Math.max(0.55, 1 - abs * 0.08);
                        var op = abs > 3 ? 0 : Math.max(0.25, 1 - abs * 0.22);
                        var s = cfSlides[i];
                        s.style.transform = 'translate(-50%,0) translateX(' + tx.toFixed(1) + '%) translateZ(' + tz.toFixed(0) + 'px) rotateY(' + ry + 'deg) scale(' + sc.toFixed(3) + ')';
                        s.style.opacity = op.toFixed(3);
                        s.style.zIndex = String(100 - abs);
                        s.style.pointerEvents = abs > 3 ? 'none' : 'auto';

                        

                        s.style.filter = abs === 0 ? 'none' : 'blur(' + Math.min(24, abs * 10).toFixed(1) + 'px)';
                    }
                }

                function cfGoTo(index) {
                    cfCurrent = ((index % cfTotal) + cfTotal) % cfTotal;
                    cfUpdate();
                }

                cfUpdate();

                
                cfSlides.forEach(function(s, i) {
                    s.addEventListener('click', function(e) {
                        e.preventDefault();
                        if (i !== cfCurrent) cfGoTo(i);       
                        else cfGoTo(cfCurrent + 1);           
                    });
                });

                
                attachCarouselDrag(slides,
                    function(delta, wasDrag) {
                        if (!wasDrag) return;
                        var threshold = slides.parentElement.offsetWidth * 0.12;
                        if (delta < -threshold) cfGoTo(cfCurrent + 1);
                        else if (delta > threshold) cfGoTo(cfCurrent - 1);
                    },
                    null,
                    function() { if (cfAutoplayTimer) { clearInterval(cfAutoplayTimer); cfAutoplayTimer = null; } }
                );

                if (autoplay) {
                    setTimeout(function(){ if (!cfPaused) cfGoTo(cfCurrent + 1); }, 300);
                    cfAutoplayTimer = setInterval(function() {
                        if (!cfPaused) cfGoTo(cfCurrent + 1);
                    }, interval);
                }
                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { cfPaused = true; });
                    carousel.addEventListener('mouseleave', function() { cfPaused = false; });
                }

                carousel._destroyCarousel = function() {
                    if (cfAutoplayTimer) clearInterval(cfAutoplayTimer);
                };

            } else if (mode === 'depth_rush') {

                

                var drSlides = slides.querySelectorAll('.impulse-carousel-slide');
                var drTotal = drSlides.length;
                if (drTotal < 1) return;
                slides.style.position = 'relative';
                slides.style.overflow = 'visible'; 
                slides.style.display = 'block';
                slides.style.height = '100%';
                var drTrack = slides.parentElement;
                if (drTrack) {
                    drTrack.style.perspective = '1400px';
                    drTrack.style.perspectiveOrigin = 'center center';
                    drTrack.style.overflow = 'hidden'; 
                }

                
                
                function drState(phase) {
                    var z, scale, opacity, t;
                    if (phase < 0.05) {
                        t = phase / 0.05;
                        z = -2000 + t * 400; scale = 0.08 + t * 0.12; opacity = t * 0.6;
                    } else if (phase < 0.55) {
                        t = (phase - 0.05) / 0.50;
                        z = -1600 + t * 1300; scale = 0.20 + t * 0.55; opacity = 0.6 + t * 0.4;
                    } else if (phase < 0.80) {
                        t = (phase - 0.55) / 0.25;
                        z = -300 + t * 300; scale = 0.75 + t * 0.25; opacity = 1;
                    } else if (phase < 0.95) {
                        t = (phase - 0.80) / 0.15;
                        z = 0 + t * 500; scale = 1.00 + t * 0.35; opacity = 1 - t;
                    } else {
                        z = -2000; scale = 0.08; opacity = 0;
                    }
                    return { z: z, scale: scale, opacity: opacity };
                }
                function drPaint(s, phase) {
                    var st = drState(phase);
                    s.style.opacity = st.opacity.toFixed(3);
                    s.style.transform = 'translate3d(0,0,' + st.z.toFixed(0) + 'px) scale(' + st.scale.toFixed(3) + ')';
                    s.style.zIndex = phase < 0.80
                        ? Math.round(100 + (phase / 0.80) * 100)   
                        : Math.round(300 + (phase - 0.80) * 200);  
                }


                drSlides.forEach(function(s, i) {
                    s.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;transform-style:preserve-3d;backface-visibility:hidden;will-change:transform,opacity';
                    drPaint(s, (i / drTotal) % 1);
                });


                var drCycle = Math.max(3000, interval * drTotal);
                var drStart = performance.now();
                var drPaused = false;
                var drPausedAt = 0;
                var drAnimId = null;

                function drFrame(ts) {
                    if (!drPaused) {
                        var global = ((ts - drStart) / drCycle) % 1;
                        for (var i = 0; i < drTotal; i++) {
                            drPaint(drSlides[i], (global + (i / drTotal)) % 1);
                        }
                    }
                    drAnimId = requestAnimationFrame(drFrame);
                }
                drAnimId = requestAnimationFrame(drFrame);

                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() {
                        drPaused = true; drPausedAt = performance.now();
                    });
                    carousel.addEventListener('mouseleave', function() {
                        if (drPaused) { drStart += (performance.now() - drPausedAt); drPaused = false; }
                    });
                }

                carousel._destroyCarousel = function() {
                    if (drAnimId) cancelAnimationFrame(drAnimId);
                };

            } else if (mode === 'card_flip' || mode === 'pixel_decode') {
                
                var allSlides = slides.querySelectorAll('.impulse-carousel-slide');
                var total = allSlides.length;
                if (total < 2) return;

                
                slides.style.position = 'relative';
                slides.style.overflow = 'visible';
                slides.style.display = 'block';
                slides.style.height = '100%';

                

                if (mode === 'card_flip') {
                    slides.style.perspective = '1500px';
                    slides.style.transformStyle = 'preserve-3d';
                    var flipTrack = slides.parentElement;
                    if (flipTrack) flipTrack.style.overflow = 'visible';
                }
                var _flipBackface = (mode === 'card_flip') ? 'backface-visibility:hidden;-webkit-backface-visibility:hidden;' : '';
                allSlides.forEach(function(s, i) {
                    s.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;opacity:' + (i === 0 ? '1' : '0') + ';z-index:' + (i === 0 ? '2' : '0') + ';transition:none;transform:none;' + _flipBackface;
                });

                var currentIndex = 0;
                var isAnimating = false;
                var autoplayTimer = null;
                var isPaused = false;
                var TRANS_MS = Math.max(900, Math.min(interval * 0.6, 2000));
                var effectFn = ImpulseCarouselEffects[mode];

                function showSlide(index) {
                    if (isAnimating || !effectFn) return;
                    isAnimating = true;
                    var prev = currentIndex;
                    currentIndex = index;
                    var outEl = allSlides[prev];
                    var inEl  = allSlides[index];
                    allSlides.forEach(function(s, i) {
                        if (i !== prev && i !== index) {
                            s.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;opacity:0;z-index:0;transition:none;transform:none';
                        }
                    });

                    

                    
                    var _doneFired = false;
                    var _safety = setTimeout(function(){
                        if (_doneFired) return;
                        _doneFired = true;
                        inEl.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;opacity:1;z-index:2;transition:none;transform:none';
                        outEl.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;opacity:0;z-index:0;transition:none;transform:none';
                        isAnimating = false;
                    }, TRANS_MS + 800);
                    try {
                        effectFn(slides, outEl, inEl, TRANS_MS, function() {
                            if (_doneFired) return;
                            _doneFired = true;
                            clearTimeout(_safety);
                            outEl.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;opacity:0;z-index:0;transition:none;transform:none';
                            inEl.style.cssText  = 'position:absolute;inset:0;width:100%;height:100%;opacity:1;z-index:2;transition:none;transform:none';
                            isAnimating = false;
                        });
                    } catch (_e) {
                        
                    }
                }

                if (autoplay) {
                    setTimeout(function(){ if (!isPaused && !isAnimating) showSlide((currentIndex + 1) % total); }, 300);
                    autoplayTimer = setInterval(function() {
                        if (!isPaused && !isAnimating) showSlide((currentIndex + 1) % total);
                    }, interval);
                }
                if (pauseOnHover) {
                    carousel.addEventListener('mouseenter', function() { isPaused = true; });
                    carousel.addEventListener('mouseleave', function() { isPaused = false; });
                }
                carousel._destroyCarousel = function() { if (autoplayTimer) clearInterval(autoplayTimer); };
            }
        });
    }
    


    
    
    function attachCarouselDrag(track, onRelease, onDragMove, onDragStart) {
        var dragging = false, startX = 0, startY = 0, currentX = 0, didDrag = false, rafId = null;
        var dirLocked = null; 
        function getX(e) { return e.touches ? e.touches[0].clientX : e.clientX; }
        function getY(e) { return e.touches ? e.touches[0].clientY : e.clientY; }
        function onDown(e) {
            if (e.button !== undefined && e.button !== 0) return;
            dragging = true; didDrag = false; dirLocked = null;
            startX = currentX = getX(e);
            startY = getY(e);
            track.style.cursor = 'grabbing';
            track.style.userSelect = 'none';
            if (onDragStart) onDragStart();
            
            if (!e.touches) e.preventDefault();
        }
        function onMove(e) {
            if (!dragging) return;
            currentX = getX(e);
            var dx = Math.abs(currentX - startX);
            var dy = Math.abs(getY(e) - startY);

            
            if (!dirLocked) {
                if (dx > dy && dx > 6) { dirLocked = 'h'; }
                else if (dy > dx && dy > 6) { dirLocked = 'v'; dragging = false; return; }
                else { return; } 
            }
            if (dirLocked !== 'h') return;

            e.preventDefault(); 
            var delta = currentX - startX;
            if (Math.abs(delta) > 3) didDrag = true;
            if (didDrag && onDragMove) {
                if (rafId) cancelAnimationFrame(rafId);
                var d = delta;
                rafId = requestAnimationFrame(function() { onDragMove(d); rafId = null; });
            }
        }
        function onUp() {
            if (!dragging) return;
            dragging = false;
            track.style.cursor = 'grab';
            track.style.userSelect = '';
            if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
            var delta = currentX - startX;
            onRelease(delta, didDrag);
            if (didDrag) {
                var blocker = function(ev) {
                    ev.stopPropagation(); ev.preventDefault();
                    track.removeEventListener('click', blocker, true);
                };
                track.addEventListener('click', blocker, true);
            }
        }
        track.style.cursor = 'grab';
        track.addEventListener('mousedown', onDown, { passive: false });
        document.addEventListener('mousemove', onMove, { passive: false });
        document.addEventListener('mouseup', onUp);
        track.addEventListener('touchstart', onDown, { passive: true }); 
        document.addEventListener('touchmove', onMove, { passive: false });
        document.addEventListener('touchend', onUp);
    }

    
    function initNewSliders() {
        document.querySelectorAll('.impulse-new-slider').forEach(function(carousel) {

            if (carousel.classList.contains('impulse-image-carousel')) return;
            
            if (carousel._sliderInit) return;
            carousel._sliderInit = true;

            
            if (carousel._sliderTimer) { clearInterval(carousel._sliderTimer); carousel._sliderTimer = null; }
            
            var slides = carousel.querySelector('.impulse-carousel-slides');
            var slideItems = carousel.querySelectorAll('.impulse-carousel-slide');
            
            if (!slides || slideItems.length === 0) return;
            
            var currentSlide = parseInt(carousel.dataset.currentSlide) || 0;
            if (currentSlide >= slideItems.length) currentSlide = 0;
            
            var direction = carousel.dataset.direction || 'right';
            var transitionSpeed = parseInt(carousel.dataset.transition) || 400;
            var isVertical = (direction === 'up' || direction === 'down');
            var effect = carousel.dataset.effect || 'slide';
            var isEffectMode = (effect !== 'slide') && ImpulseCarouselEffects[effect];
            
            var isEditorPreview = window.impulseIsPreview || false;

            
            var autoplay = carousel.dataset.autoplay === 'true';
            var speed = parseInt(carousel.dataset.speed) || 5000;
            var currentIndex = currentSlide;
            var isAnimating = false;

            var isAutoHeight = carousel.dataset.heightMode === 'auto';

            function syncTrackHeight(index) {
                if (!isAutoHeight) return;
                var track = carousel.querySelector('.impulse-carousel-track');
                if (!track) return;
                var targetSlide = slideItems[index];
                if (!targetSlide) return;
                
                var prevVis = targetSlide.style.visibility;
                var prevPos = targetSlide.style.position;
                
                var h = targetSlide.scrollHeight;
                if (h > 0) track.style.height = h + 'px';
            }

            function goToSlide(index, instant) {
                if (index < 0) index = slideItems.length - 1;
                if (index >= slideItems.length) index = 0;

                if (isEffectMode) {
                    if (isAnimating) return;
                    if (index === currentIndex) return;
                    isAnimating = true;
                    var prev = currentIndex;
                    currentIndex = index;
                    carousel.dataset.currentSlide = index;
                    var outEl = slideItems[prev];
                    var inEl  = slideItems[index];
                    
                    Array.prototype.forEach.call(slideItems, function(s, i) {
                        if (i !== prev && i !== index) {
                            s.style.transition = 'none'; s.style.opacity = '0';
                            s.style.transform = ''; s.style.zIndex = '0';
                        }
                    });
                    var dur = Math.max(600, transitionSpeed);
                    syncTrackHeight(index);
                    var _fxDone = false;
                    var _finish = function() {
                        if (_fxDone) return; _fxDone = true;
                        outEl.style.transition = 'none'; outEl.style.opacity = '0'; outEl.style.zIndex = '0'; outEl.style.transform = 'none';
                        inEl.style.transition  = 'none'; inEl.style.opacity  = '1'; inEl.style.zIndex  = '2'; inEl.style.transform  = 'none';
                        isAnimating = false;
                    };

                    
                    var _fxSafety = setTimeout(_finish, dur + 800);
                    try {
                        ImpulseCarouselEffects[effect](slides, outEl, inEl, dur, function() {
                            clearTimeout(_fxSafety); _finish();
                        });
                    } catch (_e) { clearTimeout(_fxSafety); _finish(); }
                } else {
                    
                    var prevIndex = currentIndex;
                    currentIndex = index;
                    carousel.dataset.currentSlide = index;
                    var track = carousel.querySelector('.impulse-carousel-track');
                    var itemsVisible = parseInt(carousel.dataset.items) || 1;
                    var gapPx = parseInt(carousel.dataset.gap) || 0;
                    var slideEl = slideItems[0];
                    
                    var slideSize = isVertical
                        ? (slideEl ? slideEl.offsetHeight : track.offsetHeight)
                        : (slideEl ? (slideEl.offsetWidth + gapPx) : track.offsetWidth);
                    var offset = index * slideSize;
                    var isWrap = instant || (prevIndex === slideItems.length - 1 && index === 0) || (prevIndex === 0 && index === slideItems.length - 1);
                    if (isWrap) {
                        slides.style.transition = 'none';
                        slides.style.transform = isVertical ? 'translateY(-' + offset + 'px)' : 'translateX(-' + offset + 'px)';
                        slides.offsetHeight; 
                        slides.style.transition = 'transform ' + transitionSpeed + 'ms ease-in-out';
                    } else {
                        slides.style.transform = isVertical ? 'translateY(-' + offset + 'px)' : 'translateX(-' + offset + 'px)';
                    }
                    syncTrackHeight(index);
                }
            }
            
            
            if (!isEffectMode) {
                slides.style.transition = 'none';
                goToSlide(currentSlide, true);
                slides.offsetHeight;
                slides.style.transition = 'transform ' + transitionSpeed + 'ms ease-in-out';
            } else {

                
                Array.prototype.forEach.call(slideItems, function(s, i) {
                    s.style.transition = 'none';
                    s.style.opacity = (i === currentSlide) ? '1' : '0';
                    s.style.zIndex  = (i === currentSlide) ? '2' : '0';
                    s.style.transform = 'none';
                });
            }


            
            function ensureVisible() {
                if (!isEffectMode) return;
                var _any = false;
                for (var _v = 0; _v < slideItems.length; _v++) {
                    if (parseFloat(getComputedStyle(slideItems[_v]).opacity) > 0.05) { _any = true; break; }
                }
                if (_any) return;

                
                isAnimating = false;
                var _idx = (currentIndex >= 0 && currentIndex < slideItems.length) ? currentIndex : 0;
                for (var _k = 0; _k < slideItems.length; _k++) {
                    slideItems[_k].style.transition = 'none';
                    slideItems[_k].style.opacity = (_k === _idx) ? '1' : '0';
                    slideItems[_k].style.zIndex  = (_k === _idx) ? '2' : '0';
                    slideItems[_k].style.transform = 'none';
                }
            }
            setTimeout(ensureVisible, 160);

            
            if (!isEffectMode) {
                var _resizeTimer = null;
                window.addEventListener('resize', function() {
                    clearTimeout(_resizeTimer);
                    _resizeTimer = setTimeout(function() {
                        slides.style.transition = 'none';
                        goToSlide(currentIndex, true);
                        slides.offsetHeight;
                        slides.style.transition = 'transform ' + transitionSpeed + 'ms ease-in-out';
                    }, 60);
                });
            }
            
            
            var autoDir = (direction === 'left' || direction === 'up') ? -1 : 1;
            if (autoplay) {
                carousel._sliderTimer = setInterval(function() {
                    ensureVisible();
                    if (!isAnimating) goToSlide(currentIndex + autoDir);
                }, speed);
            }
            
            function restartAutoplay() {
                if (carousel._sliderTimer) { clearInterval(carousel._sliderTimer); carousel._sliderTimer = null; }
                if (autoplay) {
                    carousel._sliderTimer = setInterval(function() {
                        if (!isAnimating) goToSlide(currentIndex + autoDir);
                    }, speed);
                }
            }

            
            (function() {
                var sliderTrack = carousel.querySelector('.impulse-carousel-slides');
                if (!sliderTrack) return;
                attachCarouselDrag(sliderTrack,
                    function(delta) {
                        if (Math.abs(delta) >= 50) { goToSlide(currentIndex + (delta < 0 ? 1 : -1)); restartAutoplay(); }
                    }
                );
            })();
            

            
            carousel.addEventListener('click', function(e) {
                if (e.target.closest('a,button,input,textarea,select,label')) return;
                goToSlide(currentIndex + 1);
                restartAutoplay();
            });

            
            carousel._goToSlide = goToSlide;
        });
    }


    
    
    window.impulseInitCarousels = initCarousels;
    window.impulseInitNewSliders = initNewSliders;

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() { initCarousels(); initNewSliders(); });
    } else {
        initCarousels(); initNewSliders();
    }


    
    
    if (typeof IntersectionObserver !== 'undefined') {
        var _carIO = new IntersectionObserver(function(entries) {
            entries.forEach(function(e) {
                if (e.isIntersecting && typeof e.target._relayout === 'function') e.target._relayout();
            });
        }, { threshold: 0.2 });
        window.impulseObserveCarousels = function() {
            document.querySelectorAll('.impulse-image-carousel').forEach(function(c) {
                if (!c._carObserved) { c._carObserved = 1; _carIO.observe(c); }
            });
        };
        window.impulseObserveCarousels();
    }
})();
