/**
 * IGIT Related Posts – Async Loader
 *
 * When load_async is enabled the server outputs a lightweight
 * .igit-rpwt-placeholder div instead of the full HTML. This script
 * fires an AJAX request for each placeholder and swaps in the real content.
 *
 * Data injected server-side via wp_localize_script as `igitRpwt`:
 *   ajaxUrl  — WordPress admin-ajax.php URL
 *   action   — WP action name ('igit_rpwt_load')
 *   nonce    — wp_nonce for request verification
 */
( function () {
	'use strict';

	/**
	 * Load related posts for a single placeholder element.
	 *
	 * @param {HTMLElement} el
	 */
	function loadPlaceholder( el ) {
		var postId = el.getAttribute( 'data-post-id' );
		var args   = el.getAttribute( 'data-args' ) || '{}';

		if ( ! postId ) {
			return;
		}

		var body = new URLSearchParams();
		body.append( 'action',  igitRpwt.action );
		body.append( 'nonce',   igitRpwt.nonce );
		body.append( 'post_id', postId );
		body.append( 'args',    args );

		fetch( igitRpwt.ajaxUrl, {
			method:      'POST',
			credentials: 'same-origin',
			headers:     { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			body:        body.toString(),
		} )
		.then( function ( response ) {
			if ( ! response.ok ) {
				throw new Error( 'Network response was not ok: ' + response.status );
			}
			return response.json();
		} )
		.then( function ( data ) {
			if ( data.success && data.data && data.data.html ) {
				var wrapper = document.createElement( 'div' );
				wrapper.innerHTML = data.data.html;
				// Move ALL child nodes (e.g. orphan-fix <style> + posts <div>) into a
				// fragment so nothing is silently discarded by firstElementChild.
				var fragment = document.createDocumentFragment();
				while ( wrapper.firstChild ) {
					fragment.appendChild( wrapper.firstChild );
				}
				el.parentNode.insertBefore( fragment, el );
				el.parentNode.removeChild( el );
				// Re-initialise carousel if the injected HTML contains one.
				if ( window.igitRpwtCarousel ) {
					window.igitRpwtCarousel.init();
				}
			} else {
				// No results or error — silently remove the placeholder.
				el.parentNode.removeChild( el );
			}
		} )
		.catch( function () {
			// On network error remove the placeholder rather than leaving a spinner.
			if ( el.parentNode ) {
				el.parentNode.removeChild( el );
			}
		} );
	}

	/**
	 * Kick off loading for every placeholder on the page.
	 * Uses IntersectionObserver when available so off-screen widgets are only
	 * fetched as they approach the viewport (lazy AJAX).
	 */
	function init() {
		var placeholders = document.querySelectorAll( '.igit-rpwt-placeholder' );
		if ( ! placeholders.length ) {
			return;
		}

		if ( 'IntersectionObserver' in window ) {
			var observer = new IntersectionObserver(
				function ( entries, obs ) {
					entries.forEach( function ( entry ) {
						if ( entry.isIntersecting ) {
							obs.unobserve( entry.target );
							loadPlaceholder( entry.target );
						}
					} );
				},
				{ rootMargin: '200px' } // start loading 200px before visible
			);
			placeholders.forEach( function ( el ) { observer.observe( el ); } );
		} else {
			// Fallback: load all immediately.
			placeholders.forEach( loadPlaceholder );
		}
	}

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

// ─────────────────────────────────────────────────────────────────────────────
// Click Tracking
// Intercepts clicks on related-post links that carry data-igit-source /
// data-igit-target attributes and fires a fire-and-forget analytics request.
// Uses navigator.sendBeacon when available so the record is sent even if the
// page navigates away before fetch resolves.
// ─────────────────────────────────────────────────────────────────────────────
( function () {
	'use strict';

	function initClickTracking() {
		if ( typeof igitRpwt === 'undefined' || ! igitRpwt.trackNonce ) {
			return;
		}

		document.addEventListener( 'click', function ( e ) {
			var a = e.target.closest( 'a[data-igit-source]' );
			if ( ! a ) { return; }

			var source = a.getAttribute( 'data-igit-source' );
			var target = a.getAttribute( 'data-igit-target' );
			if ( ! source || ! target ) { return; }

			var body = new URLSearchParams();
			body.append( 'action', igitRpwt.trackAction );
			body.append( 'nonce',  igitRpwt.trackNonce );
			body.append( 'source', source );
			body.append( 'target', target );
			body.append( 'click_source', 'widget' );

			// sendBeacon is preferred: it sends even if the page unloads immediately.
			if ( navigator.sendBeacon ) {
				navigator.sendBeacon(
					igitRpwt.ajaxUrl,
					new Blob( [ body.toString() ], { type: 'application/x-www-form-urlencoded' } )
				);
			} else {
				fetch( igitRpwt.ajaxUrl, {
					method:      'POST',
					credentials: 'same-origin',
					headers:     { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
					body:        body.toString(),
					keepalive:   true,
				} ).catch( function () {} );
			}
		} );
	}

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