
(function () {
    'use strict';

    try {
        var FT = 'instinctor_ft';
        if (!localStorage.getItem(FT)) {
            var q = new URLSearchParams(location.search);
            var rh = '';
            if (document.referrer) {
                var a = document.createElement('a');
                a.href = document.referrer;
                if (a.hostname && a.hostname !== location.hostname) rh = a.hostname;
            }
            localStorage.setItem(FT, JSON.stringify({
                r:  rh,
                us: (q.get('utm_source')   || '').slice(0, 100),
                um: (q.get('utm_medium')   || '').slice(0, 100),
                uc: (q.get('utm_campaign') || '').slice(0, 150),
                ct: (q.get('utm_content')  || '').slice(0, 100),
                tm: (q.get('utm_term')     || '').slice(0, 100),
                gc: (q.get('gclid')        || '').slice(0, 120),
                gb: (q.get('gbraid')       || '').slice(0, 120),
                wb: (q.get('wbraid')       || '').slice(0, 120),
                lp: location.pathname.slice(0, 200),
                t:  Math.floor(Date.now() / 1000)
            }));
        } else {
            
            try {
                var cur = JSON.parse(localStorage.getItem(FT) || '{}');
                var q2  = new URLSearchParams(location.search);
                var changed = false;
                ['gclid:gc', 'gbraid:gb', 'wbraid:wb'].forEach(function (pair) {
                    var parts = pair.split(':');
                    var v = (q2.get(parts[0]) || '').slice(0, 120);
                    if (v && !cur[parts[1]]) { cur[parts[1]] = v; changed = true; }
                });
                if (changed) localStorage.setItem(FT, JSON.stringify(cur));
            } catch (e2) {}
        }
    } catch (e) {}

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

    var humanInput = 0;
    function markHuman() { humanInput = 1; }
    
    ['mousemove', 'pointerdown', 'click', 'keydown', 'touchstart', 'wheel', 'touchmove'].forEach(function (ev) {
        window.addEventListener(ev, markHuman, { passive: true, once: 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(), hu: humanInput });
        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);
})();
