
(function() {
    'use strict';

    var reduced = false;
    try { reduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch (e) {}

    var containers = [];
    var rafId = null;


    
    
    function _readBaseTransform(cell) {
        var r = cell.getAttribute('data-cell-rotate');
        var s = cell.getAttribute('data-cell-scale');
        var parts = [];
        if (r && r !== '0') parts.push('rotate(' + r + 'deg)');
        if (s && s !== '100') parts.push('scale(' + (parseInt(s, 10) / 100) + ')');
        return parts.join(' ');
    }

    function initContainer(el) {
        if (el._depthInit) return;
        var intensity = parseInt(el.getAttribute('data-depth-intensity'), 10) || 0;

        
        
        var cellSel = '.impulse-grid-cell,.impulse-rows-cell,.impulse-layout-cell';
        var cells = el.querySelectorAll(cellSel);
        if (!cells.length) return;
        el._depthInit = true;

        var cols = parseInt(el.getAttribute('data-depth-cols'), 10) || 0;

        
        
        var s = Math.pow(intensity / 100, 2);
        var maxZ       = 320 * s;   
        var breathAmp  = 70  * s;   
        var parallaxPx = 26  * s;   

        

        

        var tiltIntensity = parseInt(el.getAttribute('data-tilt-intensity'), 10);
        if (isNaN(tiltIntensity)) tiltIntensity = 0;
        var tiltMax       = 10 * (tiltIntensity / 100);


        

        
        if (getComputedStyle(el).position === 'static') {
            el.style.position = 'relative';
        }
        
        if (getComputedStyle(el).overflow === 'hidden') {
            el._depthPrevOverflow = el.style.overflow;
            el.style.overflow = 'visible';
        }

        var state = {
            el: el,
            cells: [],
            mx: 0, my: 0,

            

            smx: 0, smy: 0,
            maxZ: maxZ, breathAmp: breathAmp, parallaxPx: parallaxPx, tiltMax: tiltMax,

            

            hoverZ: 110 * (intensity / 100),
            anyHover: false
        };

        cells.forEach(function(cell, i) {
            var row = parseInt(cell.getAttribute('data-depth-row'), 10);
            var col = parseInt(cell.getAttribute('data-depth-col'), 10);

            if (isNaN(row)) row = parseInt(cell.getAttribute('data-row'), 10);
            if (isNaN(col)) col = parseInt(cell.getAttribute('data-col'), 10);
            if (isNaN(row) || isNaN(col)) {
                if (cols > 0) { row = Math.floor(i / cols); col = i % cols; }
                else { row = 0; col = i; }
            }

            

            
            var phase = 0.65 + row * 0.73 + col * 0.91;
            var baseZ = maxZ * Math.sin(phase);


            

            

            

            

            

            

            
            cell.style.willChange = 'transform';
            cell.style.transition = 'none';


            

            



            
            
            function _discoverInner() {
                var _ew = cell.querySelectorAll(':scope > .impulse-el');
                var out = [];
                if (_ew.length) {
                    for (var k = 0; k < _ew.length; k++) out.push(_ew[k]);
                } else {
                    for (var k2 = 0; k2 < cell.children.length; k2++) {
                        var ck = cell.children[k2];
                        var t = ck.tagName;
                        if (t === 'SCRIPT' || t === 'STYLE') continue;
                        var cl = ck.classList;
                        if (cl && (cl.contains('impulse-cell-empty-indicator') || cl.contains('impulse-cell-bg'))) continue;
                        out.push(ck);
                    }
                }
                for (var k3 = 0; k3 < out.length; k3++) {
                    out[k3].style.willChange = 'transform,filter';
                    out[k3].style.transition = 'none';
                }
                return out;
            }

            var cs = {
                cellEl: cell,         
                inner: _discoverInner(), 
                phase: phase, baseZ: baseZ,
                curTx: 0, curTy: 0, curTz: 0, curScale: 1, curBlur: 0,
                hover: false,

                

                cellTx: 0, cellTy: 0,
                curTiltX: 0, curTiltY: 0
            };
            state.cells.push(cs);


            
            try {
                cs._mo = new MutationObserver(function() {
                    cs.inner = _discoverInner();
                });
                cs._mo.observe(cell, { childList: true });
            } catch (_e) {}


            

            
        });


        

        

        
        if (el.classList.contains('impulse-animated') && !el.classList.contains('impulse-visible')) {
            el.classList.add('impulse-visible');
        }
        el.querySelectorAll('.impulse-animated').forEach(function(_an) {
            if (!_an.classList.contains('impulse-visible')) _an.classList.add('impulse-visible');
        });

        el.addEventListener('mousemove', function(e) {
            var r = el.getBoundingClientRect();
            state.mx = ((e.clientX - r.left) / Math.max(1, r.width)) * 2 - 1;
            state.my = ((e.clientY - r.top)  / Math.max(1, r.height)) * 2 - 1;

            

            

            

            
            var anyHover = false;
            for (var hi = 0; hi < state.cells.length; hi++) {
                var cs2 = state.cells[hi];
                var cEl = cs2.cellEl;
                var cw = cEl.offsetWidth, ch = cEl.offsetHeight;
                var cLeft   = r.left + cEl.offsetLeft;
                var cTop    = r.top  + cEl.offsetTop;
                var cRight  = cLeft + cw;
                var cBottom = cTop  + ch;
                var inside = e.clientX >= cLeft && e.clientX <= cRight &&
                             e.clientY >= cTop  && e.clientY <= cBottom;
                cs2.hover = inside;
                cEl.classList.toggle('impulse-cell-depth-focus', inside);
                if (inside) anyHover = true;

                

                var rawTx = (e.clientX - cLeft) / Math.max(1, cw) - 0.5;
                var rawTy = (e.clientY - cTop)  / Math.max(1, ch) - 0.5;
                cs2.cellTx = Math.max(-0.5, Math.min(0.5, rawTx));
                cs2.cellTy = Math.max(-0.5, Math.min(0.5, rawTy));
            }
            state.anyHover = anyHover;
        });
        el.addEventListener('mouseleave', function() {
            state.mx = 0; state.my = 0;
            state.cells.forEach(function(cs) {
                cs.hover = false;
                cs.cellTx = 0;
                cs.cellTy = 0;
                cs.cellEl.classList.remove('impulse-cell-depth-focus');
            });
            state.anyHover = false;
        });

        containers.push(state);
    }

    function recomputeAnyHover(state) {
        for (var i = 0; i < state.cells.length; i++) {
            if (state.cells[i].hover) { state.anyHover = true; return; }
        }
        state.anyHover = false;
    }

    function tick(ts) {

        
        var dragging = !!(document.body && document.body.classList.contains('drag-active'));

        

        

        
        
        var _isSceneMode = !!(document.body && document.body.dataset.screenMode === '1');
        for (var i = 0; i < containers.length; i++) {
            var s = containers[i];
            var maxZ = s.maxZ || 1;
            if (_isSceneMode) {
                if (s._cachedSec === undefined) {
                    var _node = s.el;
                    var _sec = null;
                    while (_node && _node.tagName !== 'BODY') {
                        if (_node.classList && _node.classList.contains('impulse-section')) { _sec = _node; break; }
                        _node = _node.parentElement;
                    }
                    s._cachedSec = _sec || null;
                }
                if (s._cachedSec && s._cachedSec.style.visibility === 'hidden') continue;
            }

            

            
            var mxC = s.mx * Math.abs(s.mx);
            var myC = s.my * Math.abs(s.my);
            s.smx += (mxC - s.smx) * 0.025;
            s.smy += (myC - s.smy) * 0.025;
            for (var j = 0; j < s.cells.length; j++) {
                var cs = s.cells[j];
                if (dragging) {

                    
                    var _bt = _readBaseTransform(cs.cellEl);
                    cs.cellEl.style.transform = _bt;
                    cs._lastXform = _bt;
                    cs.cellEl.style.zIndex = '';
                    for (var dci = 0; dci < cs.inner.length; dci++) {
                        cs.inner[dci].style.transform = '';
                        cs.inner[dci].style.filter = '';
                    }
                    
                    cs.curTx = 0; cs.curTy = 0; cs.curTz = 0; cs.curScale = 1; cs.curBlur = 0;
                    cs.curTiltX = 0; cs.curTiltY = 0;
                    continue;
                }

                
                
                var breath = s.anyHover ? 0 : s.breathAmp * Math.sin(ts / 1700 + cs.phase);
                var tgZ, tgScale, tgTx, tgTy, tgBlur;

                

                
                
                var _zToScale = function(z) { return 1400 / (1400 - z); };
                if (cs.hover) {

                    
                    
                    tgZ     = s.hoverZ;
                    tgScale = 1;
                    tgTx    = 0;
                    tgTy    = 0;
                    tgBlur  = 0;
                } else if (s.anyHover) {

                    
                    tgZ     = 0;
                    tgScale = _zToScale(cs.baseZ);
                    tgTx    = 0;
                    tgTy    = 0;
                    tgBlur  = Math.min(6, Math.abs(cs.baseZ) * 0.020);
                } else {

                    
                    
                    var idleZ = cs.baseZ + breath;
                    tgZ     = 0;
                    tgScale = _zToScale(idleZ);
                    var pFactor = cs.baseZ / maxZ;
                    tgTx    = -s.smx * s.parallaxPx * pFactor;
                    tgTy    = -s.smy * s.parallaxPx * pFactor;
                    tgBlur  = Math.min(6, Math.abs(idleZ) * 0.014);
                }

                

                

                

                

                

                
                var _txCurve =  cs.cellTx * Math.abs(cs.cellTx) * 2;
                var _tyCurve =  cs.cellTy * Math.abs(cs.cellTy) * 2;
                var tgTiltX =  _tyCurve * s.tiltMax;
                var tgTiltY = -_txCurve * s.tiltMax;


                

                

                var k = 0.07, kS = 0.14;
                var kT_follow  = 0.030;  
                var kT_release = 0.012;  
                var _releasing = (cs.cellTx === 0 && cs.cellTy === 0);
                var kT = _releasing ? kT_release : kT_follow;
                cs.curTx    += (tgTx    - cs.curTx)    * k;
                cs.curTy    += (tgTy    - cs.curTy)    * k;
                cs.curTz    += (tgZ     - cs.curTz)    * k;
                cs.curScale += (tgScale - cs.curScale) * kS;
                cs.curBlur  += (tgBlur  - cs.curBlur)  * kS;
                cs.curTiltX += (tgTiltX - cs.curTiltX) * kT;
                cs.curTiltY += (tgTiltY - cs.curTiltY) * kT;

                

                
                
                var _hasTilt = Math.abs(cs.curTiltX) > 0.05 || Math.abs(cs.curTiltY) > 0.05;
                var _hasZ    = Math.abs(cs.curTz) > 0.5;
                var _has3D   = _hasTilt || _hasZ;
                var _dynXform = _has3D
                    ? 'perspective(700px) translate(' + cs.curTx.toFixed(1) + 'px,' + cs.curTy.toFixed(1) + 'px) rotateX(' + cs.curTiltX.toFixed(2) + 'deg) rotateY(' + cs.curTiltY.toFixed(2) + 'deg) translateZ(' + cs.curTz.toFixed(1) + 'px)'
                    : (Math.abs(cs.curTx) > 0.1 || Math.abs(cs.curTy) > 0.1
                        ? 'translate(' + cs.curTx.toFixed(1) + 'px,' + cs.curTy.toFixed(1) + 'px)'
                        : '');

                

                
                
                var _baseXform = _readBaseTransform(cs.cellEl);
                var _cellXform = _baseXform && _dynXform
                    ? _baseXform + ' ' + _dynXform
                    : (_dynXform || _baseXform);
                var _zIndex = cs.hover ? '100' : String(Math.round(100 + (cs.curScale - 1) * 100));

                

                
                if (cs._lastXform !== _cellXform) {
                    cs.cellEl.style.transform = _cellXform;
                    cs._lastXform = _cellXform;
                }
                if (cs._lastZ !== _zIndex) {
                    cs.cellEl.style.zIndex = _zIndex;
                    cs._lastZ = _zIndex;
                }


                

                
                var _innerXform = (Math.abs(cs.curScale - 1) > 0.001)
                    ? 'scale(' + cs.curScale.toFixed(3) + ')'
                    : '';
                var _innerFilter = cs.curBlur > 0.1 ? 'blur(' + cs.curBlur.toFixed(2) + 'px)' : '';
                if (cs._lastInnerX !== _innerXform || cs._lastInnerF !== _innerFilter) {
                    cs._lastInnerX = _innerXform;
                    cs._lastInnerF = _innerFilter;
                    for (var ci2 = 0; ci2 < cs.inner.length; ci2++) {
                        var ich = cs.inner[ci2];
                        ich.style.transform = _innerXform;
                        ich.style.filter = _innerFilter;
                    }
                }
            }
        }
        rafId = requestAnimationFrame(tick);
    }


    
    function injectFocusStyles() {
        if (document.getElementById('impulse-cell-depth-style')) return;
        var st = document.createElement('style');
        st.id = 'impulse-cell-depth-style';
        st.textContent =
            '.impulse-cell-depth-focus .impulse-text,' +
            '.impulse-cell-depth-focus .impulse-text-col,' +
            '.impulse-cell-depth-focus .impulse-display-text{' +
                'font-weight:700;' +
                'transition:font-weight 0.18s ease-in-out;' +
            '}';
        (document.head || document.documentElement).appendChild(st);
    }

    function init() {
        if (reduced) return; 
        injectFocusStyles();

        
        document.querySelectorAll(
            '.impulse-grid, .impulse-rows, .impulse-layout-grid, [data-depth-intensity]'
        ).forEach(initContainer);
        if (containers.length && rafId === null) rafId = requestAnimationFrame(tick);
    }

    
    window.ImpulseCellDepth = {
        init: init,
        reinit: function() {
            
            containers.forEach(function(s) {
                s.cells.forEach(function(cs) {
                    if (cs._mo) { try { cs._mo.disconnect(); } catch (_e) {} }

                    
                    cs.cellEl.style.transform = _readBaseTransform(cs.cellEl);
                    cs.cellEl.style.zIndex = '';
                    for (var k = 0; k < cs.inner.length; k++) {
                        cs.inner[k].style.transform = '';
                        cs.inner[k].style.filter = '';
                    }
                });
                s.el._depthInit = false;
            });
            containers = [];
            if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
            init();
        }
    };

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


    
    
    function reinitTarget(el) {

        if (!el) return;
        for (var i = containers.length - 1; i >= 0; i--) {
            if (containers[i].el === el) {
                containers[i].cells.forEach(function(cs) {
                    if (cs._mo) { try { cs._mo.disconnect(); } catch (_e) {} }

                    cs.cellEl.style.transform = _readBaseTransform(cs.cellEl);
                    cs.cellEl.style.zIndex = '';
                    for (var k = 0; k < cs.inner.length; k++) {
                        cs.inner[k].style.transform = '';
                        cs.inner[k].style.filter = '';
                    }
                });
                containers.splice(i, 1);
            }
        }
        el._depthInit = false;
        el.style.perspective = ''; el.style.perspectiveOrigin = ''; el.style.transformStyle = '';
        if (el._depthPrevOverflow !== undefined) { el.style.overflow = el._depthPrevOverflow; delete el._depthPrevOverflow; }

        initContainer(el);
        if (rafId === null && containers.length) rafId = requestAnimationFrame(tick);
    }

    var GRID_SELECTOR = '.impulse-grid, .impulse-rows, .impulse-layout-grid, [data-depth-intensity]';
    function _isGrid(n) {
        if (!n || n.nodeType !== 1) return false;
        if (n.matches && n.matches(GRID_SELECTOR)) return true;
        return n.querySelector && !!n.querySelector(GRID_SELECTOR);
    }
    try {
        var mo = new MutationObserver(function(muts) {
            var attrTouched = null;
            var needsInit = false;
            muts.forEach(function(m) {
                if (m.type === 'attributes' &&
                    (m.attributeName === 'data-depth-intensity' || m.attributeName === 'data-tilt-intensity')) {
                    attrTouched = m.target;
                } else if (m.type === 'childList') {
                    m.addedNodes.forEach(function(n) {
                        if (_isGrid(n)) needsInit = true;
                    });
                }
            });
            if (attrTouched) reinitTarget(attrTouched);
            if (needsInit) {
                document.querySelectorAll(GRID_SELECTOR).forEach(initContainer);
                if (containers.length && rafId === null) rafId = requestAnimationFrame(tick);
            }
        });
        mo.observe(document.body || document.documentElement, {
            childList: true, subtree: true,
            attributes: true, attributeFilter: ['data-depth-intensity', 'data-tilt-intensity']
        });
    } catch (e) {}
})();
