
(function () {
    'use strict';
    var cfg = window.__impulseTrack;
    if (!cfg || !cfg.t || !cfg.u || !navigator.sendBeacon) return;

    function _isHeadlessBrowser() {
        try {
            if (navigator.webdriver === true) return true;
            var ua = (navigator.userAgent || '').toLowerCase();
            if (ua.indexOf('headlesschrome') !== -1) return true;
            if (ua.indexOf('puppeteer')      !== -1) return true;
            if (ua.indexOf('playwright')     !== -1) return true;
            if (ua.indexOf('selenium')       !== -1) return true;
            if (ua.indexOf('phantomjs')      !== -1) return true;
            
            if (/(crawl|spider|\bbot\b|scraper|archiv)/i.test(navigator.userAgent || '')) return true;
        } catch (_e) {}
        return false;
    }
    if (_isHeadlessBrowser()) return;

    var IDLE_MS   = 30000; 
    var engaged   = 0;     
    var maxScroll = 0;     
    var lastAct   = Date.now();

    function markActive() { lastAct = Date.now(); }
    ['mousemove', 'keydown', 'scroll', 'wheel', 'touchstart', 'pointerdown', 'click'].forEach(function (ev) {
        window.addEventListener(ev, markActive, { passive: true });
    });

    
    
    setInterval(function () {
        if (document.visibilityState === 'visible' && (Date.now() - lastAct) < IDLE_MS) engaged++;
    }, 1000);

    
    
    function updateScroll() {
        var doc = document.documentElement;
        var h = Math.max(doc.scrollHeight, (document.body ? document.body.scrollHeight : 0));
        if (h <= 0) return;
        var top = window.pageYOffset || doc.scrollTop || 0;
        var pct = Math.round((top + window.innerHeight) / h * 100);
        if (pct > maxScroll) maxScroll = Math.max(0, Math.min(100, pct));
    }
    window.addEventListener('scroll', updateScroll, { passive: true });
    updateScroll();

    
    function exitScreen() {
        try {
            var sm = window.impulseScreenMode;
            if (sm && typeof sm.getCurrentScreen === 'function') {
                var i = sm.getCurrentScreen();
                if (typeof i === 'number' && i >= 0) return i;
            }
        } catch (e) {}
        return -1;
    }

    function send() {
        updateScroll();
        var payload = JSON.stringify({ t: cfg.t, s: engaged, sc: maxScroll, ex: exitScreen() });
        try { navigator.sendBeacon(cfg.u, new Blob([payload], { type: 'application/json' })); } catch (e) {}
    }

    
    
    document.addEventListener('visibilitychange', function () {
        if (document.visibilityState === 'hidden') send();
    });
    window.addEventListener('pagehide', send);

    

    
    
    setTimeout(send, 1000);
})();
