/**
 * Defog tracking beacon.
 *
 * Intentionally tiny and dependency-free. Fires once per pageview, asynchronously,
 * and never blocks rendering. No cookies, no localStorage — identity is derived
 * server-side from a daily-rotating salted hash.
 */
( function () {
	if ( window.__defogSent ) {
		return;
	}
	var cfg = window.DefogTracker;
	if ( ! cfg || ! cfg.endpoint ) {
		return;
	}

	try {
		// Skip prerendered tabs; they fire again when actually shown.
		if ( document.visibilityState === 'prerender' ) {
			return;
		}
		// Honour Do-Not-Track when the site owner opts in.
		if ( cfg.dnt && ( navigator.doNotTrack === '1' || window.doNotTrack === '1' ) ) {
			return;
		}

		var params = new URLSearchParams( window.location.search );
		var ad = '';
		if ( params.get( 'gclid' ) || params.get( 'gbraid' ) || params.get( 'wbraid' ) ) {
			ad = 'google';
		} else if ( params.get( 'msclkid' ) ) {
			ad = 'microsoft';
		}
		var payload = {
			p: window.location.pathname,
			r: document.referrer || '',
			us: params.get( 'utm_source' ) || '',
			um: params.get( 'utm_medium' ) || '',
			ad: ad,
			pt: cfg.pt || 'other'
		};

		window.__defogSent = true;
		var body = JSON.stringify( payload );

		function send( obj ) {
			var b = JSON.stringify( obj );
			if ( navigator.sendBeacon ) {
				navigator.sendBeacon( cfg.endpoint, new Blob( [ b ], { type: 'application/json' } ) );
			} else {
				fetch( cfg.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: b, keepalive: true, credentials: 'omit' } );
			}
		}

		send( payload );

		// Engagement: measure time the page is actually visible, report on hide.
		var engaged = 0, lastVisible = Date.now(), visible = ( document.visibilityState === 'visible' );
		var path = payload.p;
		function accrue() {
			if ( visible ) { engaged += Date.now() - lastVisible; }
			lastVisible = Date.now();
		}
		function reportEngagement() {
			accrue();
			var secs = Math.round( engaged / 1000 );
			if ( secs < 2 ) { return; }
			send( { p: path, dur: secs } );
		}
		document.addEventListener( 'visibilitychange', function () {
			if ( document.visibilityState === 'hidden' ) { accrue(); visible = false; reportEngagement(); }
			else { visible = true; lastVisible = Date.now(); }
		} );
		window.addEventListener( 'pagehide', reportEngagement );

		// User actions (opt-in via cfg.ev), delegated on the capture phase so they
		// still fire if another handler stops propagation.
		// - download: link to a file (by extension), any host — takes priority
		// - outbound: link leaving to another host
		// - form: a form submission (only the fact; never any field content)
		if ( cfg.ev ) {
			var DL = /\.(pdf|zip|rar|7z|gz|dmg|pkg|exe|doc|docx|xls|xlsx|csv|ppt|pptx|key|rtf|txt|mp3|wav|mp4|mov|avi|wmv|mpe?g)$/i;
			document.addEventListener( 'click', function ( e ) {
				try {
					var a = e.target && e.target.closest ? e.target.closest( 'a[href]' ) : null;
					if ( ! a ) { return; }
					var url = new URL( a.href, window.location.href );
					if ( url.protocol !== 'http:' && url.protocol !== 'https:' ) { return; }
					if ( DL.test( url.pathname ) ) {
						var file = url.pathname.split( '/' ).pop() || url.pathname;
						send( { t: 'e', ec: 'download', el: file.slice( 0, 190 ), p: window.location.pathname } );
						return;
					}
					if ( url.host === window.location.host ) { return; }
					send( { t: 'e', ec: 'outbound', el: ( url.host + url.pathname ).slice( 0, 190 ), p: window.location.pathname } );
				} catch ( err ) { /* ignore */ }
			}, true );

			document.addEventListener( 'submit', function ( e ) {
				try {
					var f = e.target;
					if ( ! f || f.nodeName !== 'FORM' ) { return; }
					var label = f.getAttribute( 'id' ) || f.getAttribute( 'name' ) || '';
					if ( ! label ) {
						var act = f.getAttribute( 'action' ) || '';
						label = act ? new URL( act, window.location.href ).pathname : window.location.pathname;
					}
					send( { t: 'e', ec: 'form', el: String( label ).slice( 0, 190 ), p: window.location.pathname } );
				} catch ( err ) { /* ignore */ }
			}, true );
		}
	} catch ( e ) {
		/* never let analytics break the page */
	}
}() );
