
(function() {
    'use strict';
    var screens = [], current = 0, transitioning = false, cooldownTimer = null, wrapperEl = null;
    var activeCloudEffect = 'none';
    var helixRot = 0;
    var _activeEnvCanvas = null; 

    

    

    

    var INSTINCTOR_ENV_WM = false;
    var _envWmCanvas = null, _envWmResizeBound = false;
    function _envWmDrawPattern(cx, w, h) {
        cx.clearRect(0, 0, w, h);
        var unit = Math.min(w, h);
        var fs   = Math.max(14, Math.round(unit * 0.045));
        var main = 'Instinctor', sub = 'Upgrade to remove';
        var mainFont = '700 ' + fs + 'px system-ui, -apple-system, "Segoe UI", Arial, sans-serif';
        var subFont  = '600 ' + Math.round(fs * 0.46) + 'px system-ui, -apple-system, "Segoe UI", Arial, sans-serif';
        cx.save();
        cx.translate(w / 2, h / 2);
        cx.rotate(-28 * Math.PI / 180);
        cx.textAlign = 'center'; cx.textBaseline = 'middle';

        
        
        cx.lineJoin = 'round';
        cx.shadowBlur = 0;
        var diag = Math.sqrt(w * w + h * h);
        cx.font = mainFont;

        var stepY = fs * 7.4, stepX = cx.measureText(main).width + fs * 6.5;
        var rows = Math.ceil(diag / stepY) + 1, cols = Math.ceil(diag / stepX) + 1;
        for (var r = -rows; r <= rows; r++) {
            var offX = (r % 2 === 0) ? 0 : stepX / 2, y = r * stepY;
            for (var c = -cols; c <= cols; c++) {
                var x = c * stepX + offX;
                cx.font = mainFont;
                cx.lineWidth = Math.max(1.5, fs * 0.045); cx.strokeStyle = 'rgba(0,0,0,0.22)';
                cx.strokeText(main, x, y - fs * 0.5);
                cx.fillStyle = 'rgba(255,255,255,0.30)';
                cx.fillText(main, x, y - fs * 0.5);
                cx.font = subFont;
                cx.lineWidth = Math.max(1, fs * 0.03); cx.strokeStyle = 'rgba(0,0,0,0.22)';
                cx.strokeText(sub, x, y + fs * 0.42);
                cx.fillStyle = 'rgba(255,255,255,0.20)';
                cx.fillText(sub, x, y + fs * 0.42);
            }
        }
        cx.restore();
    }
    function _drawEnvWatermark() {
        if (!_envWmCanvas) return;
        var dpr = Math.min(window.devicePixelRatio || 1, 2);
        var w = Math.floor(window.innerWidth * dpr), h = Math.floor(window.innerHeight * dpr);
        if (!w || !h) return;
        _envWmCanvas.width = w; _envWmCanvas.height = h;
        var cx = _envWmCanvas.getContext('2d');
        if (cx) _envWmDrawPattern(cx, w, h);
    }
    function _ensureEnvWatermark() {
        if (!INSTINCTOR_ENV_WM) return;

        
        
        var cloud = (config && config.cloudEffect) || 'none';
        if (!cloud || cloud === 'none') {
            if (_envWmCanvas && _envWmCanvas.parentNode) _envWmCanvas.parentNode.removeChild(_envWmCanvas);
            return;
        }
        if (!_envWmCanvas) {
            _envWmCanvas = document.createElement('canvas');
            _envWmCanvas.id = 'impulse-env-watermark';
            _envWmCanvas.setAttribute('aria-hidden', 'true');
        }

        
        
        var wrapZ = wrapperEl
            ? parseInt((window.getComputedStyle ? getComputedStyle(wrapperEl).zIndex : wrapperEl.style.zIndex) || '0', 10)
            : 0;
        if (isNaN(wrapZ)) wrapZ = 0;
        var z = Math.max(wrapZ, 2) + 1;
        _envWmCanvas.style.cssText = 'position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:' + z + ';pointer-events:none;';
        if (_envWmCanvas.parentNode !== document.body) document.body.appendChild(_envWmCanvas);
        _drawEnvWatermark();
        if (!_envWmResizeBound) {
            window.addEventListener('resize', _drawEnvWatermark, { passive: true });
            _envWmResizeBound = true;
        }
    }
    var _userTapped = false; 
    var config = { transition:'z_depth', cooldown:80, duration:480, intensity:50, navDots:false, infinite:false, easing:'cubic-bezier(0.4, 0, 0.2, 1)' };

    

    
    var _isReleased = false;
    var _hasPageModeBelow = false;
    var _scrollReentryBound = false;

    var presets = {

        

        

        
        
        scroll: { enter:{transform:'translateY(100%)',  opacity:'1'},
                  exit: {transform:'translateY(-100%)', opacity:'1'} },
        glide:  { enter:{transform:'translateY(48px)',  opacity:'0'},
                  exit: {transform:'translateY(-48px)', opacity:'0'} },

        fade:   { enter:{transform:'scale(1)', opacity:'0'},
                  exit: {transform:'scale(1)', opacity:'0'} },
        
    };

    
    presets.lift = presets.scroll;

    
    function _zoneReveal(el){
        if(el && el.dataset && el.dataset.reveal){
            var _pin=parseInt(el.dataset.revealIntensity);
            return {t:el.dataset.reveal, inten:isNaN(_pin)?config.intensity:_pin};
        }
        var t=config.transition, inten=config.intensity;
        if(wrapperEl){
            t=wrapperEl.dataset.transition||t;
            var _bi=parseInt(wrapperEl.dataset.intensity); if(!isNaN(_bi))inten=_bi;
        }
        return {t:t,inten:inten};
    }
    function getPreset(el, dir) {

        var zr=_zoneReveal(el);
        var p = presets[zr.t];
        if (zr.t==='z_depth' || !p) {
            var t=Math.max(0,Math.min(100,zr.inten))/100; var s=0.30+t*0.65; var b=(10+t*30).toFixed(1);
            return { enter:{transform:'perspective(700px) scale('+(1-s).toFixed(3)+')',blur:b+'px',opacity:'0'}, exit:{transform:'perspective(700px) scale('+(1+s*0.5).toFixed(3)+')',blur:b+'px',opacity:'0'} };
        }
        return p;
    }
    function getDuration(){return config.duration;}
    function transStr(p){var d=getDuration()+'ms';var e=(p&&p.easing)||config.easing;var t='transform '+d+' '+e+', opacity '+d+' '+e;if(p&&p.clip)t+=', clip-path '+d+' '+e;return t;}
    function clearStyles(el){el.style.clipPath='';el.style.transformOrigin='';var svg=el.querySelector('.impulse-dissolve-svg');if(svg)svg.remove();el.style.filter=el.style.filter.replace(/url\(#impulse-dissolve[^)]*\)\s*/g,'').trim()||'';}

    

    
    
    var _apTimer = null;
    var _apRemaining = 0;
    var _apStartedAt = 0;
    function _isEditorIframe() {
        try { return window.parent !== window; } catch (e) { return false; }
    }
    function _scheduleAutoplay(el) {
        _cancelAutoplay();
        
        var raw = el && el.getAttribute && el.getAttribute('data-autoplay-seconds');
        var secs = parseFloat(raw);
        if (!isFinite(secs) || secs <= 0) return;
        _apRemaining = Math.round(secs * 1000);
        _apStartedAt = Date.now();
        _apTimer = setTimeout(function() { _apTimer = null; if (typeof next === 'function') next(); }, _apRemaining);
    }
    function _cancelAutoplay() {
        if (_apTimer) { clearTimeout(_apTimer); _apTimer = null; }
        _apRemaining = 0;
    }
    
    if (typeof document !== 'undefined' && !document._impulseAPVisibilityWired) {
        document._impulseAPVisibilityWired = true;
        document.addEventListener('visibilitychange', function() {
            if (document.visibilityState === 'hidden' && _apTimer) {
                clearTimeout(_apTimer);
                _apTimer = null;
                _apRemaining = Math.max(0, _apRemaining - (Date.now() - _apStartedAt));
            } else if (document.visibilityState === 'visible' && _apRemaining > 0 && !_apTimer) {
                _apStartedAt = Date.now();
                _apTimer = setTimeout(function() { _apTimer = null; if (typeof next === 'function') next(); }, _apRemaining);
            }
        });
    }

    function _toggleFrostBf(f,on){if(on){if(f.hasAttribute('data-frost-bf')){var v=f.getAttribute('data-frost-bf');if(v){f.style.setProperty('backdrop-filter',v,'important');f.style.setProperty('-webkit-backdrop-filter',v,'important');}else{f.style.removeProperty('backdrop-filter');f.style.removeProperty('-webkit-backdrop-filter');}f.removeAttribute('data-frost-bf');}}else{if(!f.hasAttribute('data-frost-bf'))f.setAttribute('data-frost-bf',f.style.getPropertyValue('backdrop-filter')||f.style.getPropertyValue('-webkit-backdrop-filter')||'');f.style.setProperty('backdrop-filter','none','important');f.style.setProperty('-webkit-backdrop-filter','none','important');}}
    function setScreenFrost(el,on){try{if(!el||!el.querySelectorAll)return;var l=el.querySelectorAll('[style*="backdrop-filter"]');for(var i=0;i<l.length;i++)_toggleFrostBf(l[i],on);if(el.matches&&el.matches('[style*="backdrop-filter"]'))_toggleFrostBf(el,on);}catch(_e){}}
    function applyEnterState(el){setScreenFrost(el,false);var p=getPreset(el);el.style.transition='none';el.style.zIndex=0;el.style.setProperty('visibility','hidden','important');el.style.setProperty('pointer-events','none','important');clearStyles(el);cleanupDecomposition(el);
        if(p.clip){el.style.opacity='1';el.style.transform='scale(1)';el.style.clipPath=p.enter.clip;}
        else if(!p.complex){el.style.opacity=p.enter.opacity;el.style.transform=p.enter.transform;}
        else{el.style.opacity='1';el.style.transform='scale(1)';} el.classList.remove('impulse-screen-active');el.classList.remove('impulse-screen-entering');
        
        if(window.impulseOnScreenBlur)try{window.impulseOnScreenBlur(el);}catch(_e){}}
    function applyExitState(el){setScreenFrost(el,false);var p=getPreset(el);el.style.transition='none';el.style.zIndex=0;el.style.setProperty('visibility','hidden','important');el.style.setProperty('pointer-events','none','important');clearStyles(el);cleanupDecomposition(el);if(window.impulseAnimatorReset)window.impulseAnimatorReset(el);
        if(p.clip){el.style.opacity=p.exit.opacity;el.style.transform=p.exit.transform;}
        else if(!p.complex){el.style.opacity=p.exit.opacity;el.style.transform=p.exit.transform;}
        else{el.style.opacity='0';el.style.transform='scale(1)';} el.classList.remove('impulse-screen-active');el.classList.remove('impulse-screen-entering');
        _cancelAutoplay();
        if(window.impulseOnScreenBlur)try{window.impulseOnScreenBlur(el);}catch(_e){}}
    function applyFocusState(el){setScreenFrost(el,true);el.style.transition='none';el.style.zIndex=2;el.style.opacity='1';el.style.transform='';el.style.filter='';el.style.setProperty('visibility','visible','important');el.style.setProperty('pointer-events','auto','important');clearStyles(el);cleanupDecomposition(el);resetLeakyLayers(el);
el.querySelectorAll('.impulse-la-asset').forEach(function(a){a.style.opacity='0';a._laSettled=false;});
el.classList.remove('impulse-screen-entering');el.classList.add('impulse-screen-active');

_scheduleAutoplay(el);
if(window.impulseOnScreenFocus)window.impulseOnScreenFocus(el);setTimeout(function(){el.querySelectorAll('.impulse-new-slider').forEach(function(s){s._sliderInit=['bw_matrix','bw_grid3d','bw_blueprint','bw_marble','bw_diamonds'].indexOf(activeCloudEffect) !== -1;});if(window.ImpulseSliderInit)window.ImpulseSliderInit();else if(typeof initNewSliders==='function')initNewSliders();},50);}
    function makeOverlay(css){var ov=document.createElement('div');ov.style.cssText='position:fixed;top:0;left:0;width:100vw;height:100dvh;z-index:4;pointer-events:none;overflow:hidden'+(css||'');return ov;}
    function prepNewScreen(el){setScreenFrost(el,true);el.style.transition='none';el.style.visibility='visible';el.style.zIndex=1;el.style.opacity='1';el.style.transform='scale(1)';el.style.filter='';clearStyles(el);}

    var _decompCache = new WeakMap();
    var DECOMPOSE_SUBS = {
        'checkout': '.impulse-checkout-block > div > div:first-child, .impulse-checkout-field, .impulse-checkout-block input[placeholder], .impulse-checkout-btn',
        'contact': '.impulse-contact-form > *:not(input[type="hidden"]):not(.impulse-form-message), .impulse-form > *:not(input[type="hidden"])',
        'login': '.impulse-login-form > *:not(input[type="hidden"]):not(.impulse-form-message)',
        'register': '.impulse-register-form > *:not(input[type="hidden"]):not(.impulse-form-message)',

        'estimate': '.impulse-estimate-block .ime-head, .impulse-estimate-block .ime-sub, .impulse-estimate-block .ime-form > *:not(input[type="hidden"]):not(.ime-msg):not(.ime-vin-msg)',
        'grid': '.impulse-grid-cell',
        'rows': '.impulse-rows-cell',
        'columns': '.impulse-layout-col',
        'products': '.impulse-pcard, .impulse-flip-card',
        'bundle': '.impulse-bundle-item',
        'plans': '.impulse-pricing-card',
        'reviews': '.impulse-reviews-card',
        'price_list': '.impulse-price-item',
        'unfold': '.impulse-acc-spot-item, .impulse-unfold-card, .impulse-acc-tile, .impulse-acc-reveal-item',
        'table': '.impulse-table-item',
        'social': '.impulse-social-icons > a',
        'carousel': '.impulse-carousel-slide',
        'slider': '.impulse-carousel-slide',
        'network': '.impulse-network-card',
        
        'team': '.impulse-team-card',
        'schedule': '.isch-dayhdr, .isch-card',

        
        
        'text': '.impulse-text-col',
        
        'kinetic': '.kp-disc, .kp-line'
    };
    
    var DECOMPOSE_CLASS_DETECT = [
        ['impulse-contact-form', 'contact'],
        ['impulse-login-form', 'login'],
        ['impulse-register-form', 'register'],
        ['impulse-estimate-block', 'estimate'],
        ['impulse-checkout-block', 'checkout'],
        ['impulse-grid-cell', 'grid'],
        ['impulse-rows-cell', 'rows'],
        ['impulse-layout-grid', 'columns'],
        ['impulse-product-grid', 'products'],
        ['impulse-product-bundle', 'bundle'],
        ['impulse-pricing-card', 'plans'],
        ['impulse-reviews-card', 'reviews'],
        ['impulse-price-item', 'price_list'],
        ['impulse-acc-spot-item', 'unfold'],
        ['impulse-unfold-card', 'unfold'],
        ['impulse-acc-tile', 'unfold'],
        ['impulse-acc-reveal-item', 'unfold'],
        ['impulse-table-item', 'table'],
        ['impulse-social-icons', 'social'],
        ['impulse-carousel-slide', 'slider'],
        ['impulse-network-card', 'network'],
        ['impulse-team-block', 'team'],
        ['impulse-schedule-block', 'schedule'],

        ['impulse-text-cols', 'text'],
        ['impulse-kinetic-block', 'kinetic']
    ];

    function getDecompChildren(screenEl) {
        if (!screenEl) return [];
        if (_decompCache.has(screenEl)) return _decompCache.get(screenEl);
        
        if (screenEl.dataset && screenEl.dataset.noDecomp === '1') {
            _decompCache.set(screenEl, []); return [];
        }
        if (screenEl.querySelector('[data-no-decomp="1"]')) {
            _decompCache.set(screenEl, []); return [];
        }
        if (screenEl.querySelector('.impulse-builder-demo')) {
            _decompCache.set(screenEl, []); return [];
        }
        var container = screenEl.querySelector('.impulse-container');
        if (!container) { _decompCache.set(screenEl, []); return []; }
        
        var topBlocks = Array.from(container.querySelectorAll(':scope > .impulse-el'));
        
        if (!topBlocks.length) {
            topBlocks = Array.from(container.children).filter(function(c) {
                var tag = c.tagName;
                return tag !== 'STYLE' && tag !== 'SCRIPT' && tag !== 'LINK';
            });
        }
        var children = [];
        for (var b = 0; b < topBlocks.length; b++) {

            
            if (topBlocks[b].dataset && topBlocks[b].dataset.revealOff === '1') continue;
            
            var type = topBlocks[b].getAttribute('data-type');
            if (!type) {
                for (var _di = 0; _di < DECOMPOSE_CLASS_DETECT.length; _di++) {
                    if (topBlocks[b].querySelector('.' + DECOMPOSE_CLASS_DETECT[_di][0]) || topBlocks[b].classList.contains(DECOMPOSE_CLASS_DETECT[_di][0])) {
                        type = DECOMPOSE_CLASS_DETECT[_di][1];
                        break;
                    }
                }
            }
            var subSel = type ? DECOMPOSE_SUBS[type] : null;
            if (subSel) {
                var subs = Array.from(topBlocks[b].querySelectorAll(subSel));
                if (subs.length > 1) {
                    for (var s = 0; s < subs.length; s++) children.push(subs[s]);
                    continue;
                }
            }
            children.push(topBlocks[b]);
        }
        
        var deduped = [];
        for (var c = 0; c < children.length; c++) {
            var nested = false;
            var p = children[c].parentElement;
            while (p) {
                if (children.indexOf(p) !== -1) { nested = true; break; }
                p = p.parentElement;
            }
            if (!nested) deduped.push(children[c]);
        }
        _decompCache.set(screenEl, deduped);
        return deduped;
    }

    function decomposeEnter(screenEl) {
        var children = getDecompChildren(screenEl);
        if (!children.length) return;

        

        
        
        var effect = (typeof _zoneReveal === 'function')
            ? (_zoneReveal(screenEl).t || config.transition)
            : config.transition;
        var dur = getDuration() * 2.0;
        var stag = 0.15, act = 0.85, n = children.length, start = null;
        var alt = function(i) { return i % 2 === 0 ? 1 : -1; };

        

        
        
        for (var rvi = 0; rvi < n; rvi++) {
            var _rn = children[rvi], _rord = null, _rdly = 0;
            while (_rn && _rn.dataset) {
                if (_rord === null && _rn.dataset.revealOrder != null && _rn.dataset.revealOrder !== '') _rord = parseFloat(_rn.dataset.revealOrder);
                if (!_rdly && _rn.dataset.revealDelay) _rdly = parseFloat(_rn.dataset.revealDelay) || 0;
                if (_rn === screenEl) break;
                _rn = _rn.parentElement;
            }
            children[rvi]._revStagT = (_rord !== null && !isNaN(_rord)) ? Math.max(0, Math.min(1, _rord / 10)) : null;
            children[rvi]._revDelayFrac = (_rdly && dur) ? (_rdly / (dur * 0.65)) : 0;
        }

        

        

        
        
        function _decompFlat(ch) {
            if (!ch) return false;
            var h = ch.querySelector('.impulse-display-text[data-dt-mode]');
            if (h && h.getAttribute('data-dt-mode') === 'outline_depth') return true;
            if (ch.matches && ch.matches('.impulse-display-text[data-dt-mode="outline_depth"]')) return true;
            if (ch.querySelector('.impulse-logo-animator')) return true;
            if (ch.classList && ch.classList.contains('impulse-logo-animator')) return true;

            
            if (ch.querySelector && ch.querySelector('section.impulse-frosted')) return true;
            if (ch.matches && ch.matches('section.impulse-frosted')) return true;
            return false;
        }
        var _flat = children.map(_decompFlat);

        
        var _bases = children.map(function(c){ var b = c.getAttribute('data-decomp-base'); return b ? b + ' ' : ''; });
        var container = screenEl.querySelector('.impulse-container') || screenEl;
        container.style.perspective = '500px';
        container.style.perspectiveOrigin = '50% 50%';
        container.style.transformStyle = 'preserve-3d';

        

        

        
        var _overflowRestore = [];
        var _ancestorRestore = [];
        var walker = container.parentElement;
        while (walker && walker !== screenEl.parentElement) {
            var cs = getComputedStyle(walker);
            if (cs.overflow === 'hidden' || cs.overflowX === 'hidden' || cs.overflowY === 'hidden') {
                _overflowRestore.push({ el: walker, val: walker.style.overflow });
                walker.style.overflow = 'visible';
            }
            _ancestorRestore.push({ el: walker, prev: walker.style.transformStyle });
            walker.style.transformStyle = 'preserve-3d';
            walker = walker.parentElement;
        }
        function initState(i, t) {
            switch (effect) {
                case 'depth_spring':
                    return { tx: alt(i) * 15, ty: 10 * t, tz: -2000 - 800 * t, rx: 5 + 3 * t, ry: alt(i) * 4 };
                case 'depth_vortex':
                    return { tx: alt(i) * 30, ty: alt(i) * 20, tz: -2500 - 1000 * t, rx: alt(i) * 8, ry: alt(i) * (12 + 6 * t) };
                case 'depth_zoom':
                    dur = getDuration() * 1.8; stag = 0.15; act = 0.85;
                    return { tx: alt(i) * 10, ty: 5 * t, tz: -3000 - 500 * t, rx: 3 * t, ry: alt(i) * 2 };
                case 'rise':
                    dur = getDuration() * 2.0; stag = 0.15; act = 0.85;
                    return { tx: alt(i) * 15, ty: 30 + 15 * t, tz: -2000 - 600 * t, rx: 6 + 3 * t, ry: alt(i) * 3 };
                case 'fall':
                    dur = getDuration() * 2.0; stag = 0.15; act = 0.85;
                    return { tx: alt(i) * 15, ty: -(30 + 15 * t), tz: -2000 - 600 * t, rx: -(6 + 3 * t), ry: alt(i) * 3 };
                case 'iris':
                    dur = getDuration() * 1.6;
                    return { tx: alt(i) * 8, ty: alt(i) * 5, tz: -2800 - 800 * t, rx: alt(i) * (4 + 2 * t), ry: alt(i) * (4 + 2 * t) };
                case 'split':
                    dur = getDuration() * 1.6;
                    return { tx: alt(i) * (40 + 20 * t), ty: alt(i) * 8, tz: -2000 - 600 * t, rx: alt(i) * 3, ry: alt(i) * (8 + 4 * t) };
                case 'dissolve':
                    dur = getDuration() * 2.0;
                    var jx = Math.sin(i * 2.7 + 0.5) * 25, jy = Math.cos(i * 3.1 + 0.3) * 18;
                    return { tx: jx, ty: jy, tz: -2200 - 1200 * Math.random(), rx: alt(i) * (5 + 4 * Math.random()), ry: alt(i) * (5 + 4 * Math.random()) };
                case 'morph':

                    dur = getDuration() * 2.2;
                    return { tx: alt(i) * (8 + 4 * t), ty: alt(i) * (6 + 3 * t), tz: -1800 - 400 * t, rx: alt(i) * 2, ry: alt(i) * (20 + 10 * t) };
                case 'door':

                    dur = getDuration() * 1.9;
                    return { tx: alt(i) * (60 + 30 * t), ty: 0, tz: -1500 - 500 * t, rx: 0, ry: alt(i) * (45 + 15 * t) };
                case 'focus':

                    
                    dur = getDuration() * 1.7;
                    return { tx: alt(i) * (4 + 2 * t), ty: 6 + 3 * t, tz: -900 - 300 * t, rx: alt(i) * 1.5, ry: alt(i) * 1.5 };
                case 'swirl':
                    
                    dur = getDuration() * 2.0;
                    var ang = i * 1.2;
                    return { tx: Math.cos(ang) * (30 + 20 * t), ty: Math.sin(ang) * (30 + 20 * t), tz: -2400 - 900 * t, rx: alt(i) * (6 + 4 * t), ry: alt(i) * (15 + 8 * t) };
                default:
                    return { tx: alt(i) * (20 + 10 * t), ty: 15 + 8 * t, tz: -2200 - 900 * t, rx: 5 + 3 * t, ry: alt(i) * (4 + 2 * t) };
            }
        }

        

        

        

        

        
        function ease(cp) {
            if (cp >= 1) return 1;
            var sB = 1.35, c = cp - 1;       
            return 1 + c * c * ((sB + 1) * c + sB);
        }
        for (var i = 0; i < n; i++) {
            var t = n > 1 ? i / (n - 1) : 0;
            var s = initState(i, t);
            var anc = children[i].parentElement;
            while (anc && anc !== container) {
                anc.style.transformStyle = 'preserve-3d';
                anc.style.overflow = 'visible';
                anc = anc.parentElement;
            }
            children[i].style.transition = 'none';
            if (_flat[i]) {

                

                

                
                children[i].style.transformStyle = 'flat';
                children[i].style.transform = '';
                children[i].style.filter = '';
            } else {
                children[i].style.transformStyle = 'preserve-3d';
                children[i].style.transform = _bases[i] + 'translate3d(' + s.tx.toFixed(0) + 'px,' + s.ty.toFixed(0) + 'px,' + s.tz.toFixed(0) + 'px) rotateX(' + s.rx.toFixed(1) + 'deg) rotateY(' + s.ry.toFixed(1) + 'deg)';
                children[i].style.filter = 'blur(8px)';
            }
            children[i].style.opacity = '0';
            children[i].style.visibility = '';
            
            children[i].querySelectorAll('.impulse-la-asset').forEach(function(a){a.style.opacity='0';});

            
            
            var enterLeaky = getLeakyLayers(children[i]);
            for (var lk = 0; lk < enterLeaky.length; lk++) enterLeaky[lk].style.opacity = '0';
        }
        function frame(ts) {
            if (!start) start = ts;
            var p = Math.min((ts - start) / (dur * 0.65), 1); 
            for (var i = 0; i < n; i++) {
                var t = n > 1 ? i / (n - 1) : 0;
                var _tStag = (children[i]._revStagT != null) ? children[i]._revStagT : t;
                var childStart = stag * _tStag + (children[i]._revDelayFrac || 0);
                var cp = Math.max(0, Math.min(1, (p - childStart) / act));
                var ep = ease(cp);
                var s = initState(i, t);
                var tx = s.tx * (1 - ep);
                var ty = s.ty * (1 - ep);
                var tz = s.tz * (1 - ep);
                var rx = s.rx * (1 - ep);
                var ry = s.ry * (1 - ep);

                

                

                
                var alpha = Math.min(1, cp * 2.5);
                if (_flat[i]) {

                    children[i].style.transform = '';
                    children[i].style.filter = '';
                } else {
                    var blurAmt = 8 * (1 - Math.min(1, cp * 1.8));
                    children[i].style.transform = _bases[i] + 'translate3d(' + tx.toFixed(1) + 'px,' + ty.toFixed(1) + 'px,' + tz.toFixed(0) + 'px) rotateX(' + rx.toFixed(2) + 'deg) rotateY(' + ry.toFixed(2) + 'deg)';
                    children[i].style.filter = blurAmt > 0.3 ? 'blur(' + blurAmt.toFixed(1) + 'px)' : '';
                }
                children[i].style.opacity = alpha.toFixed(3);

                var innerLeaky = getLeakyLayers(children[i]);
                for (var il = 0; il < innerLeaky.length; il++) innerLeaky[il].style.opacity = alpha.toFixed(3);
            }
            if (p < 1) requestAnimationFrame(frame);
            else {
                for (var i = 0; i < n; i++) {
                    var anc = children[i].parentElement;
                    while (anc && anc !== container) {
                        anc.style.transformStyle = '';
                        anc.style.overflow = '';
                        anc = anc.parentElement;
                    }
                    children[i].style.transition = '';
                    children[i].style.transform = '';
                    children[i].style.opacity = '';
                    children[i].style.filter = '';
                    children[i].style.transformStyle = '';
                    
                    var endLeaky = getLeakyLayers(children[i]);
                    for (var el = 0; el < endLeaky.length; el++) endLeaky[el].style.opacity = '';
                }
                container.style.perspective = '';
                container.style.perspectiveOrigin = '';
                container.style.transformStyle = '';
                for (var ri = 0; ri < _overflowRestore.length; ri++) {
                    _overflowRestore[ri].el.style.overflow = _overflowRestore[ri].val || '';
                }

                for (var ai = 0; ai < _ancestorRestore.length; ai++) {
                    _ancestorRestore[ai].el.style.transformStyle = _ancestorRestore[ai].prev || '';
                }
            }
        }
        requestAnimationFrame(frame);
    }

    

    

    

    function getLeakyLayers(cardEl) {

        
        var out = [];
        var all = cardEl.querySelectorAll('[style*="translateZ"], [style*="translate3d"]');
        for (var i = 0; i < all.length; i++) out.push(all[i]);
        return out;
    }

    function decomposeExit(screenEl) {
        var children = getDecompChildren(screenEl);
        if (!children.length) return;
        var n = children.length;
        var dur = getDuration() * 0.9;
        var stag = 0.10, act = 0.90, start = null;
        var alt = function(i) { return i % 2 === 0 ? 1 : -1; };
        var leaks = []; 
        for (var i = 0; i < n; i++) {
            children[i].style.transition = 'none';
            leaks.push(getLeakyLayers(children[i]));
        }
        function frame(ts) {
            if (!start) start = ts;
            var p = Math.min((ts - start) / (dur * 0.65), 1); 
            for (var i = 0; i < n; i++) {
                var t = n > 1 ? i / (n - 1) : 0;
                var childStart = stag * (1 - t);
                var cp = Math.max(0, Math.min(1, (p - childStart) / act));
                var ep = cp < 0.5 ? 2 * cp * cp : 1 - Math.pow(-2 * cp + 2, 2) / 2;
                
                var tx = alt(i) * (50 + 35 * t) * ep;
                var ty = alt(i) * (25 + 18 * t) * ep;
                var rx = (4 + 3 * t) * ep;
                var ry = alt(i) * (6 + 4 * t) * ep;
                children[i].style.transform = 'translate(' + tx.toFixed(1) + 'px,' + ty.toFixed(1) + 'px) rotateX(' + rx.toFixed(2) + 'deg) rotateY(' + ry.toFixed(2) + 'deg)';
                var alpha = (1 - ep).toFixed(3);
                children[i].style.opacity = alpha;

                var ll = leaks[i];
                for (var k = 0; k < ll.length; k++) ll[k].style.opacity = alpha;
            }
            if (p < 1) requestAnimationFrame(frame);
            else {
                for (var i = 0; i < n; i++) {
                    children[i].style.transform = '';
                    children[i].style.filter = '';
                    children[i].style.opacity = '0';

                    

                    

                    
                    children[i].style.visibility = 'hidden';
                    var ll = leaks[i];
                    for (var k = 0; k < ll.length; k++) {
                        ll[k].style.opacity    = '0';
                        ll[k].style.visibility = 'hidden';
                    }
                }
            }
        }
        requestAnimationFrame(frame);
    }

    function cleanupDecomposition(screenEl) {
        var children = getDecompChildren(screenEl);
        for (var i = 0; i < children.length; i++) {
            children[i].style.transition = '';
            children[i].style.transform = '';
            children[i].style.opacity = '';
            children[i].style.filter = '';
            children[i].style.visibility = '';
        }

        

        
        
    }
    function resetLeakyLayers(screenEl) {
        var children = getDecompChildren(screenEl);
        for (var i = 0; i < children.length; i++) {
            var leaky = getLeakyLayers(children[i]);
            for (var k = 0; k < leaky.length; k++) {
                leaky[k].style.opacity    = '';
                leaky[k].style.visibility = '';
                leaky[k].style.display    = '';
            }
        }
    }

    function doDissolve(oldEl,newEl,forward,callback){var dur=getDuration();prepNewScreen(newEl);var uid='impulse-dissolve-'+Date.now();var svgNS='http://www.w3.org/2000/svg';
        var svg=document.createElementNS(svgNS,'svg');svg.setAttribute('class','impulse-dissolve-svg');svg.setAttribute('style','position:absolute;width:0;height:0;pointer-events:none');
        var defs=document.createElementNS(svgNS,'defs');var filter=document.createElementNS(svgNS,'filter');filter.setAttribute('id',uid);filter.setAttribute('x','-20%');filter.setAttribute('y','-20%');filter.setAttribute('width','140%');filter.setAttribute('height','140%');
        var turb=document.createElementNS(svgNS,'feTurbulence');turb.setAttribute('type','fractalNoise');turb.setAttribute('baseFrequency','0.015');turb.setAttribute('numOctaves','3');turb.setAttribute('seed',String(Math.floor(Math.random()*100)));turb.setAttribute('result','noise');
        var disp=document.createElementNS(svgNS,'feDisplacementMap');disp.setAttribute('in','SourceGraphic');disp.setAttribute('in2','noise');disp.setAttribute('scale','0');disp.setAttribute('xChannelSelector','R');disp.setAttribute('yChannelSelector','G');
        filter.appendChild(turb);filter.appendChild(disp);defs.appendChild(filter);svg.appendChild(defs);oldEl.appendChild(svg);oldEl.style.zIndex=3;oldEl.style.filter='url(#'+uid+')';
        var startTime=null,maxDisp=300;function animate(ts){if(!startTime)startTime=ts;var p=Math.min((ts-startTime)/dur,1);var ep=1-Math.pow(1-p,3);disp.setAttribute('scale',String(Math.floor(ep*maxDisp)));oldEl.style.opacity=String(Math.max(0,1-p*1.3));if(p<1)requestAnimationFrame(animate);else callback();}requestAnimationFrame(animate);}

    function doRise(oldEl, newEl, forward, callback) {
        var dur = getDuration() * 1.4;
        prepNewScreen(newEl);
        newEl.style.zIndex = 3; newEl.style.opacity = '0';
        newEl.style.transform = 'translateY(100vh)';
        _hardCutScreen(oldEl);
        var start = null;
        function frame(ts) {
            if (!start) start = ts;
            var t = Math.min((ts - start) / dur, 1);
            var sp = springDamp(t, 2.0, 5);
            var nY = 100 * (1 - sp); 
            var nAlpha = Math.min(1, sp * 2.5);
            newEl.style.transform = 'translateY(' + nY.toFixed(2) + 'vh)';
            newEl.style.opacity = nAlpha.toFixed(3);
            if (t < 1) requestAnimationFrame(frame);
            else { newEl.style.filter = ''; newEl.style.transform = ''; newEl.style.transformStyle = 'preserve-3d'; callback(); }
        }
        requestAnimationFrame(frame);
    }

    function doFall(oldEl, newEl, forward, callback) {
        var dur = getDuration() * 1.4;
        prepNewScreen(newEl);
        newEl.style.zIndex = 3; newEl.style.opacity = '0';
        newEl.style.transform = 'translateY(-100vh)';
        _hardCutScreen(oldEl);
        var start = null;
        function frame(ts) {
            if (!start) start = ts;
            var t = Math.min((ts - start) / dur, 1);
            var sp = springDamp(t, 1.8, 4.5);
            var nY = -100 * (1 - sp);
            var nAlpha = Math.min(1, sp * 2.5);
            newEl.style.transform = 'translateY(' + nY.toFixed(2) + 'vh)';
            newEl.style.opacity = nAlpha.toFixed(3);
            if (t < 1) requestAnimationFrame(frame);
            else { newEl.style.filter = ''; newEl.style.transform = ''; newEl.style.transformStyle = 'preserve-3d'; callback(); }
        }
        requestAnimationFrame(frame);
    }

    function springDamp(t, freq, decay) {
        
        if (t >= 1) return 1;
        var w = freq * Math.PI * 2; 
        return 1 - Math.exp(-decay * t) * Math.cos(w * t);
    }

    

    

    

    
    function _hardCutScreen(el) {
        if (!el) return;
        el.style.transition = 'none';
        el.style.zIndex = 0;
        el.style.opacity = '0';
        el.style.transform = '';
        el.style.filter = '';
        el.style.setProperty('visibility', 'hidden', 'important');
        var lk = getLeakyLayers(el);
        for (var i = 0; i < lk.length; i++) lk[i].style.display = 'none';
    }

    function doDepthSpring(oldEl, newEl, forward, callback) {
        var dur = getDuration() * 1.6; 
        prepNewScreen(newEl);
        newEl.style.zIndex = 3; newEl.style.opacity = '0';
        newEl.style.transform = 'perspective(700px) translateZ(-2000px) scale(0.1)';
        newEl.style.filter = 'blur(20px)';
        _hardCutScreen(oldEl);
        var start = null;
        function frame(ts) {
            if (!start) start = ts;
            var t = Math.min((ts - start) / dur, 1);
            var sp = springDamp(t, 2.5, 5); 
            
            var nZ = -2000 * (1 - sp);
            var nS = 0.1 + 0.9 * sp;
            var nBlur = 20 * (1 - sp);
            var nAlpha = Math.min(1, sp * 2.5);
            newEl.style.transform = 'perspective(700px) translateZ(' + nZ.toFixed(0) + 'px) scale(' + nS.toFixed(4) + ')';
            newEl.style.filter = 'blur(' + Math.max(0, nBlur).toFixed(1) + 'px)';
            newEl.style.opacity = nAlpha.toFixed(3);
            if (t < 1) requestAnimationFrame(frame);
            else { newEl.style.filter = ''; newEl.style.transform = ''; newEl.style.transformStyle = 'preserve-3d'; callback(); }
        }
        requestAnimationFrame(frame);
    }

    function doDepthVortex(oldEl, newEl, forward, callback) {
        var dur = getDuration() * 1.8;
        prepNewScreen(newEl);
        newEl.style.zIndex = 3; newEl.style.opacity = '0';
        newEl.style.transform = 'perspective(700px) translateZ(-1800px) rotate(-180deg) scale(0.05)';
        newEl.style.filter = 'blur(18px)';
        _hardCutScreen(oldEl);
        var start = null;
        function frame(ts) {
            if (!start) start = ts;
            var t = Math.min((ts - start) / dur, 1);
            var sp = springDamp(t, 2.0, 4); 
            var nZ = -1800 * (1 - sp);
            var nRot = -180 * (1 - sp);
            var nS = 0.05 + 0.95 * sp;
            var nBlur = 18 * (1 - sp);
            var nAlpha = Math.min(1, sp * 2.5);
            newEl.style.transform = 'perspective(700px) translateZ(' + nZ.toFixed(0) + 'px) rotate(' + nRot.toFixed(1) + 'deg) scale(' + nS.toFixed(4) + ')';
            newEl.style.filter = 'blur(' + Math.max(0, nBlur).toFixed(1) + 'px)';
            newEl.style.opacity = nAlpha.toFixed(3);
            if (t < 1) requestAnimationFrame(frame);
            else { newEl.style.filter = ''; newEl.style.transform = ''; newEl.style.transformStyle = 'preserve-3d'; callback(); }
        }
        requestAnimationFrame(frame);
    }

    function doDepthZoom(oldEl, newEl, forward, callback) {
        var dur = getDuration() * 2.0;
        prepNewScreen(newEl);
        newEl.style.zIndex = 3; newEl.style.opacity = '0';
        newEl.style.transform = 'perspective(700px) translateZ(-3000px) scale(0.02)';
        newEl.style.filter = 'blur(30px)';
        _hardCutScreen(oldEl);
        var start = null;
        function frame(ts) {
            if (!start) start = ts;
            var t = Math.min((ts - start) / dur, 1);
            var sp = springDamp(t, 3.0, 6); 
            var nZ = -3000 * (1 - sp);
            var nS = 0.02 + 0.98 * sp;
            var nBlur = 30 * Math.max(0, 1 - sp * 1.5);
            var nAlpha = Math.min(1, sp * 3);
            newEl.style.transform = 'perspective(700px) translateZ(' + nZ.toFixed(0) + 'px) scale(' + nS.toFixed(4) + ')';
            newEl.style.filter = 'blur(' + Math.max(0, nBlur).toFixed(1) + 'px)';
            newEl.style.opacity = nAlpha.toFixed(3);
            if (t < 1) requestAnimationFrame(frame);
            else { newEl.style.filter = ''; newEl.style.transform = ''; newEl.style.transformStyle = 'preserve-3d'; callback(); }
        }
        requestAnimationFrame(frame);
    }

    function doMorph(oldEl,newEl,forward,callback){var dur=getDuration()*1.2;prepNewScreen(newEl);newEl.style.zIndex=3;newEl.style.opacity='0';newEl.style.transform='scale(1.08) skewX(3deg)';newEl.style.filter='blur(8px)';oldEl.style.zIndex=1;var start=null;function frame(ts){if(!start)start=ts;var t=Math.min((ts-start)/dur,1);var e=t<0.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;newEl.style.opacity=Math.min(1,e*1.8).toFixed(3);newEl.style.transform='scale('+(1.08-0.08*e).toFixed(3)+') skewX('+(3*(1-e)).toFixed(1)+'deg)';newEl.style.filter='blur('+(8*(1-e)).toFixed(1)+'px)';oldEl.style.transform='scale('+(1+0.08*e).toFixed(3)+') skewX('+(-3*e).toFixed(1)+'deg)';oldEl.style.opacity=(1-e).toFixed(3);oldEl.style.filter='blur('+(8*e).toFixed(1)+'px)';if(t<1)requestAnimationFrame(frame);else{newEl.style.filter='';newEl.style.transform='';oldEl.style.filter='';callback();}}requestAnimationFrame(frame);}

    function doDoor(oldEl,newEl,forward,callback){var dur=getDuration()*1.1;prepNewScreen(newEl);newEl.style.zIndex=1;newEl.style.opacity='1';oldEl.style.zIndex=3;var start=null;function frame(ts){if(!start)start=ts;var t=Math.min((ts-start)/dur,1);var e=1-Math.pow(1-t,3);var half=50*e;oldEl.style.clipPath='inset(0 '+half.toFixed(1)+'% 0 '+half.toFixed(1)+'%)';oldEl.style.opacity=(1-t*t).toFixed(3);if(t<1)requestAnimationFrame(frame);else{oldEl.style.clipPath='';oldEl.style.transform='';cleanupDecomposition(newEl);callback();}}requestAnimationFrame(frame);}

    
    
    function doFocus(oldEl,newEl,forward,callback){var dur=getDuration()*1.5;prepNewScreen(newEl);newEl.style.zIndex=3;newEl.style.opacity='0';newEl.style.transform='scale(1.04)';newEl.style.filter='blur(14px)';oldEl.style.zIndex=1;var start=null;function frame(ts){if(!start)start=ts;var t=Math.min((ts-start)/dur,1);var e=t<0.5?2*t*t:1-Math.pow(-2*t+2,2)/2;newEl.style.opacity=Math.min(1,e*1.6).toFixed(3);newEl.style.transform='scale('+(1.04-0.04*e).toFixed(3)+')';newEl.style.filter='blur('+(14*(1-e)).toFixed(1)+'px)';oldEl.style.transform='scale('+(1-0.02*e).toFixed(3)+')';oldEl.style.opacity=(1-e).toFixed(3);oldEl.style.filter='blur('+(10*e).toFixed(1)+'px)';if(t<1)requestAnimationFrame(frame);else{newEl.style.filter='';newEl.style.transform='';oldEl.style.filter='';oldEl.style.transform='';callback();}}requestAnimationFrame(frame);}
    function doSwirl(oldEl,newEl,forward,callback){var dur=getDuration()*1.4;prepNewScreen(newEl);newEl.style.zIndex=3;newEl.style.opacity='0';newEl.style.transform='rotate(180deg) scale(0)';oldEl.style.zIndex=1;var start=null;function frame(ts){if(!start)start=ts;var t=Math.min((ts-start)/dur,1);var sp=springDamp(t,1.5,4);newEl.style.transform='rotate('+(180*(1-sp)).toFixed(1)+'deg) scale('+Math.max(0.01,sp).toFixed(3)+')';newEl.style.opacity=Math.min(1,sp*2).toFixed(3);oldEl.style.transform='rotate('+(-90*t).toFixed(1)+'deg) scale('+(1-0.5*t).toFixed(3)+')';oldEl.style.opacity=(1-t).toFixed(3);if(t<1)requestAnimationFrame(frame);else{newEl.style.transform='';oldEl.style.transform='';callback();}}requestAnimationFrame(frame);}

    var _currentSceneId = null;
    var _sceneEnvRegistry = {}; 
    function _swapSceneEnv(newEl) {
        var newSceneId = newEl.dataset.sceneId || null;
        if (!newSceneId || newSceneId === _currentSceneId) return false;
        _currentSceneId = newSceneId;
        
        if (newEl.dataset.sceneEnv && !_sceneEnvRegistry[newSceneId]) {
            try { _sceneEnvRegistry[newSceneId] = JSON.parse(newEl.dataset.sceneEnv); } catch(e) {}
        }
        var envData = _sceneEnvRegistry[newSceneId] || null;
        if (!envData) return true; 

        if (envData.transition) config.transition = envData.transition;
        if (envData.duration)   config.duration   = envData.duration;

        var newCloud = envData.cloudEffect || 'none';
        var newTunnel = envData.tunnel ? true : false;
        var newBg = envData.bg || '#000000';
        var xfadeDur = Math.max(400, Math.min(config.duration, 800));

        
        var _snapshots = [];
        var _cvIds = ['impulse-tunnel-canvas','impulse-motion-lava-canvas','impulse-wave-canvas','impulse-3d-canvas','impulse-fx-canvas'];
        _cvIds.forEach(function(id) {
            var src = document.getElementById(id);
            if (!src || src.style.opacity === '0') return;
            try {
                var snap = document.createElement('canvas');
                snap.width = src.width || window.innerWidth;
                snap.height = src.height || window.innerHeight;
                snap.style.cssText = src.style.cssText + ';position:fixed;top:0;left:0;width:100%;height:100%;z-index:1;pointer-events:none;opacity:1;transition:opacity ' + xfadeDur + 'ms ease-in-out;';
                snap.getContext('2d').drawImage(src, 0, 0);
                document.body.appendChild(snap);
                _snapshots.push(snap);
            } catch(e) {}
        });

        requestAnimationFrame(function() {
            _snapshots.forEach(function(s) { s.style.opacity = '0'; });
            setTimeout(function() { _snapshots.forEach(function(s) { if(s.parentNode) s.parentNode.removeChild(s); }); }, xfadeDur + 50);
        });

        
        
        document.documentElement.style.cssText = document.documentElement.style.cssText.replace(/background[^;]+;/g,'');
        document.documentElement.style.background = newBg;

        if (wrapperEl && envData) {
            var _dsMap = {
                lavaColor1:'lavaColor1',lavaColor2:'lavaColor2',lavaColor3:'lavaColor3',lavaColor4:'lavaColor4',
                
                lavaSpeed:'lavaSpeed',lavaIntensity:'lavaIntensity',waveColor1:'waveColor1',waveColor2:'waveColor2',waveColor3:'waveColor3',
                waveColor4:'waveColor4',waveSpeed:'waveSpeed',wavePreset:'wavePreset',waveIntensity:'waveIntensity',
                '3dColor1':'3dColor1','3dColor2':'3dColor2','3dColor3':'3dColor3','3dColor4':'3dColor4',
                '3dSpeed':'3dSpeed','3dPreset':'3dPreset','3dIntensity':'3dIntensity','3dBgColor':'3dBgColor',
                pageBgColor:'pageBgColor',mouseSensLevel:'mouseSensLevel',neonHue:'neonHue',
                spaceVariant:'spaceVariant',prismBg:'prismBg',prismShape:'prismShape',
                bwElementSize:'bwElementSize',bwElementCount:'bwElementCount',bwAccentColor:'bwAccentColor',
                tunnelSpeed:'tunnelSpeed'
            };
            Object.keys(_dsMap).forEach(function(k) {
                if (envData[k] !== undefined) wrapperEl.dataset[_dsMap[k]] = envData[k];
            });
            
            wrapperEl.dataset.depthEnabled  = envData.depthEnabled  || '0';
            wrapperEl.dataset.depthImage    = envData.depthImage    || '';
            wrapperEl.dataset.depthMap      = envData.depthMap      || '';
            wrapperEl.dataset.depthStrength = envData.depthStrength || 50;
        }
        
        if (typeof reinitTunnel === 'function') {
            reinitTunnel(newTunnel, newCloud === 'none' ? null : newCloud, null, envData.tunnelSpeed || null);
        }

        return true;
    }

    
    function _zoneDuration(idx){
        if(!wrapperEl)return config.duration;
        var sc=screens&&screens[idx];
        if(sc){
            var ms=parseInt(sc.dataset.revealSpeedMs);
            if(!isNaN(ms)&&ms>0)return ms;
        }
        var d=parseInt(wrapperEl.dataset.duration); 
        return isNaN(d)?config.duration:d;
    }
    function goTo(index){if(transitioning||index<0||index>=screens.length||index===current)return;transitioning=true;config.duration=_zoneDuration(index);
        
        try{document.body.classList.add('impulse-screens-transitioning');}catch(_e){}
        
        var forward=(current===screens.length-1&&index===0)?true:(current===0&&index===screens.length-1)?false:index>current;
        var _backFirstOptIn = wrapperEl && wrapperEl.dataset.heroBackFirstTransition;
        window._impulseSoftBackReveal = (!forward && index === 0 && !!_backFirstOptIn);
        
        if (window.impulseOnScreenLeave) { try { window.impulseOnScreenLeave(screens[current]); } catch (_e) {} }
        
        screens[index].classList.add('impulse-screen-entering');
        if(window.impulsePreWarmScreen)window.impulsePreWarmScreen(screens[index]);

        
        if(navigator.vibrate&&window===window.top&&_userTapped){try{navigator.vibrate(6);}catch(e){}}
        _swapSceneEnv(screens[index]);
        
        var p=getPreset(screens[index], forward?'fwd':'back');
        var oldEl=screens[current],newEl=screens[index];if(config.cloudEffect==='cosmos'&&window._impulseCosmosHyperJump)window._impulseCosmosHyperJump();else if(config.cloudEffect==='fireflies'&&window._impulseFirefliesHyperJump)window._impulseFirefliesHyperJump();current=index;
        
        try { document.body.setAttribute('data-impulse-screen', String(index)); } catch(_e){}
        function cleanup(){try{document.body.classList.remove('impulse-screens-transitioning');}catch(_e){}screens.forEach(function(s,i){if(i===index){applyFocusState(s);s.style.animation='';}else if(i<index)applyExitState(s);else applyEnterState(s);});current=index;transitioning=false;updateHash();updateNavDots();updateScreenNav();cooldownTimer=setTimeout(function(){cooldownTimer=null;if(_pendingNav===1){_pendingNav=0;next();}else if(_pendingNav===-1){_pendingNav=0;prev();}},config.cooldown);document.dispatchEvent(new Event('impulse-screen-changed'));if(window._impulseSeedTimelineProgress)window._impulseSeedTimelineProgress(forward);}
        var entrancePreset=newEl.dataset.entrancePreset||'none';
        if(entrancePreset!=='none'){newEl.style.transition='none';newEl.style.visibility='visible';newEl.style.zIndex=3;newEl.style.opacity='1';newEl.style.transform='scale(1)';newEl.style.pointerEvents='none';void newEl.offsetHeight;var entranceBg=newEl.dataset.entranceBg||'#000000';impulseRunScreenEntrance(newEl,entranceBg);oldEl.style.zIndex=1;var _trans=transStr(p);oldEl.style.transition=_trans;oldEl.style.opacity=p.exit.opacity;oldEl.style.transform=p.exit.transform;setTimeout(cleanup,getDuration()+50);return;}
        if(p.complex){var fn={rise:doRise,fall:doFall,dissolve:doDissolve,depth_spring:doDepthSpring,depth_vortex:doDepthVortex,depth_zoom:doDepthZoom,morph:doMorph,door:doDoor,swirl:doSwirl,focus:doFocus}[p.complex];if(fn){var _cc=getDecompChildren(newEl);
        
        for(var ci=0;ci<_cc.length;ci++)_cc[ci].style.opacity='0';

        

        
        
        var _oldCards  = getDecompChildren(oldEl);
        var _oldLeaky  = [];
        for (var _oci = 0; _oci < _oldCards.length; _oci++) {
            var _lls = getLeakyLayers(_oldCards[_oci]);
            for (var _lli = 0; _lli < _lls.length; _lli++) _oldLeaky.push(_lls[_lli]);
        }
        var _leakySync = 0;
        function _tickLeakyOpacity() {
            _leakySync = 0;
            if (!_oldLeaky.length) return;
            var cs = getComputedStyle(oldEl);
            var a = cs.opacity || '1';
            for (var li = 0; li < _oldLeaky.length; li++) _oldLeaky[li].style.opacity = a;
            _leakySync = requestAnimationFrame(_tickLeakyOpacity);
        }
        if (_oldLeaky.length) _leakySync = requestAnimationFrame(_tickLeakyOpacity);

        

        if(_cc.length>0){decomposeEnter(newEl);}
        
        fn(oldEl,newEl,forward,function(){
            if (_leakySync) { cancelAnimationFrame(_leakySync); _leakySync = 0; }

            

            
            
            for (var lk = 0; lk < _oldLeaky.length; lk++) {
                _oldLeaky[lk].style.display = 'none';
            }
            cleanup();
        });
        
        return;}}
        var trans=transStr(p);

        
        clearStyles(newEl); 
        if(p.clip){if(forward){newEl.style.transition='none';newEl.style.visibility='visible';newEl.style.zIndex=3;newEl.style.opacity='1';newEl.style.transform='scale(1)';newEl.style.clipPath=p.enter.clip;void newEl.offsetHeight;newEl.style.transition=trans;newEl.style.clipPath=p.visible.clip;oldEl.style.zIndex=1;oldEl.style.transition=trans;oldEl.style.opacity=p.exit.opacity;oldEl.style.transform=p.exit.transform;}
        else{newEl.style.transition='none';newEl.style.visibility='visible';newEl.style.zIndex=1;newEl.style.opacity='1';newEl.style.transform='scale(1)';clearStyles(newEl);oldEl.style.transition='none';oldEl.style.zIndex=3;oldEl.style.clipPath=p.visible.clip;void oldEl.offsetHeight;oldEl.style.transition=trans;oldEl.style.clipPath=p.enter.clip;oldEl.style.opacity=p.exit.opacity;}}
        else{if(forward){newEl.style.transition='none';newEl.style.visibility='visible';newEl.style.zIndex=3;newEl.style.opacity=p.enter.opacity;newEl.style.transform=p.enter.transform;if(p.origin)newEl.style.transformOrigin=p.origin;void newEl.offsetHeight;newEl.style.transition=trans;newEl.style.opacity='1';newEl.style.transform='scale(1)';oldEl.style.zIndex=1;if(p.exitOrigin)oldEl.style.transformOrigin=p.exitOrigin;oldEl.style.transition=trans;oldEl.style.opacity=p.exit.opacity;oldEl.style.transform=p.exit.transform;}
        else{newEl.style.transition='none';newEl.style.visibility='visible';newEl.style.zIndex=3;newEl.style.opacity=p.exit.opacity;newEl.style.transform=p.exit.transform;if(p.exitOrigin)newEl.style.transformOrigin=p.exitOrigin;void newEl.offsetHeight;newEl.style.transition=trans;newEl.style.opacity='1';newEl.style.transform='scale(1)';oldEl.style.zIndex=1;if(p.origin)oldEl.style.transformOrigin=p.origin;oldEl.style.transition=trans;oldEl.style.opacity=p.enter.opacity;oldEl.style.transform=p.enter.transform;}}
        oldEl.style.filter='';

        oldEl.style.transition = 'none';
        oldEl.style.transform = '';
        oldEl.style.opacity = '0';
        oldEl.style.setProperty('visibility', 'hidden', 'important');
        var _ohLeaks = getLeakyLayers(oldEl);
        for (var _li = 0; _li < _ohLeaks.length; _li++) _ohLeaks[_li].style.display = 'none';
        setTimeout(cleanup,getDuration()+50);}

    

    

    

    

    var _pendingNav=0; 
    
    function _isSkippedScreen(i) {
        var s = screens[i];
        if (!s) return false;
        return s.getAttribute('data-screen-skip') === '1'
            || s.classList.contains('impulse-screen-skipped');
    }
    function _nextVisibleIndex(start) {
        var i = start;
        while (i < screens.length && _isSkippedScreen(i)) i++;
        return i;
    }
    function _prevVisibleIndex(start) {
        var i = start;
        while (i >= 0 && _isSkippedScreen(i)) i--;
        return i;
    }
    function next(){if(transitioning||cooldownTimer)return;if(_isReleased)return;if(hasScroll(screens[current])&&!atBottom(screens[current]))return;_pendingNav=0;

        var _hcC=wrapperEl?(parseInt(wrapperEl.dataset.heroCount)||0):0;
        if(config.bodyScroll==='classic'&&_hcC>0&&_hcC<screens.length&&current+1>=_hcC){releaseToBody();return;}
        if(current+1>=screens.length){
            
            if(window._impulseNextSequenceUrl){navigateToNextSequence();}
            else if(_hasPageModeBelow){releaseScreenMode();}
            else if(config.infinite){goTo(0);}
            
        }else{
            var _nv = _nextVisibleIndex(current+1);
            if (_nv >= screens.length) {
                
                if(window._impulseNextSequenceUrl){navigateToNextSequence();}
                else if(_hasPageModeBelow){releaseScreenMode();}
                else if(config.infinite){goTo(_nextVisibleIndex(0));}
            } else {
                goTo(_nv);
            }
        }}

    

    function detectPageModeBelow() {
        if (!wrapperEl) return false;
        var sib = wrapperEl.nextElementSibling;
        while (sib) {
            if (sib.nodeType === 1 && sib.offsetHeight > 0
                && !sib.matches('.impulse-screen, .impulse-screen-wrapper, script, style, link, '
                    
                    + 'header.impulse-header, footer.impulse-footer, '
                    + '.impulse-modal, .impulse-modal-drawer')) {
                
                var _pmPos = getComputedStyle(sib).position;
                if (_pmPos !== 'fixed' && _pmPos !== 'absolute') return true;
            }
            sib = sib.nextElementSibling;
        }
        return false;
    }
    function releaseScreenMode() {
        if (_isReleased) return;
        _isReleased = true;
        var b = document.body, h = document.documentElement;
        b.style.overflow = ''; b.style.overflowX = ''; b.style.height = '';
        b.style.maxWidth = ''; b.style.position = ''; b.style.width = '';
        h.style.overflow = ''; h.style.height = ''; h.style.overscrollBehavior = '';
        b.classList.remove('impulse-screen-mode-active');
        b.classList.add('impulse-screen-mode-released');

        

        
        var unit = 'var(--imp-vh, 100dvh)';
        wrapperEl.style.position = 'relative';
        wrapperEl.style.height = unit;
        wrapperEl.style.width = '100%';
        wrapperEl.style.overflow = 'hidden';

        screens.forEach(function(s) {
            s.style.position = 'absolute';
            s.style.top = '0'; s.style.left = '0';
            s.style.width = '100%'; s.style.height = '100%';
        });
        if (!_scrollReentryBound) {
            _scrollReentryBound = true;
            bindReleaseScroll();
        }

        

        
        document.body.classList.add('impulse-hero-exiting');

        
        requestAnimationFrame(function() {
            window.scrollTo({ top: wrapperEl.offsetHeight, behavior: 'smooth' });
        });
        window.dispatchEvent(new CustomEvent('impulse-roll-released'));
    }
    function reEnterScreenMode() {
        if (!_isReleased) return;
        _isReleased = false;
        var b = document.body, h = document.documentElement;
        var unit = 'var(--imp-vh, 100dvh)';
        b.style.overflow = 'hidden'; b.style.overflowX = 'hidden';
        b.style.height = unit; b.style.maxWidth = '100vw';
        b.style.position = 'fixed'; b.style.width = '100%';
        h.style.overflow = 'hidden'; h.style.height = unit;
        h.style.overscrollBehavior = 'none';
        b.classList.add('impulse-screen-mode-active');
        b.classList.remove('impulse-screen-mode-released');
        b.classList.remove('impulse-hero-exiting');
        
        b.classList.add('impulse-hero-visible');
        b.classList.remove('impulse-past-hero');
        wrapperEl.style.position = '';
        wrapperEl.style.height = '';
        wrapperEl.style.width = '';
        wrapperEl.style.overflow = '';
        screens.forEach(function(s) {
            s.style.position = 'fixed';
            s.style.top = '0'; s.style.left = '0';
            s.style.width = '100vw'; s.style.height = unit;
        });
        
        if (typeof jumpTo === 'function') jumpTo(current);
        window.dispatchEvent(new CustomEvent('impulse-roll-re-entered'));
    }
    function bindReleaseScroll() {
        var lastY = window.scrollY;
        var rafId = null;
        function check() {
            rafId = null;
            if (!_isReleased) return;
            var y = window.scrollY || window.pageYOffset || 0;
            
            if (y <= 2 && lastY > 2) {
                reEnterScreenMode();
            }
            lastY = y;
        }
        window.addEventListener('scroll', function() {
            if (rafId) return;
            rafId = requestAnimationFrame(check);
        }, { passive: true });
    }

    

    

    var _classicScrollBound = false;
    function releaseToBody(){
        if(_isReleased) return;
        var hc = wrapperEl ? (parseInt(wrapperEl.dataset.heroCount)||0) : 0;
        if(hc<=0 || hc>=screens.length) return; 
        _isReleased = true;
        var b=document.body, h=document.documentElement;
        var unit='var(--imp-vh, 100dvh)';
        
        b.style.overflow=''; b.style.overflowX=''; b.style.height='';
        b.style.maxWidth=''; b.style.position=''; b.style.width='';
        h.style.overflow=''; h.style.height=''; h.style.overscrollBehavior='';
        h.style.scrollSnapType='y proximity';
        b.classList.remove('impulse-screen-mode-active');
        b.classList.add('impulse-screen-mode-released');
        b.classList.add('impulse-body-classic');

        

        wrapperEl.style.position='relative';
        wrapperEl.style.height='auto';
        wrapperEl.style.minHeight=unit;
        wrapperEl.style.width='100%';
        wrapperEl.style.overflow='visible';
        wrapperEl.style.paddingTop=unit;
        screens.forEach(function(s,i){
            if(i<hc){
                
                s.style.position='absolute';
                s.style.top='0'; s.style.left='0';
                s.style.width='100%'; s.style.height=unit;
            } else {

                s.style.position='relative';
                s.style.top=''; s.style.left='';
                s.style.width='100%'; s.style.height='auto';
                s.style.minHeight=unit; s.style.zIndex='';
                s.style.transition='none'; s.style.transform=''; s.style.filter='';
                s.style.opacity='1';
                s.style.setProperty('visibility','visible','important');
                s.style.setProperty('pointer-events','auto','important');
                s.style.scrollSnapAlign='start';
                s.classList.remove('impulse-screen-active','impulse-screen-entering');

                s.style.marginTop = '';
            }
        });
        if(!_classicScrollBound){ _classicScrollBound=true; bindClassicScroll(); }
        document.body.classList.add('impulse-hero-exiting');

        
        requestAnimationFrame(function(){
            var fb=screens[hc];
            var top=fb ? (fb.getBoundingClientRect().top + (window.scrollY||window.pageYOffset||0)) : window.innerHeight;
            window.scrollTo({ top: top, behavior:'smooth' });
            document.body.classList.add('impulse-past-hero');
            document.body.classList.remove('impulse-hero-visible');
        });
        window.dispatchEvent(new CustomEvent('impulse-roll-released'));
    }
    function reEnterToHero(){
        if(!_isReleased) return;
        var hc = wrapperEl ? (parseInt(wrapperEl.dataset.heroCount)||0) : 0;
        _isReleased=false;
        var b=document.body, h=document.documentElement;
        var unit='var(--imp-vh, 100dvh)';
        h.style.scrollSnapType='';
        b.style.overflow='hidden'; b.style.overflowX='hidden';
        b.style.height=unit; b.style.maxWidth='100vw';
        b.style.position='fixed'; b.style.width='100%';
        h.style.overflow='hidden'; h.style.height=unit; h.style.overscrollBehavior='none';
        b.classList.add('impulse-screen-mode-active');
        b.classList.remove('impulse-screen-mode-released');
        b.classList.remove('impulse-body-classic');
        b.classList.remove('impulse-hero-exiting');
        b.classList.remove('impulse-past-hero');
        b.classList.add('impulse-hero-visible');
        wrapperEl.style.position=''; wrapperEl.style.height=''; wrapperEl.style.minHeight='';
        wrapperEl.style.width=''; wrapperEl.style.overflow=''; wrapperEl.style.paddingTop='';
        screens.forEach(function(s){
            s.style.position='fixed'; s.style.top='0'; s.style.left='0';
            s.style.width='100vw'; s.style.height=unit;
            s.style.marginTop=''; s.style.minHeight=''; s.style.scrollSnapAlign='';
        });
        current = Math.max(0, hc-1);
        if(typeof jumpTo==='function') jumpTo(current);
        try{document.body.setAttribute('data-impulse-screen', String(current));}catch(_e){}
        window.dispatchEvent(new CustomEvent('impulse-roll-re-entered'));
    }
    function bindClassicScroll(){
        var lastY=window.scrollY||window.pageYOffset||0;
        var rafId=null;
        function chk(){
            rafId=null;
            if(!_isReleased) return;
            var y=window.scrollY||window.pageYOffset||0;
            
            if(y<=2 && lastY>2){ reEnterToHero(); }
            lastY=y;
        }
        window.addEventListener('scroll', function(){ if(rafId)return; rafId=requestAnimationFrame(chk); }, {passive:true});
    }
    function navigateToNextSequence(){
        var url=window._impulseNextSequenceUrl;
        if(!url||nextSeqNavigating)return;
        nextSeqNavigating=true;

        var oldEl=screens[current];
        var p=getPreset();
        var dur=getDuration();
        var trans=transStr(p);

        oldEl.style.zIndex=2;
        oldEl.style.transition=trans+(p.enter&&p.enter.blur?', filter '+dur+'ms '+config.easing:'');
        oldEl.style.opacity=p.exit.opacity;
        oldEl.style.transform=p.exit.transform;
        if(p.exit&&p.exit.blur) oldEl.style.filter='blur('+p.exit.blur+')';

        setTimeout(function(){ window.location.href=url; }, dur+30);
    }
    var nextSeqNavigating=false;

    (function preloadNextSequence(){
        if(!window._impulseNextSequenceUrl) return;
        function maybePreload(){
            if(screens && current===screens.length-1 && !window._seqPreloaded){
                window._seqPreloaded=true;
                var link=document.createElement('link');
                link.rel='prefetch'; link.href=window._impulseNextSequenceUrl;
                document.head.appendChild(link);
                if(typeof fetch!=='undefined'){
                    fetch(window._impulseNextSequenceUrl,{credentials:'same-origin',cache:'force-cache'}).catch(function(){});
                }
            }
        }
        document.addEventListener('impulse-screen-changed', maybePreload);
        setTimeout(maybePreload, 1000);
    })();
        
        function prev(){if(transitioning||cooldownTimer)return;if(hasScroll(screens[current])&&!atTop(screens[current]))return;_pendingNav=0;
            
            if(current-1<0){}
            else{
                var _pv = _prevVisibleIndex(current-1);
                if (_pv >= 0) goTo(_pv);
                
            }}

    

    var OVERFLOW_TOLERANCE_PX = 80;

    

    
    
    function hasScroll(s){if(!s)return false;var ov=getComputedStyle(s).overflowY;if(ov!=='scroll'&&ov!=='auto')return false;var mode=s.dataset?s.dataset.scroll:'';
    
    var _mob=(window.innerWidth||document.documentElement.clientWidth||0)<=767;
    var tol=(mode==='free'||_mob)?2:OVERFLOW_TOLERANCE_PX;return s.scrollHeight>s.clientHeight+tol;}function atTop(s){return s.scrollTop<=1;}function atBottom(s){return s.scrollTop+s.clientHeight>=s.scrollHeight-2;}
    function init(){

        
        if(document.body.getAttribute('data-screen-mode')!=='1')return;
        wrapperEl=document.querySelector('.impulse-screen-wrapper');if(!wrapperEl)return;

        

        

        
        (function(){
            function _reserveSnapFooter(){
                var _f=document.querySelector('.impulse-snap-footer'); if(!_f)return;
                var _sc=_f.closest('.impulse-screen'); if(!_sc)return;
                var _h=(getComputedStyle(_f).display==='none')?0:Math.ceil(_f.getBoundingClientRect().height);
                _sc.style.setProperty('--impulse-screen-bottom-inset', _h+'px');
            }
            _reserveSnapFooter();
            setTimeout(_reserveSnapFooter,250); setTimeout(_reserveSnapFooter,700);
            var _sfT; window.addEventListener('resize',function(){clearTimeout(_sfT);_sfT=setTimeout(_reserveSnapFooter,150);});
        })();

        
        
        if(document.body.classList.contains('impulse-scroll-classic')){
            window._impulseScreenMode=false;
            var _cs=wrapperEl.querySelectorAll(':scope > .impulse-screen');

            
            
            var _nativeMinVhFor=function(_s){var _w=window.innerWidth||document.documentElement.clientWidth||0;var _pick=function(_v){if(_v==null||_v==='')return null;var _n=parseInt(_v);return isNaN(_n)?null:_n;};var _m=_pick(_s.dataset.nativeMinVhMobile),_t=_pick(_s.dataset.nativeMinVhTablet),_d=_pick(_s.dataset.nativeMinVh);var _v;if(_w<=767){_v=(_m!=null)?_m:((_t!=null)?_t:_d);}else if(_w<=1024){_v=(_t!=null)?_t:_d;}else{_v=_d;}return (_v!=null&&_v>0)?_v:0;};
            var _applyClassicMinH=function(){for(var _i=0;_i<_cs.length;_i++){var _s=_cs[_i];_s.style.position='relative';_s.style.opacity='1';_s.style.transform='none';_s.style.filter='none';_s.style.clipPath='';_s.style.setProperty('visibility','visible','important');_s.style.setProperty('height','auto','important');_s.style.setProperty('max-height','none','important');var _mv=_nativeMinVhFor(_s);var _mvv=(_mv>0?_mv+'vh':'0');_s.style.setProperty('min-height',_mvv,'important');var _is=_s.querySelector(':scope > .impulse-section');if(_is){_is.style.setProperty('height','auto','important');_is.style.setProperty('min-height',_mvv,'important');_is.style.setProperty('max-height','none','important');_is.style.setProperty('overflow','visible','important');}

var _pg=_s.querySelector(':scope > .impulse-page');if(_pg){_pg.style.setProperty('min-height',_mvv,'important');_pg.style.setProperty('height','auto','important');}
var _cw=_s.querySelector('.impulse-content-wrapper');if(_cw){_cw.style.setProperty('min-height',_mvv,'important');_cw.style.setProperty('height','auto','important');}}};
            _applyClassicMinH();
            var _rzT;window.addEventListener('resize',function(){clearTimeout(_rzT);_rzT=setTimeout(_applyClassicMinH,150);});

            

            try{requestAnimationFrame(function(){requestAnimationFrame(function(){document.body.classList.add('impulse-screens-booted');});});}catch(_e){try{document.body.classList.add('impulse-screens-booted');}catch(_e2){}}
            return;
        }
        window._impulseScreenMode=true;

        
        
        window.impulseScreenMode = { getCurrentScreen: function(){ return current; } };config.transition=wrapperEl.dataset.transition||'z_depth';config.cooldown=parseInt(wrapperEl.dataset.cooldown)||150;config.duration=parseInt(wrapperEl.dataset.duration)||700;config.intensity=parseInt(wrapperEl.dataset.intensity)||50;config.navDots=wrapperEl.dataset.navdots==='1';config.infinite=wrapperEl.dataset.infinite==='1';config.bodyScroll=(wrapperEl.dataset.bodyScroll==='classic')?'classic':'snap';config.tunnel=wrapperEl.dataset.tunnel==='1';config.tunnelSpeed=parseFloat(wrapperEl.dataset.tunnelSpeed)||1;config.cloudEffect=wrapperEl.dataset.cloudEffect||'none';config.tunnelFill=wrapperEl.dataset.tunnelFill==='1';config.mouseSensLevel=parseFloat(wrapperEl.dataset.mouseSensLevel||'0.5');config.depthEnabled=wrapperEl.dataset.depthEnabled==='1';config.depthImage=wrapperEl.dataset.depthImage||'';config.depthMap=wrapperEl.dataset.depthMap||'';config.depthStrength=parseInt(wrapperEl.dataset.depthStrength||'50');if(config.cloudEffect==='depth_image'&&!config.depthMap){config.cloudEffect='none';}

        
        
        document.body.style.overflow='hidden';
        document.body.style.overflowX='hidden';
        document.body.style.height='var(--imp-vh, 100dvh)';
        document.body.style.maxWidth='100vw';
        document.body.style.position='fixed';
        document.body.style.width='100%';
        document.documentElement.style.overflow='hidden';
        document.documentElement.style.height='var(--imp-vh, 100dvh)';
        document.documentElement.style.overscrollBehavior='none';
        document.body.classList.add('impulse-screen-mode-active');
        screens=Array.from(wrapperEl.querySelectorAll('.impulse-screen'));_currentSceneId=screens.length?screens[0].dataset.sceneId||null:null;screens.forEach(function(s){if(s.dataset.sceneEnv&&s.dataset.sceneId&&!_sceneEnvRegistry[s.dataset.sceneId]){try{_sceneEnvRegistry[s.dataset.sceneId]=JSON.parse(s.dataset.sceneEnv);}catch(e){}}});if((config.tunnel||config.cloudEffect!=='none')&&config.cloudEffect!=='depth_image'){try{initTunnel();}catch(e){console.error('Impulse: effect init failed',e);}}if(screens.length<2){if(screens.length===1){injectStyles();var _s0=screens[0];_s0.dataset.screenIndex=0;_s0.style.position='fixed';_s0.style.top='0';_s0.style.left='0';_s0.style.width='100vw';_s0.style.height='var(--imp-vh, 100dvh)';_s0.style.zIndex='2';_s0.style.overflowX='hidden';_s0.style.overflowY='auto';_s0.style.overscrollBehavior='none';_s0.style.maxWidth='100vw';_s0.style.willChange='transform, opacity';_s0.style.transition='none';applyFocusState(_s0);try{document.body.setAttribute('data-impulse-screen','0');}catch(_e){}requestAnimationFrame(function(){requestAnimationFrame(function(){try{document.body.classList.add('impulse-screens-booted');}catch(_e){}});});try{if(window.ImpulseTimeline&&window.ImpulseTimeline.hasTimeline(_s0))window.ImpulseTimeline.apply(_s0,0);}catch(_eTL){}}return;}injectStyles();
        screens.forEach(function(s,i){s.dataset.screenIndex=i;s.style.position='fixed';s.style.top='0';s.style.left='0';s.style.width='100vw';s.style.height='var(--imp-vh, 100dvh)';s.style.zIndex='2';s.style.overflowX='hidden';s.style.overflowY='auto';s.style.overscrollBehavior='none';s.style.maxWidth='100vw';s.style.willChange='transform, opacity';s.style.transition='none';if(i===0)applyFocusState(s);else applyEnterState(s);});
        
        try { document.body.setAttribute('data-impulse-screen', '0'); } catch(_e){}
        
        requestAnimationFrame(function(){
            requestAnimationFrame(function(){
                try { document.body.classList.add('impulse-screens-booted'); } catch(_e){}
            });
        });
        
        try {
            if (window.ImpulseTimeline && screens[0] &&
                window.ImpulseTimeline.hasTimeline(screens[0])) {
                window.ImpulseTimeline.apply(screens[0], 0);
            }
        } catch(_eTL){}
        
        setTimeout(function(){
            try { document.dispatchEvent(new Event('impulse-screen-changed')); } catch(_e){}
        }, 0);
        if((config.depthEnabled||config.cloudEffect==='glass')&&config.depthImage&&config.depthMap&&window.ImpulseDepthParallax){var _pageBgD=document.body.dataset.pageBgColor||'#f5f5f5';document.documentElement.style.cssText+='background:'+_pageBgD+'!important;';if(wrapperEl){wrapperEl.style.zIndex='2';wrapperEl.style.background='transparent';}screens.forEach(function(s){var _sBg=s.dataset.explicitBg||s.style.backgroundColor||s.style.background||'';var _hasExplicitBg=_sBg&&_sBg!=='transparent'&&_sBg!=='rgba(0, 0, 0, 0)';if(!_hasExplicitBg){s.style.background='transparent';s.style.backgroundColor='transparent';}var sec=s.querySelector('.impulse-section,section');if(sec){var _secBg=sec.style.backgroundColor||sec.style.background||'';var _secHasExplicit=_secBg&&_secBg!=='transparent'&&_secBg!=='rgba(0, 0, 0, 0)';if(!_secHasExplicit){sec.style.background='transparent';sec.style.backgroundColor='transparent';}}});document.body.setAttribute('data-depth-image',config.depthImage);document.body.setAttribute('data-depth-map',config.depthMap);document.body.setAttribute('data-depth-strength',config.depthStrength);document.body.setAttribute('data-depth-enabled','1');window.ImpulseDepthParallax.init(document.body);}var hash=window.location.hash.replace('#','');if(hash){var idx=findScreenByHash(hash);if(idx>0)jumpTo(idx);}_hasPageModeBelow=detectPageModeBelow();bindEvents();

        
        function _frHeroPause() {

            

            
            
            if (document.querySelector('.impulse-frosted')) return;
            try { if (window._impulseMotionLava && window._impulseMotionLava.pause) window._impulseMotionLava.pause(); } catch (e) {}
            try { if (window._impulseWave && window._impulseWave.pause) window._impulseWave.pause(); } catch (e) {}
            try { if (window._impulse3D && window._impulse3D.pause) window._impulse3D.pause(); } catch (e) {}
            window.dispatchEvent(new CustomEvent('impulse-pause-effects'));
        }
        function _frHeroResume() {
            try { if (window._impulseMotionLava && window._impulseMotionLava.play) window._impulseMotionLava.play(); } catch (e) {}
            try { if (window._impulseWave && window._impulseWave.play) window._impulseWave.play(); } catch (e) {}

            

            

            try { if (window._impulse3D && window._impulse3D.play) window._impulse3D.play(); } catch (e) {}
            window.dispatchEvent(new CustomEvent('impulse-resume-effects'));
        }
        document.body.classList.add('impulse-hero-visible');
        document.body.classList.remove('impulse-past-hero');
        if ('IntersectionObserver' in window) {
            var _heroIO = new IntersectionObserver(function(entries){
                entries.forEach(function(en){
                    if (en.isIntersecting) {
                        document.body.classList.add('impulse-hero-visible');
                        document.body.classList.remove('impulse-past-hero');
                        _frHeroResume();
                    } else {
                        document.body.classList.remove('impulse-hero-visible');
                        document.body.classList.add('impulse-past-hero');
                        _frHeroPause();
                    }
                });
            }, { threshold: 0, rootMargin: '0px 0px -1px 0px' });
            _heroIO.observe(wrapperEl);
        }

        
        
        var _frWasExited = false;
        function _frHeroSyncByScroll() {
            var sy = window.pageYOffset || document.documentElement.scrollTop || 0;
            var stageH = wrapperEl.offsetHeight || window.innerHeight;

            

            

            

            if (sy >= stageH - 1) {
                document.body.classList.add('impulse-hero-exiting');
                document.body.classList.add('impulse-past-hero');
                document.body.classList.remove('impulse-hero-visible');
                _frWasExited = true;
            } else {
                document.body.classList.remove('impulse-past-hero');
                document.body.classList.add('impulse-hero-visible');
            }

            

            if (sy <= 2 && _frWasExited) {
                document.body.classList.remove('impulse-hero-exiting');
                _frWasExited = false;
            }
        }
        window.addEventListener('scroll', _frHeroSyncByScroll, { passive: true });
        _frHeroSyncByScroll();

        

        

        

        var _frIsEditor = !!window._impulseEditorPreview;
        var _frLastSy = 0, _frFaded = false;
        function _frFadeTick(){
            if (_frIsEditor) return; 
            var sy = window.pageYOffset || document.documentElement.scrollTop || 0;
            var delta = sy - _frLastSy;
            if (Math.abs(delta) >= 2) {
                _frLastSy = sy;
                if (delta > 0 && !_frFaded && sy > 8) {
                    _frFaded = true;
                    document.body.classList.add('impulse-hero-faded');
                } else if (delta < 0 && _frFaded) {
                    _frFaded = false;
                    document.body.classList.remove('impulse-hero-faded');
                }
            }
            requestAnimationFrame(_frFadeTick);
        }
        requestAnimationFrame(_frFadeTick);if(config.navDots)createNavDots();updateScreenNav();document.addEventListener('click',function(e){var link=e.target.closest('.impulse-snav-link');if(!link)return;e.preventDefault();var idx=parseInt(link.dataset.screenIndex);if(!isNaN(idx))goTo(idx);var panel=document.getElementById('impulse-snav-panel');if(panel)panel.classList.remove('open');});document.addEventListener('click',function(e){var panel=document.getElementById('impulse-snav-panel');if(!panel||!panel.classList.contains('open'))return;if(e.target.closest('.impulse-snav-panel')||e.target.closest('.impulse-screen-nav-toggle'))return;panel.classList.remove('open');});
        document.body.style.overflow='hidden';document.body.style.overflowX='hidden';document.body.style.height='var(--imp-vh, 100dvh)';document.body.style.maxWidth='100vw';document.body.style.position='fixed';document.body.style.width='100%';document.documentElement.style.overflow='hidden';document.documentElement.style.height='var(--imp-vh, 100dvh)';document.documentElement.style.overscrollBehavior='none';document.body.classList.add('impulse-screen-mode-active');
        
    }
    
    var _strip=null;function createStrip(){}
    function updateStrip(){}
    function findScreenByHash(hash){for(var i=0;i<screens.length;i++)if((screens[i].dataset.screenHash||'')===hash||hash===String(i))return i;return-1;}
    function jumpTo(index){if(index<0||index>=screens.length)return;screens.forEach(function(s,i){s.style.transition='none';clearStyles(s);if(i===index)applyFocusState(s);else if(i<index)applyExitState(s);else applyEnterState(s);});current=index;try{document.body.setAttribute('data-impulse-screen',String(index));}catch(_e){}updateHash();updateNavDots();updateScreenNav();}

    

    
    
    var _tlProgress = 0;

    
    function _scrollDistancePx(screenEl) {
        var raw = screenEl && screenEl.dataset && screenEl.dataset.scrollDistance;
        if (raw) {
            var m = String(raw).match(/^([\d.]+)(vh|px)?$/);
            if (m) return m[2] === 'px' ? parseFloat(m[1]) : parseFloat(m[1]) / 100 * window.innerHeight;
        }
        return window.innerHeight;
    }
    function _hasTimeline(screenEl) {
        return !!(window.ImpulseTimeline && window.ImpulseTimeline.hasTimeline(screenEl));
    }
    function _applyTimeline(screenEl, progress) {
        if (window.ImpulseTimeline) window.ImpulseTimeline.apply(screenEl, progress);
    }
    
    function _seedTimelineProgress(forward) {
        var screen = screens[current];
        if (!screen || !_hasTimeline(screen)) { _tlProgress = 0; return; }
        _tlProgress = forward ? 0 : 1;
        _applyTimeline(screen, _tlProgress);
    }
    window._impulseSeedTimelineProgress = _seedTimelineProgress;

    function _timelineWheel(e) {
        var screen = screens[current];
        if (!screen || !_hasTimeline(screen)) return false;
        var dist = _scrollDistancePx(screen);
        var before = _tlProgress;
        _tlProgress = Math.max(0, Math.min(1, _tlProgress + e.deltaY / dist));
        _applyTimeline(screen, _tlProgress);

        if (_tlProgress >= 1 && before >= 1 && e.deltaY > 0) return false;
        if (_tlProgress <= 0 && before <= 0 && e.deltaY < 0) return false;
        return true; 
    }

    function bindEvents(){

        

        

        

        
        var _sensAccum = 0;
        var _sensTimer = null;
        function _sensReset() {
            _sensAccum = 0;
            if (_sensTimer) { clearTimeout(_sensTimer); _sensTimer = null; }
        }
        function _destSensitivity(dir) {
            var idx;
            if (dir > 0) {
                idx = current + 1;
                if (idx >= screens.length) idx = config.infinite ? 0 : -1;
            } else {
                idx = current - 1;
                if (idx < 0) return 1; 
            }
            if (idx < 0 || idx >= screens.length) return 1;
            var raw = screens[idx].dataset.revealSensitivity;
            var n = parseInt(raw, 10);
            if (!n || n < 1) return 1;
            return n > 4 ? 4 : n;
        }
        function _gestureAdvance(dir) {
            if (_isReleased) return;
            if (transitioning || cooldownTimer) return;

            
            if (config.bodyScroll === 'classic') {
                if (dir > 0) next(); else prev();
                return;
            }
            _sensAccum += dir;
            if (_sensTimer) clearTimeout(_sensTimer);
            _sensTimer = setTimeout(_sensReset, 1500);
            var sgn = _sensAccum > 0 ? 1 : (_sensAccum < 0 ? -1 : 0);
            if (sgn === 0) return;
            var need = _destSensitivity(sgn);
            if (Math.abs(_sensAccum) < need) return;
            _sensReset();
            if (sgn > 0) next(); else prev();
        }

        document.addEventListener('impulse-screen-changed', _sensReset);

        

        

        
        
        document.addEventListener('wheel',function(e){
        if (_isReleased) return; 
        if (_timelineWheel(e)) { e.preventDefault(); return; }

        
        var s=screens[current];
        if(s&&hasScroll(s)){
            if(e.deltaY>0&&!atBottom(s))return;
            if(e.deltaY<0&&!atTop(s))return;
        }
        e.preventDefault();if(e.deltaY>0)_gestureAdvance(1);else if(e.deltaY<0)_gestureAdvance(-1);},{passive:false});
        document.addEventListener('keydown',function(e){if(_isReleased)return;var _kt=e.target;if(_kt&&(_kt.tagName==='INPUT'||_kt.tagName==='TEXTAREA'||_kt.tagName==='SELECT'||_kt.isContentEditable))return;if(e.key==='ArrowDown'||e.key==='PageDown'||e.key===' '){e.preventDefault();next();}else if(e.key==='ArrowUp'||e.key==='PageUp'){e.preventDefault();prev();}else if(e.key==='Home'){e.preventDefault();goTo(0);}else if(e.key==='End'){e.preventDefault();goTo(screens.length-1);}});

        
        
        var _t={
            sy:0,sx:0,st:0,active:false,
            fingers:0,
            initDist:0,
            pinchTriggered:false
        };
        
        var _drag = {
            active: false,      
            dir: 0,             
            startY: 0,          
            progress: 0,        
            oldEl: null,        
            newEl: null,        
            oldIdx: 0,
            newIdx: 0,
            vh: 0,              
            
            enterScale: 0, exitScale: 0,
            enterBlur: 0, exitBlur: 0,
            hasPerspective: false,
            snapRafId: null     
        };
        function _parseScale(str) {
            var m = str && str.match(/scale\(([^)]+)\)/);
            return m ? parseFloat(m[1]) : 1;
        }
        function _canDragPreset(el) {
            var p = getPreset(el);
            return !p.complex && !p.clip;
        }
        function _dragApply(t) {
            
            var d = _drag;
            
            var oldScale = 1 + t * (d.exitScale - 1);
            var oldOpacity = 1 - t;
            var oldBlur = t * d.exitBlur;
            var pfx = d.hasPerspective ? 'perspective(700px) ' : '';
            d.oldEl.style.transition = 'none';
            d.oldEl.style.transform = pfx + 'scale(' + oldScale.toFixed(4) + ')';
            d.oldEl.style.opacity = oldOpacity.toFixed(3);
            d.oldEl.style.filter = oldBlur > 0.3 ? 'blur(' + oldBlur.toFixed(1) + 'px)' : '';

            var newScale = d.enterScale + t * (1 - d.enterScale);
            var newOpacity = t;
            var newBlur = d.enterBlur * (1 - t);
            d.newEl.style.transition = 'none';
            d.newEl.style.transform = pfx + 'scale(' + newScale.toFixed(4) + ')';
            d.newEl.style.opacity = newOpacity.toFixed(3);
            d.newEl.style.filter = newBlur > 0.3 ? 'blur(' + newBlur.toFixed(1) + 'px)' : '';
        }
        function _dragCommit() {
            var d = _drag, idx = d.newIdx;
            d.active = false;
            
            _swapSceneEnv(screens[idx]);
            if (config.cloudEffect === 'cosmos' && window._impulseCosmosHyperJump) window._impulseCosmosHyperJump();
            else if (config.cloudEffect === 'fireflies' && window._impulseFirefliesHyperJump) window._impulseFirefliesHyperJump();
            current = idx;

            
            
            try { document.body.setAttribute('data-impulse-screen', String(idx)); } catch(_e){}
            
            screens.forEach(function(s, i) {
                if (i === idx) {
                    applyFocusState(s);

                    

                    
                    if (!s.querySelector('.impulse-frosted')) {
                        s.style.animation = 'impulse-snap-in 320ms cubic-bezier(0.4, 0, 0.2, 1)';
                        setTimeout(function() { s.style.animation = ''; }, 320);
                    } else {
                        s.style.animation = '';
                    }
                } else if (i < idx) applyExitState(s);
                else applyEnterState(s);
            });
            updateHash(); updateNavDots(); updateScreenNav();

            

            

            setTimeout(function() {
                transitioning = false;
                cooldownTimer = setTimeout(function() {
                    cooldownTimer = null;
                    if (_pendingNav === 1) { _pendingNav = 0; next(); }
                    else if (_pendingNav === -1) { _pendingNav = 0; prev(); }
                }, config.cooldown);
            }, 320);
            
            if (getDecompChildren(screens[idx]).length > 0) decomposeEnter(screens[idx]);
            document.dispatchEvent(new Event('impulse-screen-changed'));
        }
        function _dragCancel() {
            var d = _drag;
            d.active = false;
            applyFocusState(d.oldEl);
            if (d.dir > 0) applyEnterState(d.newEl);
            else applyExitState(d.newEl);
            transitioning = false;
        }
        function _dragAnimate(from, to, onDone) {
            
            if (_drag.snapRafId) cancelAnimationFrame(_drag.snapRafId);
            var start = performance.now(), dur = 280;
            (function tick() {
                var elapsed = performance.now() - start;
                var t = Math.min(1, elapsed / dur);
                
                var eased = 1 - (1 - t) * (1 - t) * (1 - t);
                var p = from + (to - from) * eased;
                _dragApply(p);
                if (t < 1) { _drag.snapRafId = requestAnimationFrame(tick); }
                else { _drag.snapRafId = null; onDone(); }
            })();
        }

        function touchDist(t){var dx=t[0].clientX-t[1].clientX,dy=t[0].clientY-t[1].clientY;return Math.sqrt(dx*dx+dy*dy);}
        document.addEventListener('touchstart',function(e){
            if (_isReleased) return; 
            _userTapped = true; 
            _t.active=true;
            _t.pinchTriggered=false;
            _t.fingers=e.touches.length;
            if(e.touches.length===1){
                _t.sy=e.touches[0].clientY;
                _t.sx=e.touches[0].clientX;
                _t.st=Date.now();
            } else if(e.touches.length===2){
                _t.initDist=touchDist(e.touches);
                
                if (_drag.active) {
                    _dragAnimate(_drag.progress, 0, _dragCancel);
                }
            }
        },{passive:true});
        document.addEventListener('touchmove',function(e){
            if (_isReleased) return;
            if(!_t.active)return;
            
            if(e.touches.length===2&&!_t.pinchTriggered&&!_drag.active){
                if(!transitioning){
                    var ratio=touchDist(e.touches)/_t.initDist;
                    if(ratio<0.65){_t.pinchTriggered=true;e.preventDefault();next();}
                    else if(ratio>1.5){_t.pinchTriggered=true;e.preventDefault();prev();}
                }
                return;
            }
            
            if(e.touches.length!==1)return;
            var curY=e.touches[0].clientY;

            if(_drag.active){
                
                var rawDelta=(_drag.startY-curY)*_drag.dir;
                _drag.progress=Math.max(0,Math.min(1.15,rawDelta/_drag.vh)); 
                _dragApply(Math.min(1,_drag.progress));
                e.preventDefault();
                return;
            }
            
            if(transitioning)return;
            var dy=_t.sy-curY;
            var dx=_t.sx-e.touches[0].clientX;
            
            if(Math.abs(dy)<12)return;
            if(Math.abs(dy)<Math.abs(dx))return;
            var dir=dy>0?1:-1;
            
            if(dir===1&&current>=screens.length-1&&!config.infinite){
                if(window._impulseNextSequenceUrl)return; 
                return;
            }
            if(dir===-1&&current<=0&&!config.infinite)return;
            
            if(dir===1&&hasScroll(screens[current])&&!atBottom(screens[current]))return;
            if(dir===-1&&hasScroll(screens[current])&&!atTop(screens[current]))return;

            

            var newIdx;
            if(dir===1){
                newIdx=_nextVisibleIndex(current+1);
                if(newIdx>=screens.length){ if(config.infinite){newIdx=_nextVisibleIndex(0);} else return; }
            } else {
                newIdx=_prevVisibleIndex(current-1);
                if(newIdx<0){ if(config.infinite){newIdx=_prevVisibleIndex(screens.length-1);} else return; }
            }
            if(newIdx===current||newIdx<0||newIdx>=screens.length)return;
            if(screens[newIdx].dataset.entrancePreset&&screens[newIdx].dataset.entrancePreset!=='none')return;

            
            
            if(!_canDragPreset(screens[newIdx]))return;
            
            var p=getPreset(screens[newIdx]);
            _drag.active=true;
            _drag.dir=dir;
            _drag.startY=_t.sy;
            _drag.vh=window.innerHeight*0.55; 
            _drag.oldEl=screens[current];
            _drag.newEl=screens[newIdx];
            _drag.oldIdx=current;
            _drag.newIdx=newIdx;
            _drag.enterScale=_parseScale(p.enter.transform);
            _drag.exitScale=_parseScale(p.exit.transform);
            _drag.enterBlur=parseFloat(p.enter.blur)||0;
            _drag.exitBlur=parseFloat(p.exit.blur)||0;
            _drag.hasPerspective=!!(p.enter.transform&&p.enter.transform.indexOf('perspective')!==-1);
            _drag.progress=0;
            transitioning=true;
            
            _drag.newEl.style.transition='none';
            _drag.newEl.style.visibility='visible';
            _drag.newEl.style.pointerEvents='none';
            if(dir>0){_drag.newEl.style.zIndex='1';_drag.oldEl.style.zIndex='3';}
            else{_drag.newEl.style.zIndex='3';_drag.oldEl.style.zIndex='1';}
            if(window.impulsePreWarmScreen)window.impulsePreWarmScreen(_drag.newEl);
            e.preventDefault();
        },{passive:false});
        document.addEventListener('touchend',function(e){
            if (_isReleased) return;
            if(!_t.active&&!_drag.active)return;
            _t.active=false;
            
            if(_drag.active){
                var p=_drag.progress;
                var endY=e.changedTouches[0].clientY;
                var vel=Math.abs(_drag.startY-endY)/Math.max(Date.now()-_t.st,1);
                
                if(p>=0.4||(p>=0.15&&vel>0.4)){
                    if(navigator.vibrate){try{navigator.vibrate(6);}catch(ex){}}
                    _dragAnimate(Math.min(p,1),1,_dragCommit);
                } else {
                    _dragAnimate(Math.min(p,1),0,_dragCancel);
                }
                return;
            }
            
            if(_t.pinchTriggered||_t.fingers!==1)return;
            var fEndY=e.changedTouches[0].clientY;
            var fEndX=e.changedTouches[0].clientX;
            var fdy=_t.sy-fEndY;
            var fdx=_t.sx-fEndX;
            var fdt=Date.now()-_t.st;
            if(Math.abs(fdy)<Math.abs(fdx))return;
            if(Math.abs(fdy)<15&&fdt>150)return;
            if(fdt>1200)return;
            var fvel=Math.abs(fdy)/Math.max(fdt,1);
            if(Math.abs(fdy)<15&&fvel<0.3)return;

            
            if(fdy>0)_gestureAdvance(1);else _gestureAdvance(-1);
        },{passive:true});
        window.addEventListener('hashchange',function(){var h=window.location.hash.replace('#','');if(h){var idx=findScreenByHash(h);if(idx>=0&&idx!==current)goTo(idx);}});

        
        var _pushMouseY=0.5, _pushGyroY=0.5;
        var _pushHoldStart=0, _pushDir=0; 
        var _pushCooldown=0;
        var _pushHoldMs=400; 
        document.addEventListener('mousemove',function(e){
            _pushMouseY=e.clientY/window.innerHeight;
        });
        var _pushGyroBaseB=null;
        if (!_isTouchDevice) {
        window.addEventListener('deviceorientation',function(e){
            if(e.beta===null)return;
            if(_pushGyroBaseB===null)_pushGyroBaseB=e.beta||0;
            
            _pushGyroY=0.5+Math.max(-0.5,Math.min(0.5,((e.beta||0)-_pushGyroBaseB)/30));
        },{passive:true});
        }
        var _isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        (function pushLoop(){
            requestAnimationFrame(pushLoop);

            if (_isTouchDevice) return;
            var sens=config.mouseSensLevel||0;
            if(sens<=0||screens.length<2)return;
            if(transitioning)return;
            var now=Date.now();
            if(now<_pushCooldown)return;
            
            var y=_pushMouseY;
            var gy=_pushGyroY;
            if(Math.abs(gy-0.5)>Math.abs(y-0.5))y=gy;
            
            var edgeZone=0.04+sens*0.14;
            var dir=0;
            if(y<edgeZone)dir=-1; 
            else if(y>1-edgeZone)dir=1; 
            if(dir===0||dir!==_pushDir){
                _pushDir=dir;
                _pushHoldStart=dir?now:0;
                return;
            }
            
            if(_pushHoldStart&&now-_pushHoldStart>=_pushHoldMs){
                _pushHoldStart=0;
                _pushDir=0;
                _pushCooldown=now+config.duration+config.cooldown+200;
                if(dir>0)next();else prev();
            }
        })();

    }
    function updateHash(){var h=screens[current].dataset.screenHash||'';if(h)history.replaceState(null,'','#'+h);else if(current===0)history.replaceState(null,'',window.location.pathname);}
    var dotsContainer=null;

    
    
    function createNavDots(){dotsContainer=document.createElement('div');dotsContainer.className='impulse-screen-dots';dotsContainer.setAttribute('style','position:fixed;right:20px;top:50%;transform:translateY(-50%);z-index:9999;display:flex;flex-direction:column;gap:10px;');screens.forEach(function(s,i){if(_isSkippedScreen(i))return;var d=document.createElement('button');d.className='impulse-screen-dot'+(i===current?' active':'');d.dataset.screenIndex=i;d.setAttribute('style','width:10px;height:10px;border-radius:50%;border:1.5px solid rgba(255,255,255,0.6);background:'+(i===current?'rgba(255,255,255,0.9)':'transparent')+';cursor:pointer;padding:0;transition:all 0.3s ease-in-out;');d.setAttribute('aria-label','Screen '+(i+1));d.addEventListener('click',function(){goTo(i);});dotsContainer.appendChild(d);});document.body.appendChild(dotsContainer);}
    function updateNavDots(){if(!dotsContainer)return;dotsContainer.querySelectorAll('.impulse-screen-dot').forEach(function(d){var i=parseInt(d.dataset.screenIndex,10);var active=(i===current);d.classList.toggle('active',active);d.style.background=active?'rgba(255,255,255,0.9)':'transparent';});}
    function updateScreenNav(){var nameEl=document.getElementById('impulse-snav-current');if(nameEl){var links=document.querySelectorAll('.impulse-snav-link');var name='';links.forEach(function(l,i){var isActive=parseInt(l.dataset.screenIndex)===current;l.classList.toggle('active',isActive);if(isActive)name=l.textContent;});if(name)nameEl.value=name;}var nav=document.querySelector('.impulse-screen-nav');if(nav&&nav.dataset.autoColor==='1'&&screens[current]){var sc=screens[current];var bg=getComputedStyle(sc).backgroundColor||getComputedStyle(document.body).backgroundColor;var m=bg.match(/\d+/g);if(m&&m.length>=3){var lum=(0.299*parseInt(m[0])+0.587*parseInt(m[1])+0.114*parseInt(m[2]))/255;var col=lum>0.6?'#333333':'#ffffff';nav.querySelectorAll('.impulse-screen-nav-logo a,.impulse-screen-nav-toggle,.impulse-snav-link').forEach(function(el){el.style.color=col;});}}}
    function injectStyles(){var style=document.createElement('style');style.textContent='.impulse-screen:not(.impulse-screen-active) .impulse-la-asset{opacity:0!important}.impulse-screen .impulse-el:has(.impulse-logo-animator){overflow:visible!important}.impulse-screen .impulse-logo-animator{overflow:visible!important}.impulse-screen .impulse-section:has(.impulse-logo-animator){overflow:visible!important}.impulse-screen .impulse-container:has(.impulse-logo-animator){overflow:visible!important}.impulse-screen-wrapper{position:fixed;top:0;left:0;width:100%;width:100vw;height:100%;height:100dvh;overflow:hidden;perspective:1200px;touch-action:none}.impulse-screen{box-sizing:border-box;backface-visibility:hidden;-webkit-backface-visibility:hidden;border:none!important;outline:none!important;box-shadow:none!important;overflow:hidden;max-width:100vw}.impulse-screen .impulse-section:has(.impulse-logo-animator),.impulse-screen .impulse-el:has(.impulse-logo-animator),.impulse-screen .impulse-logo-animator{overflow:visible!important}.impulse-screen>.impulse-section>.impulse-container{max-width:none!important;width:100%!important;overflow-x:hidden}.impulse-screen .impulse-el[data-type="image"] img{max-height:100dvh;object-fit:contain;width:auto;max-width:100%}.impulse-screen .impulse-el[data-type="image"] .impulse-image-wrapper{max-height:100dvh}.impulse-screen::-webkit-scrollbar{display:none}.impulse-screen-dot:hover{background:rgba(255,255,255,0.5)!important;transform:scale(1.3)}@keyframes impulse-snap-in{0%{transform:scale(1) translateZ(0)}55%{transform:scale(1.013) translateZ(0)}100%{transform:scale(1) translateZ(0)}}'+

        'body.impulse-scroll-classic #impulse-fx-canvas,body.impulse-scroll-classic #impulse-3d-canvas,body.impulse-scroll-classic #impulse-tunnel-canvas,body.impulse-scroll-classic #impulse-motion-lava-canvas,body.impulse-scroll-classic #impulse-wave-canvas,body.impulse-scroll-classic #impulse-depth-canvas{display:none!important}';
        document.head.appendChild(style);}

    function initTunnel(){

        
        if (config.bodyScroll === 'classic') return;
        if (!window._tunnelGen) window._tunnelGen = 0;
        helixRot = 0;
        _activeEnvCanvas = null; 

        if (INSTINCTOR_ENV_WM) requestAnimationFrame(_ensureEnvWatermark);
        var cv=document.getElementById('impulse-tunnel-canvas');if(!cv)return;
        var _isAmbient=['lava','wave','bubbles','particles','crystal','blob','wormhole','fireflies','plexus','fractal','caustics','glass','bubble','flow','aurora','aura','topography','neon','noise','dots','ripple','swirl','kaleidoscope','columns','nebula','agate','storm','lens','asteroid','grid'].indexOf(config.cloudEffect)!==-1;
        
        var _forceWhite = [];
        var _forceBlack = ['cosmos','neon','caustics','glass','fractal','bubble','flow','aurora','aura','topography','lava','noise','ripple','swirl','kaleidoscope','columns','lens','asteroid','particles'];
        var _isPaletteCloud = false;
        var _isWax = false; 
        var _pageBg = document.body.dataset.pageBgColor || (wrapperEl && wrapperEl.dataset.pageBgColor) || '#f5f5f5';
        var _3dEffects = ['cosmos','bubbles','particles','crystal','blob','wormhole','fireflies','plexus','fractal','caustics','glass','bubble','flow','aurora','topography','neon','columns','asteroid','grid'];
        var _is3dEffect = _3dEffects.indexOf(config.cloudEffect) !== -1;

        

        

        

        if (config.tunnel || _forceBlack.indexOf(config.cloudEffect) !== -1) {
            document.documentElement.style.cssText += 'background:#000000!important;';
        } else if (_forceWhite.indexOf(config.cloudEffect) !== -1) {
            document.documentElement.style.cssText += 'background:#ffffff!important;';
        } else {
            document.documentElement.style.cssText += 'background:' + _pageBg + '!important;';
        }
        
        var BLUR_PAD = 16;
        document.body.appendChild(cv);
        _activeEnvCanvas = cv; 
        cv.style.cssText='position:fixed;top:-'+BLUR_PAD+'px;left:-'+BLUR_PAD+'px;width:calc(100% + '+BLUR_PAD*2+'px);height:calc(100% + '+BLUR_PAD*2+'px);z-index:0;pointer-events:none;background:transparent;';
        if(wrapperEl)wrapperEl.style.zIndex='2';
        if((_isAmbient) && wrapperEl) wrapperEl.style.background='transparent';
        if(_isAmbient||_isPaletteCloud){screens.forEach(function(s){var _sBg=s.style.backgroundColor||s.style.background||'';if(!_sBg||_sBg==='transparent'||_sBg==='rgba(0, 0, 0, 0)'){s.dataset.origBg=s.style.background||'';s.style.background='transparent';}var sec=s.querySelector('.impulse-section,section');if(sec){var _secBg=sec.style.backgroundColor||sec.style.background||'';var _secImg=sec.querySelector('.impulse-section-bg-frameloop,.impulse-section-bg-overlay-img');if(!_secBg||_secBg==='transparent'||_secBg==='rgba(0, 0, 0, 0)'||_secImg){sec.dataset.origBg=sec.style.background||sec.style.backgroundColor||'';sec.style.background='transparent';sec.style.backgroundColor='transparent';}}});}

        if (config.cloudEffect === 'lava' && window.ImpulseMotionLava) {
            var lvCv = document.createElement('canvas');
            lvCv.id = 'impulse-motion-lava-canvas';
            lvCv.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:0;pointer-events:none;';
            document.body.insertBefore(lvCv, document.body.firstChild);
            if(wrapperEl) wrapperEl.style.zIndex = '2';
            var _lvC1, _lvC2, _lvC3, _lvC4;
            if (_isWax) {
            } else {
                _lvC1 = (wrapperEl && wrapperEl.dataset.lavaColor1) || '#ef008f';
                _lvC2 = (wrapperEl && wrapperEl.dataset.lavaColor2) || '#6ec3f4';
                _lvC3 = (wrapperEl && wrapperEl.dataset.lavaColor3) || '#7038ff';
                _lvC4 = (wrapperEl && wrapperEl.dataset.lavaColor4) || '#ffba27';
            }
            var _lvSpd = ((parseInt((wrapperEl && wrapperEl.dataset.lavaSpeed) || '10')) || 10) / 10;

            
            
            var _lvFreq   = 1.0;
            var _lvBaseAmp = 320;
            
            var _lvInt = ((parseInt((wrapperEl && wrapperEl.dataset.lavaIntensity) || '5')) || 5);
            var _lvAmp = Math.round(_lvBaseAmp * (0.5 + (_lvInt - 1) / 9.0));
            var _lvShadow = 1.0;
            if (_isWax) _lvSpd *= 0.25;
            _activeEnvCanvas = lvCv;
            window._impulseMotionLava = new ImpulseMotionLava(lvCv, {
                colors: [_lvC1, _lvC2, _lvC3, _lvC4],
                speed: _lvSpd,
                amp: _lvAmp,
                noiseFreq: _lvFreq,
                shadowScale: _lvShadow
            });
            window._impulseMotionLava.play();
        }

        if (config.cloudEffect === 'wave' && window.ImpulseWave) {
            var wvCv = document.createElement('canvas');
            wvCv.id = 'impulse-wave-canvas';
            wvCv.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:0;pointer-events:none;';
            document.body.insertBefore(wvCv, document.body.firstChild);
            if(wrapperEl) wrapperEl.style.zIndex = '2';
            var _wvC1 = (wrapperEl && wrapperEl.dataset.waveColor1) || '#ef008f';
            var _wvC2 = (wrapperEl && wrapperEl.dataset.waveColor2) || '#6ec3f4';
            var _wvC3 = (wrapperEl && wrapperEl.dataset.waveColor3) || '#7038ff';
            var _wvC4 = (wrapperEl && wrapperEl.dataset.waveColor4) || '#ffba27';
            var _wvSpd = ((parseInt((wrapperEl && wrapperEl.dataset.waveSpeed) || '10')) || 10) / 10;
            var _wvPreset = (wrapperEl && wrapperEl.dataset.wavePreset) || 'flow';
            var _wvIntensity = ((parseInt((wrapperEl && wrapperEl.dataset.waveIntensity) || '10')) || 10) / 10;
            _activeEnvCanvas = wvCv;
            window._impulseWave = new ImpulseWave(wvCv, {
                colors: [_wvC1, _wvC2, _wvC3, _wvC4],
                speed: _wvSpd,
                preset: _wvPreset,
                intensity: _wvIntensity
            });
            window._impulseWave.play();
            
            var _wvBg = (wrapperEl && wrapperEl.dataset['3dBgColor']) || '';
            if (!_wvBg || _wvBg.charAt(0) !== '#') _wvBg = (document.body && document.body.getAttribute('data-page-bg-color')) || '';
            if (window._impulseWave.updateBgColor && _wvBg && _wvBg.charAt(0) === '#') window._impulseWave.updateBgColor(_wvBg);
        }

        if (_is3dEffect && window.Impulse3D) {
            var i3dCv = document.createElement('canvas');
            i3dCv.id = 'impulse-3d-canvas';
            i3dCv.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:0;pointer-events:none;';
            document.body.insertBefore(i3dCv, document.body.firstChild);
            if(wrapperEl) wrapperEl.style.zIndex = '1';
            
            var _3dC1raw = wrapperEl && wrapperEl.dataset['3dColor1'];
            var _3dC2raw = wrapperEl && wrapperEl.dataset['3dColor2'];
            var _3dC3raw = wrapperEl && wrapperEl.dataset['3dColor3'];
            var _3dC4raw = wrapperEl && wrapperEl.dataset['3dColor4'];
            var _3dSpd = ((parseInt((wrapperEl && wrapperEl.dataset['3dSpeed']) || '5')) || 5) / 10;
            var _3dPreset = (wrapperEl && wrapperEl.dataset['3dPreset']) || '';
            var _3dIntensity = ((parseInt((wrapperEl && wrapperEl.dataset['3dIntensity']) || '5')) || 5) / 10;
            var _3dCount = parseInt((wrapperEl && wrapperEl.dataset['3dCount']) || '7') || 7;
            var _3dVarRaw = wrapperEl && wrapperEl.dataset['3dVariation'];
            var _3dVariation = (_3dVarRaw !== undefined && _3dVarRaw !== '') ? parseInt(_3dVarRaw) : 3;
            var _3dDenRaw = wrapperEl && wrapperEl.dataset['3dDensity'];
            var _3dDensity = (_3dDenRaw !== undefined && _3dDenRaw !== '') ? parseInt(_3dDenRaw) : 7;
            var _3dHaloRaw = wrapperEl && wrapperEl.dataset['3dHalo'];
            var _3dHalo = (_3dHaloRaw !== undefined && _3dHaloRaw !== '') ? parseInt(_3dHaloRaw) : 4;
            var _3dSens = parseFloat((wrapperEl && wrapperEl.dataset.mouseSensLevel) || '0.5');
            _activeEnvCanvas = i3dCv;
            var _3dInitOpts = {
                effect: config.cloudEffect,
                speed: _3dSpd,
                preset: _3dPreset || undefined,
                intensity: _3dIntensity,
                count: _3dCount,
                variation: _3dVariation,
                density: _3dDensity,
                halo: _3dHalo,
                sensitivity: _3dSens
            };
            
            var _hasUserColors = _3dC1raw || _3dC2raw || _3dC3raw || _3dC4raw;
            var _isGreyDefaultFill = (
                _3dC1raw === '#333333' &&
                _3dC2raw === '#999999' &&
                _3dC3raw === '#666666' &&
                _3dC4raw === '#cccccc'
            );
            var _omitColors = !_hasUserColors || (_isGreyDefaultFill && _3dPreset);
            if (!_omitColors) {
                _3dInitOpts.colors = [
                    _3dC1raw || '#333333',
                    _3dC2raw || '#999999',
                    _3dC3raw || '#666666',
                    _3dC4raw || '#cccccc'
                ];
            }
            window._impulse3D = Impulse3D.init(i3dCv, _3dInitOpts);
            
            var _bgCtrl3d = ['particles','crystal','blob','plexus','bubbles','grid','columns','asteroid'];
            if (window._impulse3D && _bgCtrl3d.indexOf(config.cloudEffect) !== -1) {
                
                var _activeP = window._impulse3D._activePreset;
                var _presetForceBg = (_activeP && _activeP.darkBg === false) ? '#ffffff' : null;

                

                var _3dBgAttr = (wrapperEl && wrapperEl.dataset['3dBgColor']) || '';
                var _effectiveBg3d = _presetForceBg || (_3dBgAttr.charAt(0) === '#' ? _3dBgAttr : _pageBg);
                if (window._impulse3D.updateBgColor) window._impulse3D.updateBgColor(_effectiveBg3d);
                
                if (config.cloudEffect === 'particles' && window._impulse3D.updateBlendMode) {
                    window._impulse3D.updateBlendMode(_effectiveBg3d !== '#ffffff');
                }
            }
        }

        
        var _fxEffects = ['fractal','caustics','glass','bubble','flow','aurora','clouds','aura','topography','neon','noise','dots','ripple','swirl','kaleidoscope','membrane','nebula','agate','storm','lens'];
        var _isFxEffect = _fxEffects.indexOf(config.cloudEffect) !== -1;
        if (_isFxEffect && window.ImpulseFX) {
            var fxCv = document.createElement('canvas');
            fxCv.id = 'impulse-fx-canvas';
            fxCv.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:0;pointer-events:none;';
            document.body.insertBefore(fxCv, document.body.firstChild);
            if(wrapperEl) wrapperEl.style.zIndex = '2';
            var _fxC1 = (wrapperEl && wrapperEl.dataset['3dColor1']) || '#000000';
            var _fxC2 = (wrapperEl && wrapperEl.dataset['3dColor2']) || '#333333';
            var _fxC3 = (wrapperEl && wrapperEl.dataset['3dColor3']) || '#ffffff';

            
            var _fxSpd = config.cloudEffect === 'glass'
                ? 0.5
                : ((parseInt((wrapperEl && wrapperEl.dataset['3dSpeed']) || '10')) || 10) / 10;
            var _fxInt = ((parseInt((wrapperEl && wrapperEl.dataset['3dIntensity']) || '5')) || 5) / 10;
            var _fxSens = parseFloat((wrapperEl && wrapperEl.dataset.mouseSensLevel) || '0.5');

            var _fxOuterOp = wrapperEl && wrapperEl.dataset.outerOpacity != null && wrapperEl.dataset.outerOpacity !== ''
                ? Math.max(0, Math.min(100, parseInt(wrapperEl.dataset.outerOpacity))) / 100
                : 1.0;
            _activeEnvCanvas = fxCv;

            
            
            var _nebulaMode = (config.cloudEffect === 'nebula');
            var _fxInitOpts = {
                effect: config.cloudEffect,
                speed: _fxSpd,
                intensity: _fxInt,
                opacity: 1.0,
                outerOpacity: _fxOuterOp,
                color1: _fxC1,
                color2: _fxC2,
                bgColor: (wrapperEl && wrapperEl.dataset['3dBgColor'] && wrapperEl.dataset['3dBgColor'].charAt(0)==='#') ? wrapperEl.dataset['3dBgColor'] : ((_pageBg && _pageBg.charAt && _pageBg.charAt(0)==='#') ? _pageBg : '#000000'),
                mouse: _fxSens,
                bgImage: (wrapperEl && (wrapperEl.dataset.depthImage || wrapperEl.dataset.prismBg)) || '',
                shape: parseInt((wrapperEl && wrapperEl.dataset.prismShape) || '0')
            };
            if (_nebulaMode) _fxInitOpts.color3 = _fxC3;
            window._impulseFX = ImpulseFX.init(fxCv, _fxInitOpts);
        }

        var _oldSpaceW=document.getElementById('impulse-space-wrap');if(_oldSpaceW)_oldSpaceW.remove();

        var ctx=cv.getContext('2d');
        var W,H,cx,cy;

        var cvFar =document.createElement('canvas');
        var cvMid =document.createElement('canvas');
        var cvNear=document.createElement('canvas');
        var ctxFar =cvFar.getContext('2d');
        var ctxMid =cvMid.getContext('2d');
        var ctxNear=cvNear.getContext('2d');
        
        var _isMobileDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        
        if (_isMobileDevice) {
            [ctx, ctxFar, ctxMid, ctxNear].forEach(function(c) {
                try { Object.defineProperty(c, 'shadowBlur', { set: function(){}, get: function(){ return 0; }, configurable: true }); } catch(e) {}
            });
        }
        
        var svgNS = 'http://www.w3.org/2000/svg';
        var svgCloud = document.createElementNS(svgNS, 'svg');
        svgCloud.setAttribute('xmlns', svgNS);
        svgCloud.setAttribute('id', 'impulse-cloud-svg');
        
        var _actualBg = (_forceBlack.indexOf(config.cloudEffect) !== -1 || config.tunnel) ? '#000000' : (_forceWhite.indexOf(config.cloudEffect) !== -1) ? '#ffffff' : _pageBg;
        var _bgc = (_actualBg || '#000000').replace(/\s/g,'');
        var _bghx = _bgc.charAt(0)==='#' ? [parseInt(_bgc.slice(1,3)||'0',16),parseInt(_bgc.slice(3,5)||'0',16),parseInt(_bgc.slice(5,7)||'0',16)] : [0,0,0];
        var _bgDark = (_bghx[0]*0.299+_bghx[1]*0.587+_bghx[2]*0.114) < 80;
        
        var cvCloud = null, ctxCloud = null;
        if (_isMobileDevice && _isPaletteCloud) {
            cvCloud = document.createElement('canvas');
            cvCloud.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:-1;pointer-events:none;filter:blur(50px);will-change:transform;';
            document.body.appendChild(cvCloud);
            svgCloud.style.display = 'none';
        } else {
            svgCloud.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:-1;pointer-events:none;mix-blend-mode:normal;overflow:visible;';
        }
        var svgDefs = document.createElementNS(svgNS, 'defs');
        var svgFilter = document.createElementNS(svgNS, 'filter');
        svgFilter.setAttribute('id', 'impulse-cloud-blur');
        svgFilter.setAttribute('x', '-150%'); svgFilter.setAttribute('y', '-150%');
        svgFilter.setAttribute('width', '400%'); svgFilter.setAttribute('height', '400%');
        var svgBlur = document.createElementNS(svgNS, 'feGaussianBlur');
        svgBlur.setAttribute('stdDeviation', '130');
        svgFilter.appendChild(svgBlur);
        svgDefs.appendChild(svgFilter);
        svgCloud.appendChild(svgDefs);
        var svgG = document.createElementNS(svgNS, 'g');
        svgG.setAttribute('filter', 'url(#impulse-cloud-blur)');
        svgCloud.appendChild(svgG);
        var svgCircles = [];
        for (var _i=0; _i<40; _i++) {
            var _ce = document.createElementNS(svgNS, 'ellipse');
            _ce.setAttribute('opacity', '0');
            svgG.appendChild(_ce);
            svgCircles.push(_ce);
        }
        document.body.appendChild(svgCloud);

        function resize(){
            W=cv.width=window.innerWidth+BLUR_PAD*2;
            H=cv.height=window.innerHeight+BLUR_PAD*2;
            cx=W/2; cy=H/2;
            cvFar.width=cvMid.width=cvNear.width=W;
            cvFar.height=cvMid.height=cvNear.height=H;
            if(cvCloud){cvCloud.width=window.innerWidth;cvCloud.height=window.innerHeight;ctxCloud=cvCloud.getContext('2d');}
            
        }
        window.addEventListener('resize',resize,{passive:true});resize();

        var FOV   = 600;
        var NPART = 180;
        var Z_NEAR= 40,  Z_FAR = 2800;
        
        var FOCAL_Z = Z_NEAR + (Z_FAR - Z_NEAR) * 0.35;
        
        var Z_MID_IN  = Z_NEAR + (Z_FAR - Z_NEAR) * 0.055;  
        var Z_MID_OUT = Z_NEAR + (Z_FAR - Z_NEAR) * 0.60;  

        var NCLOUD = _isMobileDevice ? 10 : 15;        
        activeCloudEffect = config.tunnel ? 'none' : (config.cloudEffect || 'none');

        function hslToRgb(h, s, l) {
            h /= 360; s /= 100; l /= 100;
            var r, g, b;
            if (s === 0) { r = g = b = l; }
            else {
                var q = l < 0.5 ? l*(1+s) : l+s-l*s;
                var p = 2*l - q;
                function hue2rgb(p,q,t){
                    if(t<0)t+=1; if(t>1)t-=1;
                    if(t<1/6)return p+(q-p)*6*t;
                    if(t<1/2)return q;
                    if(t<2/3)return p+(q-p)*(2/3-t)*6;
                    return p;
                }
                r = hue2rgb(p, q, h+1/3);
                g = hue2rgb(p, q, h);
                b = hue2rgb(p, q, h-1/3);
            }
            return [r, g, b];
        }

        var CLOUD_FADE_SPEED = 0.006; 

        var clouds = [];
        var PALETTE_CLOUDS = []; 
        var isPaletteCloud = PALETTE_CLOUDS.indexOf(activeCloudEffect) !== -1;
        if (isPaletteCloud) {
            for (var ci = 0; ci < NCLOUD; ci++) clouds.push(spawnCloud(true));
        }

        
        var neonMouseX = 0, neonMouseY = 0; 
        var _neonMouseSens = config.mouseSensLevel;
        var _neonTargX = 0, _neonTargY = 0;
        (function(){
            var el = wrapperEl || document.body;
            el.addEventListener('mousemove', function(e){
                var r = el.getBoundingClientRect();
                _neonTargX = ((e.clientX - r.left) / r.width  - 0.5) * 2;
                _neonTargY = ((e.clientY - r.top)  / r.height - 0.5) * 2;
            }, {passive:true});
            
            if (window._impulseGyro) {
                window._impulseGyro.register(function(e) {
                    if (e.gamma != null) _neonTargX = Math.max(-1, Math.min(1, e.gamma / 30));
                    if (e.beta  != null) _neonTargY = Math.max(-1, Math.min(1, (e.beta - 30) / 30));
                });
            }
        })();

        var NCOMET = 2;
        function spawnComet(init) {
            var ang = Math.random() * Math.PI * 2;
            var rad = 10 + Math.random() * 260;
            var z   = init ? (Z_NEAR*3 + Math.random() * (Z_FAR - Z_NEAR*3)) : Z_FAR;
            var sc0 = FOV / z;
            return { x: Math.cos(ang)*rad, y: Math.sin(ang)*rad, z: z,
                     psx: cx + Math.cos(ang)*rad*sc0,
                     psy: cy + Math.sin(ang)*rad*sc0,
                     width: 0.8 + Math.random() * 1.0,
                     bright: 0.85 + Math.random() * 0.15 };
        }
        var comets = [];
        for (var _ci=0; _ci<NCOMET; _ci++) comets.push(spawnComet(true));

                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+')';
        }

        var pointer = { x: 0, y: 0, tx: 0, ty: 0 };
        document.addEventListener('mousemove', function(e) {
            pointer.tx = (e.clientX / (window.innerWidth  || 1)) * 2 - 1;
            pointer.ty = (e.clientY / (window.innerHeight || 1)) * 2 - 1;
        }, { passive: true });

        
        var neonHueClock = 0;
        var neonHueManual = -1;
        function getNeonHue(off){ return neonHueManual>=0 ? (neonHueManual+(off||0))%360 : (neonHueClock*0.18+(off||0))%360; }

        var frameCount=0;
        var _myGen = ++window._tunnelGen;  
        function frame(){
            if (window._tunnelGen !== _myGen) return;  
            _rafRunning = true;

            if(W===0||H===0){resize();return;}

            frameCount++;
            neonHueClock++;
            neonHueManual = parseInt(wrapperEl.dataset.neonHue || '-1');
            helixRot += 0.016;

            var _sl2=parseFloat(wrapperEl.dataset.mouseSensLevel||'0');if(_sl2>0){neonMouseX+=(_neonTargX*_sl2-neonMouseX)*0.06;neonMouseY+=(_neonTargY*_sl2-neonMouseY)*0.06;}else{neonMouseX=0;neonMouseY=0;}
            var SPD = 1.2 * config.tunnelSpeed;
            var CLOUD_SPD = config.tunnelSpeed * 8.0; 
            ctx.clearRect(0,0,W,H); 

                
            if(cvFar.width>0&&cvFar.height>0){
                if (_isMobileDevice) {

                    ctx.globalAlpha=1;
                    ctx.drawImage(cvFar,0,0);
                } else {
                    
                    ctx.filter='blur(6px)';
                    ctx.globalAlpha=1;
                    ctx.drawImage(cvFar,0,0);
                }

                if (isPaletteCloud && clouds.length > 0) {
                    var Z_FADE_OUT = Z_NEAR + (Z_FAR - Z_NEAR) * 0.12;
                    var cloudIntensity = Math.max(0, Math.min(1, (config.intensity !== undefined ? config.intensity : 50) / 100));
                    for (var ci = 0; ci < clouds.length; ci++) {
                        var cl = clouds[ci];
                        cl.z -= CLOUD_SPD;
                        if (cl.z < Z_FADE_OUT) cl.dying = true;
                        if (cl.dying) { cl.opacity -= CLOUD_FADE_SPEED * 2.5; }
                        else if (cl.fadeDelay > 0) { cl.fadeDelay--; }
                        else          { cl.opacity = Math.min(1, cl.opacity + CLOUD_FADE_SPEED); }
                    }
                    if (ctxCloud) {
                        
                        var cW=cvCloud.width, cH=cvCloud.height, cCX=cW/2, cCY=cH/2;
                        ctxCloud.clearRect(0,0,cW,cH);
                        for (var ci2 = 0; ci2 < clouds.length; ci2++) {
                            var cl2 = clouds[ci2];
                            var fade2 = Math.max(0, Math.min(1, cl2.opacity)) * cl2.density;
                            if (fade2 < 0.008) continue;
                            var sc2 = FOV / cl2.z;
                            var sx2 = cCX + cl2.x * sc2;
                            var sy2 = cCY + cl2.y * sc2;
                            var srx2 = cl2.worldR * sc2 * 1.8;
                            var sry2 = srx2 * cl2.ryRatio;
                            if (srx2 < 2) continue;
                            ctxCloud.save();
                            ctxCloud.translate(sx2, sy2);
                            ctxCloud.rotate(cl2.rot * Math.PI / 180);
                            ctxCloud.globalAlpha = fade2 * cloudIntensity;
                            var rgb2 = hslToRgb(cl2.h, cl2.s, cl2.l);
                            ctxCloud.fillStyle = 'rgb(' + Math.round(rgb2[0]*255) + ',' + Math.round(rgb2[1]*255) + ',' + Math.round(rgb2[2]*255) + ')';
                            ctxCloud.beginPath();
                            ctxCloud.ellipse(0, 0, srx2, sry2, 0, 0, Math.PI * 2);
                            ctxCloud.fill();
                            ctxCloud.restore();
                        }
                    } else {
                        
                        svgCloud.style.display = 'block';
                        for (var ci3 = 0; ci3 < clouds.length; ci3++) {
                            var cl3 = clouds[ci3];
                            var fade3 = Math.max(0, Math.min(1, cl3.opacity)) * cl3.density;
                            var sc3 = FOV / cl3.z;
                            var sx3 = cx + cl3.x * sc3;
                            var sy3 = cy + cl3.y * sc3;
                            var srx3 = cl3.worldR * sc3;
                            var sry3 = srx3 * cl3.ryRatio;
                            var el = svgCircles[ci3];
                            if (ci3 >= svgCircles.length) continue;
                            if (fade3 < 0.008 || srx3 < 2) {
                                el.setAttribute('opacity', '0');
                            } else {
                                var tr = 'rotate('+cl3.rot.toFixed(1)+','+sx3.toFixed(1)+','+sy3.toFixed(1)+')';
                                el.setAttribute('cx', sx3.toFixed(1)); el.setAttribute('cy', sy3.toFixed(1));
                                el.setAttribute('rx', srx3.toFixed(1)); el.setAttribute('ry', sry3.toFixed(1));
                                el.setAttribute('transform', tr);
                                el.setAttribute('opacity', (fade3 * cloudIntensity).toFixed(3));
                                if (el._h !== cl3.h) {
                                    el.setAttribute('fill', 'hsl('+cl3.h+','+cl3.s+'%,'+cl3.l+'%)');
                                    el._h = cl3.h;
                                }
                            }
                        }
                    }
                } else {
                    svgCloud.style.display = 'none';
                }

                if (!_isMobileDevice) ctx.filter='none';
                ctx.globalAlpha=1;
                ctx.drawImage(cvMid,0,0);
                ctx.drawImage(cvNear,0,0);
                ctxFar.clearRect(0,0,W,H);
                ctxMid.clearRect(0,0,W,H);
                ctxNear.clearRect(0,0,W,H);

                

                

                

                

                
                var _isBW = ['bw_matrix','bw_grid3d','bw_blueprint','bw_marble','bw_diamonds'].indexOf(activeCloudEffect) !== -1;
                if (_isBW) {
                    var bwFG = _bgDark ? 'rgba(255,255,255,' : 'rgba(0,0,0,';
                    var _bwAccent = (wrapperEl.dataset.bwAccentColor || '').trim();
                    if (_bwAccent && _bwAccent.charAt(0) === '#' && _bwAccent.length >= 7) {
                        var _ar = parseInt(_bwAccent.slice(1,3),16), _ag = parseInt(_bwAccent.slice(3,5),16), _ab = parseInt(_bwAccent.slice(5,7),16);
                        bwFG = 'rgba(' + _ar + ',' + _ag + ',' + _ab + ',';
                    }
                    var bwMX = neonMouseX * 180, bwMY = neonMouseY * 120;
                    var bwT = frameCount;
                    var bwSizePct = parseFloat(wrapperEl.dataset.bwElementSize || '100') / 100;
                    var bwCountPct = parseFloat(wrapperEl.dataset.bwElementCount || '50') / 50;
                    ctx.save();

                    if (activeCloudEffect === 'bw_matrix') {
                        var DM_LAYERS = 3;
                        var DM_SPACINGS = [16, 28, 44];
                        var DM_MAX_RS = [6, 4.5, 3];
                        var DM_ALPHAS = [0.65, 0.35, 0.15];
                        for (var dmL = 0; dmL < DM_LAYERS; dmL++) {
                            var dmDep = dmL / (DM_LAYERS - 1);
                            var dmPlxX = bwMX * (0.3 + dmDep * 2.0), dmPlxY = bwMY * (0.3 + dmDep * 2.0);
                            var dmAlpha = DM_ALPHAS[dmL];
                            var dmSpacing = DM_SPACINGS[dmL] * bwSizePct; if (dmSpacing < 4) dmSpacing = 4;
                            var dmMaxR = DM_MAX_RS[dmL] * bwSizePct * (1 + Math.sin(bwT * 0.012 + dmL * 1.5) * 0.15);
                            var dmCX = Math.floor((-dmPlxX - W * 0.1) / dmSpacing), dmCE = Math.ceil((W - dmPlxX + W * 0.1) / dmSpacing);
                            var dmRY = Math.floor((-dmPlxY - H * 0.1) / dmSpacing), dmRE = Math.ceil((H - dmPlxY + H * 0.1) / dmSpacing);
                            ctx.fillStyle = bwFG + dmAlpha.toFixed(3) + ')';
                            for (var dmC = dmCX; dmC <= dmCE; dmC++) { for (var dmR = dmRY; dmR <= dmRE; dmR++) {
                                var dmSX = dmC * dmSpacing + dmPlxX, dmSY = dmR * dmSpacing + dmPlxY;
                                if (dmSX < -10 || dmSX > W + 10 || dmSY < -10 || dmSY > H + 10) continue;
                                var nz = Math.sin(dmC * 0.43 + dmR * 0.67 + dmL * 2.3 + bwT * 0.008) * Math.cos(dmC * 0.29 + dmR * 0.51 + dmL * 1.1);
                                var r = dmMaxR * (0.15 + 0.85 * Math.max(0, (nz + 1) * 0.5)); if (r < 0.5) continue;
                                ctx.beginPath(); ctx.arc(dmSX, dmSY, r, 0, Math.PI * 2); ctx.fill();
                            }}
                        }
                    }

                    else if (activeCloudEffect === 'bw_grid3d') {
                        var GD_LAYERS = 3;
                        var GD_SPACINGS = [55, 80, 120]; 
                        for (var gdL = 0; gdL < GD_LAYERS; gdL++) {
                            var gdDep = gdL / (GD_LAYERS - 1);
                            var gdPlxX = bwMX * (0.4 + gdDep * 1.8), gdPlxY = bwMY * (0.4 + gdDep * 1.8);
                            var gdAlpha = 0.08 + (1 - gdDep) * 0.32;
                            var gdTileBase = (22 + (1 - gdDep) * 20) * bwSizePct; if (gdTileBase < 6) gdTileBase = 6;
                            var gdSpacing = GD_SPACINGS[gdL];
                            var gdCols = Math.ceil(W / gdSpacing) + 4, gdRows = Math.ceil(H / gdSpacing) + 4;
                            var gdOffX = gdPlxX - gdSpacing * 2;
                            var gdOffY = gdPlxY - gdSpacing * 2;
                            for (var gdC = 0; gdC < gdCols; gdC++) { for (var gdR = 0; gdR < gdRows; gdR++) {
                                var gdX = gdC * gdSpacing + gdOffX, gdY = gdR * gdSpacing + gdOffY;
                                if (gdX < -gdTileBase || gdX > W + gdTileBase || gdY < -gdTileBase || gdY > H + gdTileBase) continue;
                                var gdN = Math.sin(gdC * 0.53 + gdR * 0.71 + gdL * 2.3);
                                if (gdN < 0.0) continue;
                                var gdTS = gdTileBase * (0.6 + 0.4 * gdN);
                                var gdA = gdAlpha * (0.3 + 0.7 * gdN); if (gdA < 0.02) continue;
                                ctx.fillStyle = bwFG + gdA.toFixed(3) + ')'; ctx.fillRect(Math.round(gdX), Math.round(gdY), Math.round(gdTS), Math.round(gdTS));
                            }}
                        }
                    }

                    else if (activeCloudEffect === 'bw_blueprint') {
                        var BP_LAYERS = 3, BP_GRIDS = [40, 70, 110], BP_ALPHAS = [0.45, 0.22, 0.08];
                        for (var bpL = 0; bpL < BP_LAYERS; bpL++) {
                            var bpDep = bpL / (BP_LAYERS - 1);
                            var bpPlxX = bwMX * (0.3 + bpDep * 1.8), bpPlxY = bwMY * (0.3 + bpDep * 1.8);
                            var bpAlpha = BP_ALPHAS[bpL];
                            var bpGrid = BP_GRIDS[bpL] * bwSizePct; if (bpGrid < 12) bpGrid = 12;
                            var bpDrift = bwT * (0.04 + (1 - bpDep) * 0.08) * config.tunnelSpeed;
                            var bpOffX = (bpDrift * 0.7) % bpGrid + bpPlxX, bpOffY = (bpDrift * 0.5) % bpGrid + bpPlxY;
                            var bpLW = Math.max(0.5, 1.5 - bpDep * 0.6);
                            ctx.strokeStyle = bwFG + (bpAlpha * 0.4).toFixed(3) + ')'; ctx.lineWidth = bpLW * 0.5; ctx.beginPath();
                            for (var bpGX = Math.floor(-bpOffX / bpGrid) * bpGrid + bpOffX; bpGX < W + bpGrid; bpGX += bpGrid) { ctx.moveTo(Math.round(bpGX) + 0.5, 0); ctx.lineTo(Math.round(bpGX) + 0.5, H); }
                            for (var bpGY = Math.floor(-bpOffY / bpGrid) * bpGrid + bpOffY; bpGY < H + bpGrid; bpGY += bpGrid) { ctx.moveTo(0, Math.round(bpGY) + 0.5); ctx.lineTo(W, Math.round(bpGY) + 0.5); }
                            ctx.stroke();
                            ctx.strokeStyle = bwFG + bpAlpha.toFixed(3) + ')'; ctx.lineWidth = bpLW;
                            var bpCols = Math.ceil(W / bpGrid) + 2, bpRows = Math.ceil(H / bpGrid) + 2;
                            for (var bpC = -1; bpC < bpCols; bpC++) { for (var bpR = -1; bpR < bpRows; bpR++) {
                                var bpX = bpC * bpGrid + bpOffX, bpY = bpR * bpGrid + bpOffY;
                                if (bpX < -bpGrid || bpX > W + bpGrid || bpY < -bpGrid || bpY > H + bpGrid) continue;
                                var bpN = Math.sin(bpC * 0.73 + bpR * 0.47 + bpL * 2.1 + bpDrift * 0.005);
                                if (bpN > 0.3) {
                                    var bpRad = bpGrid * (0.15 + Math.abs(bpN) * 0.3);
                                    ctx.beginPath(); ctx.arc(bpX, bpY, bpRad, 0, Math.PI * 2); ctx.stroke();
                                    var bpCH = bpRad * 0.4; ctx.beginPath();
                                    ctx.moveTo(bpX - bpCH, bpY); ctx.lineTo(bpX + bpCH, bpY);
                                    ctx.moveTo(bpX, bpY - bpCH); ctx.lineTo(bpX, bpY + bpCH); ctx.stroke();
                                } else if (bpN > 0.0) {
                                    var bpDimW = bpGrid * (0.4 + Math.abs(bpN) * 0.5), bpTick = bpGrid * 0.08;
                                    ctx.beginPath(); ctx.moveTo(bpX - bpDimW, bpY); ctx.lineTo(bpX + bpDimW, bpY);
                                    ctx.moveTo(bpX - bpDimW, bpY - bpTick); ctx.lineTo(bpX - bpDimW, bpY + bpTick);
                                    ctx.moveTo(bpX + bpDimW, bpY - bpTick); ctx.lineTo(bpX + bpDimW, bpY + bpTick); ctx.stroke();
                                }
                            }}
                        }
                    }

                    else if (activeCloudEffect === 'bw_marble') {
                        
                        if (!window._marbleCanvas) {
                            window._marbleCanvas = document.createElement('canvas');
                            window._marbleCtx = window._marbleCanvas.getContext('2d');
                            window._marbleFrame = -1;
                            window._marbleR = 0; window._marbleG = 0; window._marbleB = 0;
                        }
                        var mbPad = 140;
                        var mbScale = 3; 
                        var mbW = Math.ceil((W + mbPad * 2) / mbScale), mbH = Math.ceil((H + mbPad * 2) / mbScale);
                        if (window._marbleCanvas.width !== mbW || window._marbleCanvas.height !== mbH) {
                            window._marbleCanvas.width = mbW; window._marbleCanvas.height = mbH;
                            window._marbleFrame = -1; 
                        }
                        
                        var mbR1, mbG1, mbB1;
                        var _mbAcc = (wrapperEl.dataset.bwAccentColor || '').trim();
                        if (_mbAcc && _mbAcc.charAt(0) === '#' && _mbAcc.length >= 7) {
                            mbR1 = parseInt(_mbAcc.slice(1,3),16); mbG1 = parseInt(_mbAcc.slice(3,5),16); mbB1 = parseInt(_mbAcc.slice(5,7),16);
                        } else if (_bgDark) { mbR1 = 255; mbG1 = 255; mbB1 = 255; }
                        else { mbR1 = 0; mbG1 = 0; mbB1 = 0; }
                        if (mbR1 !== window._marbleR || mbG1 !== window._marbleG || mbB1 !== window._marbleB) {
                            window._marbleFrame = -1; window._marbleR = mbR1; window._marbleG = mbG1; window._marbleB = mbB1;
                        }
                        
                        if (frameCount - window._marbleFrame >= 4) {
                            window._marbleFrame = frameCount;
                            var mbCtx = window._marbleCtx;
                            var mbT = bwT * 0.0012 * config.tunnelSpeed;
                            var mbImg = mbCtx.createImageData(mbW, mbH);
                            var mbD = mbImg.data;
                            var mbFreq = 0.025 / bwSizePct;
                            for (var mbY = 0; mbY < mbH; mbY++) {
                                for (var mbX = 0; mbX < mbW; mbX++) {
                                    var nx = mbX * mbFreq, ny = mbY * mbFreq;
                                    var v = Math.sin(nx * 1.2 + mbT) + Math.sin(ny * 0.9 + mbT * 0.7)
                                          + Math.sin((nx + ny) * 0.7 + mbT * 1.3)
                                          + Math.sin(Math.sqrt(nx * nx + ny * ny) * 0.8 + mbT * 0.5)
                                          + Math.sin((nx * 0.6 - ny * 1.1) + mbT * 0.9) * 0.7;
                                    var ribbon = Math.sin(v * 2.5);
                                    var idx = (mbY * mbW + mbX) * 4;
                                    if (ribbon > 0.25) {
                                        mbD[idx] = mbR1; mbD[idx+1] = mbG1; mbD[idx+2] = mbB1; mbD[idx+3] = 255;
                                    } else if (ribbon > 0.05) {
                                        mbD[idx] = mbR1; mbD[idx+1] = mbG1; mbD[idx+2] = mbB1;
                                        mbD[idx+3] = Math.round(((ribbon - 0.05) / 0.20) * 255);
                                    } else { mbD[idx+3] = 0; }
                                }
                            }
                            mbCtx.putImageData(mbImg, 0, 0);
                        }
                        
                        ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high';
                        var mbLayers = [
                            { alpha: 0.18, plxMul: 0.15, scaleMul: 0.94 },
                            { alpha: 0.35, plxMul: 0.50, scaleMul: 1.00 },
                            { alpha: 0.55, plxMul: 0.90, scaleMul: 1.07 }
                        ];
                        for (var mbLi = 0; mbLi < 3; mbLi++) {
                            var mbL = mbLayers[mbLi];
                            ctx.globalAlpha = mbL.alpha;
                            var mbDrawW = (W + mbPad * 2) * mbL.scaleMul;
                            var mbDrawH = (H + mbPad * 2) * mbL.scaleMul;
                            var mbDrawX = -mbPad - (mbDrawW - W - mbPad * 2) * 0.5 + bwMX * mbL.plxMul;
                            var mbDrawY = -mbPad - (mbDrawH - H - mbPad * 2) * 0.5 + bwMY * mbL.plxMul * 0.7;
                            ctx.drawImage(window._marbleCanvas, mbDrawX, mbDrawY, mbDrawW, mbDrawH);
                        }
                        ctx.globalAlpha = 1;
                    }

                    else if (activeCloudEffect === 'bw_diamonds') {
                        
                        var DI_LAYERS = 4;
                        var DI_BASE_COUNTS = [6, 12, 20, 30];
                        var DI_SIZES = [120, 70, 40, 20];
                        var DI_ALPHAS = [0.25, 0.15, 0.08, 0.04];
                        var diHue = getNeonHue(0);
                        for (var diL = 0; diL < DI_LAYERS; diL++) {
                            var diDep = diL / (DI_LAYERS - 1);
                            var diPlxX = bwMX * (0.3 + diDep * 2.0), diPlxY = bwMY * (0.3 + diDep * 2.0);
                            var diN = Math.max(1, Math.round(DI_BASE_COUNTS[diL] * bwCountPct));
                            var diMaxS = DI_SIZES[diL] * bwSizePct;
                            var diAlpha = DI_ALPHAS[diL];
                            var diSpeed = (0.04 + (1 - diDep) * 0.08) * config.tunnelSpeed;
                            
                            var diGridC = Math.max(1, Math.round(Math.sqrt(diN * W / H)));
                            var diGridR = Math.max(1, Math.ceil(diN / diGridC));
                            var diCellW = W / diGridC, diCellH = H / diGridR;
                            var diIdx = 0;
                            for (var diGR = 0; diGR < diGridR && diIdx < diN; diGR++) {
                                for (var diGC = 0; diGC < diGridC && diIdx < diN; diGC++) {
                                    
                                    var diSeed = Math.sin((diGC + 1) * 127.1 + (diGR + 1) * 269.5 + diL * 311.7) * 43758.5453;
                                    var diJX = (diSeed - Math.floor(diSeed)) - 0.5;
                                    var diSeed2 = Math.sin((diGC + 1) * 419.2 + (diGR + 1) * 137.3 + diL * 183.3) * 43758.5453;
                                    var diJY = (diSeed2 - Math.floor(diSeed2)) - 0.5;
                                    var diSeed3 = Math.sin((diGC + 1) * 389.9 + (diGR + 1) * 251.7 + diL * 71.9) * 43758.5453;
                                    var diRS = (diSeed3 - Math.floor(diSeed3));
                                    var diX = (diGC + 0.5 + diJX * 0.7) * diCellW + diPlxX + Math.sin(bwT * diSpeed * 0.003 + diIdx * 0.8) * 20;
                                    var diY = (diGR + 0.5 + diJY * 0.7) * diCellH + diPlxY + Math.cos(bwT * diSpeed * 0.002 + diIdx * 1.1) * 15;
                                    var diS = diMaxS * (0.4 + diRS * 0.6);
                                    
                                    var diMDX = diX - (W * 0.5 + bwMX * W * 0.3), diMDY = diY - (H * 0.5 + bwMY * H * 0.3);
                                    var diMDist = Math.sqrt(diMDX * diMDX + diMDY * diMDY);
                                    var diMProx = Math.max(0, 1 - diMDist / (Math.max(W, H) * 0.4));
                                    diS *= (1 + diMProx * 1.2);
                                    if (diX < -diS || diX > W + diS || diY < -diS || diY > H + diS) { diIdx++; continue; }
                                    var diH = (diHue + diIdx * 15 + diL * 40) % 360;
                                    var diRGB = hslToRgb(diH, 50, _bgDark ? 70 : 35);
                                    var diA = diAlpha * (0.5 + diRS * 0.5);
                                    ctx.save(); ctx.translate(diX, diY); ctx.rotate(Math.PI / 4);
                                    ctx.fillStyle = 'rgba(' + diRGB[0] + ',' + diRGB[1] + ',' + diRGB[2] + ',' + diA.toFixed(3) + ')';
                                    ctx.fillRect(-diS * 0.5, -diS * 0.5, diS, diS);
                                    ctx.restore();
                                    diIdx++;
                                }
                            }
                        }
                    }

ctx.restore();
                }

                if (!_isMobileDevice) ctx.filter='none';
                ctx.globalAlpha=1;
            }
            if (window._tunnelGen === _myGen) requestAnimationFrame(frame);
        }
        
        var _rafRunning = true;
        window._impulseTunnelKill = function() { window._tunnelGen++; };
        document.addEventListener('visibilitychange', function() {
            if (!document.hidden && !_rafRunning && window._tunnelGen === _myGen) { _rafRunning = true; frame(); }
        });
        setTimeout(function(){ frame(); }, 0);
    }
    function reinitTunnel(newTunnel,newCloud,newStars,newSpeed){
        
        if (window._impulseTunnelKill) window._impulseTunnelKill();
        
        if (window._impulseMotionLava) { window._impulseMotionLava.destroy(); window._impulseMotionLava = null; }
        var oldLavaCv = document.getElementById('impulse-motion-lava-canvas'); if (oldLavaCv) oldLavaCv.remove();
        if (window._impulseWave) { window._impulseWave.destroy(); window._impulseWave = null; }
        var oldWaveCv = document.getElementById('impulse-wave-canvas'); if (oldWaveCv) oldWaveCv.remove();
        if (window._impulse3D) { window._impulse3D.destroy(); window._impulse3D = null; }
        if (window.Impulse3D) Impulse3D.destroyAll();
        var old3dCv = document.getElementById('impulse-3d-canvas'); if (old3dCv) old3dCv.remove();
        if (window._impulseFX && window.ImpulseFX) { var _oldFxCv = document.getElementById('impulse-fx-canvas'); if (_oldFxCv) ImpulseFX.destroy(_oldFxCv); window._impulseFX = null; }
        var oldFxCv = document.getElementById('impulse-fx-canvas'); if (oldFxCv) oldFxCv.remove();
        
        var oldBgDiv=document.querySelector('body>div[style*="radial-gradient"]');if(oldBgDiv)oldBgDiv.remove();
        var oldSvg=document.getElementById('impulse-cloud-svg');if(oldSvg)oldSvg.remove();
        var oldSpaceW=document.getElementById('impulse-space-wrap');if(oldSpaceW)oldSpaceW.remove();
        var cv=document.getElementById('impulse-tunnel-canvas');
        if(cv){cv.style.cssText='position:fixed;top:-16px;left:-16px;width:calc(100% + 32px);height:calc(100% + 32px);z-index:-1;pointer-events:none;background:transparent;display:block;';document.body.appendChild(cv);}
        config.tunnel=!!newTunnel;config.cloudEffect=(!!newTunnel)?'none':(newCloud||'none');if(newSpeed!==undefined)config.tunnelSpeed=parseFloat(newSpeed)||1;config.tunnelFill=wrapperEl.dataset.tunnelFill==='1';config.mouseSensLevel=parseFloat(wrapperEl.dataset.mouseSensLevel||'0.5');
        var _3dEffectsList = ['cosmos','bubbles','particles','crystal','blob','wormhole','fireflies','plexus','grid'];
        var _needsDelay = _3dEffectsList.indexOf(config.cloudEffect) !== -1;
        if(config.tunnel||config.cloudEffect!=='none'){
            if (_needsDelay) {
                setTimeout(function(){ try{initTunnel();}catch(e){console.error('Impulse: effect reinit failed',e);} }, 100);
            } else {
                try{initTunnel();}catch(e){console.error('Impulse: effect reinit failed',e);}
            }
        }
        else {
            
            var cv2=document.getElementById('impulse-tunnel-canvas');
            if(cv2){cv2.getContext('2d').clearRect(0,0,cv2.width,cv2.height);cv2.style.display='none';}
        }

        
        if (window.ImpulseDepthParallax || window.ImpulseDepthMesh) {
            if (window.ImpulseDepthParallax) window.ImpulseDepthParallax.destroyAll();
            if (wrapperEl.__depthMeshApi) { try { wrapperEl.__depthMeshApi.destroy(); } catch(e){} wrapperEl.__depthMeshApi = null; }
            var _dEnabled = wrapperEl.dataset.depthEnabled === '1';
            var _dImg = wrapperEl.dataset.depthImage || '';
            var _dMap = wrapperEl.dataset.depthMap || '';

            
            var _dGlass = wrapperEl.dataset.cloudEffect === 'glass';
            var _dRelief = wrapperEl.dataset.depthMode === 'relief' && !_dGlass;
            if ((_dEnabled || _dGlass) && _dImg && _dMap) {
                wrapperEl.setAttribute('data-depth-image', _dImg);
                wrapperEl.setAttribute('data-depth-map', _dMap);
                wrapperEl.setAttribute('data-depth-strength', wrapperEl.dataset.depthStrength || 50);
                wrapperEl.style.zIndex = '2';
                wrapperEl.style.background = 'transparent';
                screens.forEach(function(s){
                    var _sBg=s.style.backgroundColor||s.style.background||'';
                    if(!_sBg||_sBg==='transparent'||_sBg==='rgba(0, 0, 0, 0)'){s.style.background='transparent';s.style.backgroundColor='transparent';}
                    var sec=s.querySelector('.impulse-section,section');
                    if(sec){var _secBg=sec.style.backgroundColor||sec.style.background||'';if(!_secBg||_secBg==='transparent'||_secBg==='rgba(0, 0, 0, 0)'){sec.style.background='transparent';sec.style.backgroundColor='transparent';}}
                });
                
                document.documentElement.style.cssText += 'background:' + (document.body.dataset.pageBgColor||'#f5f5f5') + '!important;';
                if (_dRelief && window.ImpulseDepthMesh) {
                    
                    var _mTravel = Math.max(0, Math.min(100, parseInt(wrapperEl.dataset.depthStrength || '50', 10))) / 100 * 0.1;
                    var _mLight  = Math.max(0, Math.min(70,  parseInt(wrapperEl.dataset.depthLight  || '50', 10))) / 100;
                    var _mPivot  = Math.max(0, Math.min(100, parseInt(wrapperEl.dataset.depthPivot  || '50', 10))) / 100;
                    var _mZoom   = Math.max(100, Math.min(140, parseInt(wrapperEl.dataset.depthZoom || '100', 10))) / 100;
                    wrapperEl.setAttribute('data-depth-mode', 'relief');
                    wrapperEl.__depthMeshApi = window.ImpulseDepthMesh.init(wrapperEl, {
                        colorUrl: _dImg, depthUrl: _dMap,
                        strength: _mLight, travel: _mTravel, pivot: _mPivot, zoom: _mZoom
                    });
                } else if (window.ImpulseDepthParallax) {
                    wrapperEl.setAttribute('data-depth-mode', 'parallax');
                    window.ImpulseDepthParallax.init(wrapperEl);
                }
            } else {
                wrapperEl.removeAttribute('data-depth-image');
                wrapperEl.removeAttribute('data-depth-map');
            }
        }
    }

    
    window._impulseReinitEnv = function(tunnel, cloud, stars, speed) {
        try { reinitTunnel(tunnel, cloud, stars, speed); }
        catch(e) { console.error('Impulse: _impulseReinitEnv failed', e); }
    };
    Object.defineProperty(window, '_impulseScreenWrapper', {
        get: function() { return wrapperEl; },
        configurable: true
    });
    Object.defineProperty(window, '_impulseScreenCanonicalEnv', {
        get: function() {
            return (wrapperEl && wrapperEl.dataset.cloudEffect) || 'none';
        },
        configurable: true
    });

    function impulseRunScreenEntrance(screenEl, bgColor) {
        var preset = screenEl.dataset.entrancePreset || 'none';
        if (preset === 'none' || !preset) return;
        var duration = parseInt(screenEl.dataset.entranceDuration) || 1200;
        var W = screenEl.offsetWidth || window.innerWidth;
        var H = screenEl.offsetHeight || window.innerHeight;
        
        var assetEl = screenEl.querySelector('.impulse-logo-animator, .impulse-display-text, .impulse-image img, img');
        var cx = W * 0.5, cy = H * 0.5;
        if (assetEl) {
            try {
                var sRect = screenEl.getBoundingClientRect();
                var aRect = assetEl.getBoundingClientRect();
                var ax = (aRect.left + aRect.width * 0.5) - sRect.left;
                var ay = (aRect.top + aRect.height * 0.5) - sRect.top;
                if (ax > 0 && ax < W && ay > 0 && ay < H) { cx = ax; cy = ay; }
            } catch(e) {}
        }
        var cv = document.createElement('canvas');
        cv.width = W; cv.height = H;
        cv.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;z-index:9998;pointer-events:none;';
        var prevOverflow = screenEl.style.overflow;
        screenEl.style.overflow = 'hidden';
        screenEl.appendChild(cv);
        var ctx = cv.getContext('2d');
        var maxR = Math.sqrt(Math.max(cx, W-cx)*Math.max(cx, W-cx) + Math.max(cy, H-cy)*Math.max(cy, H-cy)) * 1.05;
        function eOut(t) { return 1 - Math.pow(1-t, 2.5); }
        var start = null;
        function frame(ts) {
            if (!start) start = ts;
            var t = Math.min((ts - start) / duration, 1);
            var p = eOut(t);
            ctx.globalCompositeOperation = 'source-over';
            ctx.fillStyle = bgColor || '#000';
            ctx.fillRect(0, 0, W, H);
            ctx.globalCompositeOperation = 'destination-out';
            ctx.fillStyle = 'rgba(0,0,0,1)';
            var r = p * maxR;
            if (preset === 'iris') {
                ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI*2); ctx.fill();
            } else if (preset === 'diamond') {
                ctx.save(); ctx.translate(cx, cy); ctx.rotate(Math.PI/4);
                ctx.fillRect(-r, -r, r*2, r*2); ctx.restore();
            } else if (preset === 'hex') {
                ctx.beginPath();
                for (var i=0; i<6; i++) { var a=i*Math.PI/3-Math.PI/6; i===0?ctx.moveTo(cx+r*Math.cos(a),cy+r*Math.sin(a)):ctx.lineTo(cx+r*Math.cos(a),cy+r*Math.sin(a)); }
                ctx.closePath(); ctx.fill();
            } else if (preset === 'shatter') {
                var N=18, gap=Math.sin(t*Math.PI*0.5)*0.08;
                for (var s=0; s<N; s++) { var a1=(s/N)*Math.PI*2, a2=((s+1)/N)*Math.PI*2-gap; ctx.beginPath(); ctx.moveTo(cx,cy); ctx.lineTo(cx+r*Math.cos(a1),cy+r*Math.sin(a1)); ctx.lineTo(cx+r*Math.cos(a2),cy+r*Math.sin(a2)); ctx.closePath(); ctx.fill(); }
            } else if (preset === 'bands') {
                var nB=12, bH=H/nB;
                for (var b=0; b<nB; b++) { var bcy=(b+0.5)*bH, dist=Math.abs(bcy-cy)/H, del=dist*0.45, bt=Math.max(0,Math.min(1,(t-del)/(1-del))), bp=eOut(bt), bw=bp*W; ctx.fillRect(cx-bw*0.5, b*bH, bw, bH+1); }
            }
            if (t < 1) { requestAnimationFrame(frame); }
            else { cv.remove(); screenEl.style.overflow = prevOverflow; }
        }
        requestAnimationFrame(frame);
        return true;
    }

    
    function captureEnvCanvas() {
        var cv = _activeEnvCanvas;
        if (!cv || cv.width < 10 || cv.height < 10) {
            
            var ids = ['impulse-motion-lava-canvas','impulse-wave-canvas','impulse-3d-canvas','impulse-fx-canvas','impulse-tunnel-canvas'];
            for (var i = 0; i < ids.length; i++) {
                var c = document.getElementById(ids[i]);
                if (c && c.width > 10 && c.height > 10) { cv = c; break; }
            }
        }
        if (!cv || cv.width < 10 || cv.height < 10) return null;
        try {
            var W = window.innerWidth || cv.width;
            var H = window.innerHeight || cv.height;
            var snap = document.createElement('canvas');
            snap.width = W; snap.height = H;
            var ctx2 = snap.getContext('2d');
            
            var bg = document.body.style.background || getComputedStyle(document.body).backgroundColor || '#000000';
            ctx2.fillStyle = (bg && bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') ? bg : '#000000';
            ctx2.fillRect(0, 0, W, H);

            ctx2.globalCompositeOperation = 'source-over';
            ctx2.drawImage(cv, 0, 0, W, H);
            
            var url = snap.toDataURL('image/jpeg', 0.85);
            if (!url || url.length < 200 || url === 'data:,') {
                
                url = cv.toDataURL('image/png');
                if (!url || url.length < 200) return null;
            }
            return url;
        } catch(ex) { return null; }
    }
    
    function _resolveScreenIndex(target){
        if(target==null) return -1;
        if(typeof target==='number'){
            if(target>=0 && target<screens.length) return target;
            
            for(var i=0;i<screens.length;i++){
                if(parseInt(screens[i].dataset.id||screens[i].id,10)===target) return i;
            }
            return -1;
        }
        if(typeof target==='string'){
            for(var j=0;j<screens.length;j++){
                if(screens[j].dataset.id===target||screens[j].id===target||screens[j].dataset.screenId===target) return j;
            }
            var n=parseInt(target,10);
            return isNaN(n)?-1:_resolveScreenIndex(n);
        }
        if(target.nodeType===1){
            for(var k=0;k<screens.length;k++){ if(screens[k]===target) return k; }
        }
        return -1;
    }
    function openScreen(target){
        var idx=_resolveScreenIndex(target);
        if(idx<0) return false;
        var bridge=screens[idx];
        bridge.removeAttribute('data-screen-skip');
        bridge.classList.remove('impulse-screen-skipped');
        bridge.dispatchEvent(new CustomEvent('impulse-screen-revealed',{bubbles:true,detail:{index:idx}}));
        goTo(idx);
        var rebound=false;
        var onChange=function(){
            if(rebound) return;
            if(current!==idx){
                rebound=true;
                bridge.setAttribute('data-screen-skip','1');
                bridge.classList.add('impulse-screen-skipped');

                

                bridge.dispatchEvent(new CustomEvent('impulse-screen-rehidden',{bubbles:true,detail:{index:idx}}));
                document.removeEventListener('impulse-screen-changed',onChange);
            }
        };
        document.addEventListener('impulse-screen-changed',onChange);
        return true;
    }
    
    document.addEventListener('click',function(e){
        var t=e.target&&e.target.closest&&e.target.closest('[data-open-screen],a[href^="#screen-"],[data-link^="#screen-"]');
        if(!t) return;
        var raw=t.getAttribute('data-open-screen');
        if(!raw){
            var h=t.getAttribute('href')||t.getAttribute('data-link')||'';
            raw=h.replace(/^#screen-/,'');
        }
        if(!raw) return;
        if(!openScreen(raw)) return;
        e.preventDefault();
    },true);

    window.ImpulseScreens={init:init,next:next,prev:prev,goTo:goTo,jumpTo:jumpTo,openScreen:openScreen,getCurrent:function(){return current;},getCount:function(){return screens.length;},captureEnvCanvas:captureEnvCanvas,updateSettings:function(t,c,d,n,i,inf,ts,stars){config.transition=t||config.transition;config.cooldown=c||config.cooldown;config.duration=d||config.duration;config.navDots=!!n;if(i!==undefined)config.intensity=i;if(ts!==undefined)config.tunnelSpeed=ts},updateTunnelSpeed:function(ts){config.tunnelSpeed=parseFloat(ts)||1;},reinitTunnel:reinitTunnel};
    if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',init);else init();

})();
