/**
 * Truong Thinh SEO Console — lightweight, privacy-respecting engagement tracker.
 * No PII collected: only a random per-browser id (localStorage, falls back to
 * a first-party cookie), scroll milestones, CTA/form/outbound clicks, and a
 * throttled text-selection signal. Deferred, sends via sendBeacon/fetch.
 */
( function () {
	'use strict';
	if ( typeof window.ttseoEng === 'undefined' ) {
		return;
	}
	var cfg = window.ttseoEng; // { ajaxUrl, postId }
	if ( ! cfg.postId ) {
		return;
	}

	/* ---------- anon id (no PII) ---------- */
	function randomId() {
		if ( window.crypto && window.crypto.getRandomValues ) {
			var arr = new Uint8Array( 16 );
			window.crypto.getRandomValues( arr );
			return Array.prototype.map.call( arr, function ( b ) { return b.toString( 16 ).padStart( 2, '0' ); } ).join( '' );
		}
		return 'a' + Math.random().toString( 16 ).slice( 2 ) + Date.now().toString( 16 );
	}
	function getCookie( name ) {
		var m = document.cookie.match( new RegExp( '(?:^|; )' + name + '=([^;]*)' ) );
		return m ? decodeURIComponent( m[1] ) : '';
	}
	function setCookie( name, val, days ) {
		var d = new Date();
		d.setTime( d.getTime() + days * 86400000 );
		document.cookie = name + '=' + encodeURIComponent( val ) + ';expires=' + d.toUTCString() + ';path=/;SameSite=Lax';
	}
	function getAnonId() {
		var id = '';
		try {
			id = window.localStorage.getItem( 'ttseo_anon' );
		} catch ( e ) {}
		if ( ! id ) {
			id = getCookie( 'ttseo_anon' );
		}
		if ( ! id ) {
			id = randomId();
		}
		try {
			window.localStorage.setItem( 'ttseo_anon', id );
		} catch ( e ) {}
		setCookie( 'ttseo_anon', id, 365 );
		return id;
	}
	function getSessionStart() {
		var s = '';
		try {
			s = window.sessionStorage.getItem( 'ttseo_session_start' );
		} catch ( e ) {}
		if ( ! s ) {
			s = new Date().toISOString().slice( 0, 19 ).replace( 'T', ' ' );
			try {
				window.sessionStorage.setItem( 'ttseo_session_start', s );
			} catch ( e ) {}
		}
		return s;
	}

	var anonId   = getAnonId();
	var sessStart = getSessionStart();
	var pageStart = Date.now();

	/* ---------- sender ---------- */
	function send( type, detail ) {
		var payload = new URLSearchParams();
		payload.set( 'action', 'ttseo_track' );
		payload.set( 'post_id', cfg.postId );
		payload.set( 'event_type', type );
		payload.set( 'event_detail', detail || '' );
		payload.set( 'anon_id', anonId );
		payload.set( 'session_start', sessStart );

		var body = payload.toString();
		var url  = cfg.ajaxUrl;
		try {
			if ( navigator.sendBeacon ) {
				var blob = new Blob( [ body ], { type: 'application/x-www-form-urlencoded' } );
				navigator.sendBeacon( url, blob );
				return;
			}
		} catch ( e ) {}
		try {
			fetch( url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: body, keepalive: true, credentials: 'omit' } );
		} catch ( e ) {}
	}

	/* ---------- scroll depth milestones ---------- */
	var milestones = { 25: false, 50: false, 75: false, 100: false };
	var maxScroll  = 0;
	var reached80At = null;
	var readSent   = false;
	var ticking    = false;

	function scrollPercent() {
		var doc = document.documentElement;
		var scrollTop = window.pageYOffset || doc.scrollTop || 0;
		var winH = window.innerHeight || doc.clientHeight;
		var docH = Math.max( doc.scrollHeight, document.body ? document.body.scrollHeight : 0 );
		if ( docH <= winH ) {
			return 100;
		}
		return Math.min( 100, Math.round( ( ( scrollTop + winH ) / docH ) * 100 ) );
	}

	function onScroll() {
		if ( ticking ) {
			return;
		}
		ticking = true;
		window.requestAnimationFrame( function () {
			var pct = scrollPercent();
			if ( pct > maxScroll ) {
				maxScroll = pct;
			}
			[ 25, 50, 75, 100 ].forEach( function ( m ) {
				if ( ! milestones[ m ] && pct >= m ) {
					milestones[ m ] = true;
					send( 'scroll_depth', m + '%' );
				}
			} );
			if ( pct >= 80 && ! reached80At ) {
				reached80At = Date.now();
			}
			maybeSendReadCompletion();
			ticking = false;
		} );
	}

	function maybeSendReadCompletion() {
		if ( readSent || ! reached80At ) {
			return;
		}
		if ( Date.now() - pageStart >= 30000 ) {
			readSent = true;
			send( 'read_complete', Math.round( ( Date.now() - pageStart ) / 1000 ) + 's' );
		}
	}
	window.addEventListener( 'scroll', onScroll, { passive: true } );
	setInterval( maybeSendReadCompletion, 5000 );

	/* ---------- CTA clicks ---------- */
	document.addEventListener( 'click', function ( e ) {
		var el = e.target.closest ? e.target.closest( '.ttseo-cta-btn' ) : null;
		if ( el ) {
			var which = el.classList.contains( 'ttseo-cta-btn-secondary' ) ? 'secondary' : 'primary';
			send( 'cta_click', el.getAttribute( 'data-ttseo-cta' ) || which );
		}
		var out = e.target.closest ? e.target.closest( 'a[href^="tel:"], a[href*="wa.me"], a[href*="zalo"]' ) : null;
		if ( out ) {
			send( 'outbound_contact_click', out.getAttribute( 'href' ) || '' );
		}
	} );

	/* ---------- CF7 submit ---------- */
	document.addEventListener( 'wpcf7submit', function ( e ) {
		var id = ( e.detail && e.detail.contactFormId ) ? e.detail.contactFormId : '';
		send( 'form_submit', 'cf7-' + id );
	}, false );

	/* ---------- text selection (throttled) ---------- */
	var lastSelSent = 0;
	function onSelection() {
		var sel = window.getSelection ? window.getSelection().toString() : '';
		if ( ! sel || sel.trim().length < 3 ) {
			return;
		}
		var now = Date.now();
		if ( now - lastSelSent < 5000 ) {
			return;
		}
		lastSelSent = now;
		send( 'text_selection', String( sel.length ) + 'chars' );
	}
	document.addEventListener( 'selectionchange', function () {
		// selectionchange fires very often; debounce on mouseup/keyup instead.
	} );
	document.addEventListener( 'mouseup', onSelection );
	document.addEventListener( 'keyup', function ( e ) {
		if ( e.shiftKey ) {
			onSelection();
		}
	} );

	/* ---------- page view (fires once, on load) ---------- */
	send( 'page_view', '' );
} )();
