/**
 * PressConduit live reload.
 *
 * Polls /wp-json/pressconduit/v1/recent-changes every 2.5s and shows a toast
 * when the currently-logged-in user fires a change. Idle timeout 5 min.
 */
(function () {
	'use strict';

	var cfg = window.pcdDcLiveReload;
	if ( ! cfg || ! cfg.endpoint ) return;

	var endpoint     = cfg.endpoint;
	var nonce        = cfg.nonce;
	var isAdmin      = cfg.isAdmin === '1';
	var currentPost  = parseInt( cfg.postId, 10 ) || 0;
	var currentUser  = parseInt( cfg.userId, 10 ) || 0;
	var POLL_MS      = 2500;
	var IDLE_MS      = 5 * 60 * 1000;
	var TOAST_MS     = 15000;

	var lastSeen    = 0;
	var lastChange  = Date.now();
	var timer       = null;
	var toastTimer  = null;

	function poll() {
		if ( Date.now() - lastChange > IDLE_MS ) {
			clearInterval( timer );
			return;
		}

		var url = endpoint + ( endpoint.indexOf( '?' ) !== -1 ? '&' : '?' ) + 'since=' + lastSeen;
		fetch( url, {
			headers: { 'X-WP-Nonce': nonce },
			credentials: 'same-origin',
		} )
			.then( function ( r ) { return r.ok ? r.json() : null; } )
			.then( function ( data ) {
				if ( ! data || ! data.changes || ! data.changes.length ) return;

				// First poll — record the latest timestamp without acting (don't show toasts for changes that happened before we loaded).
				if ( lastSeen === 0 ) {
					lastSeen = data.changes[ data.changes.length - 1 ].timestamp;
					return;
				}

				for ( var i = 0; i < data.changes.length; i++ ) {
					handleChange( data.changes[ i ] );
				}
				lastSeen   = data.changes[ data.changes.length - 1 ].timestamp;
				lastChange = Date.now();
			} )
			.catch( function () {} );
	}

	function handleChange( change ) {
		var action      = change.action || {};
		var changeUser  = change.user_id || 0;
		var changedPost = change.post_id || 0;
		var force       = action.force || false;
		var label       = action.label || 'Refresh';

		// Only notify the user whose AI session caused the change.
		if ( ! currentUser || changeUser !== currentUser ) return;

		var navUrl = isAdmin ? ( action.admin_url || action.url || '' ) : ( action.url || '' );

		// Force navigation — no toast.
		if ( force && navUrl ) {
			window.location.href = navUrl;
			return;
		}

		if ( isAdmin ) {
			// Same post the user is editing → auto-reload to show the AI's edits.
			if ( currentPost && changedPost && currentPost === changedPost ) {
				location.reload();
			} else {
				showToast( change.summary || 'AI made a change', navUrl, label );
			}
		} else if ( navUrl ) {
			if ( location.href === navUrl || location.href === navUrl + '/' ) {
				location.reload();
			} else {
				window.location.href = navUrl;
			}
		} else {
			location.reload();
		}
	}

	function removeToast() {
		var el = document.getElementById( 'pcd-pc-toast' );
		if ( el ) el.remove();
		if ( toastTimer ) {
			clearTimeout( toastTimer );
			toastTimer = null;
		}
	}

	function escHtml( str ) {
		var d = document.createElement( 'div' );
		d.textContent = String( str );
		return d.innerHTML;
	}

	function showToast( summary, url, label ) {
		removeToast();
		var btnLabel = label || ( url ? 'View' : 'Refresh' );
		var actionBtn;
		if ( url ) {
			actionBtn = '<a href="' + url + '" class="pcd-pc-toast__btn" target="_self">' + escHtml( btnLabel ) + '</a>';
		} else {
			actionBtn = '<button type="button" class="pcd-pc-toast__btn" onclick="location.reload()">' + escHtml( btnLabel ) + '</button>';
		}

		var toast       = document.createElement( 'div' );
		toast.id        = 'pcd-pc-toast';
		toast.innerHTML =
			'<span class="pcd-pc-toast__dot"></span>' +
			'<span class="pcd-pc-toast__text">' + escHtml( summary ) + '</span>' +
			actionBtn +
			'<button type="button" class="pcd-pc-toast__close" aria-label="Dismiss" onclick="this.parentElement.remove()">&times;</button>';
		document.body.appendChild( toast );

		// Auto-dismiss only if there's no action URL (i.e., generic refresh).
		if ( ! url ) {
			toastTimer = setTimeout( removeToast, TOAST_MS );
		}
	}

	timer = setInterval( poll, POLL_MS );
	poll();
} )();
