/**
 * Heartbeat Health Monitor
 *
 * Sends health check requests via WordPress Heartbeat API to detect
 * stale jobs and trigger loopback processing when needed.
 *
 * @package AgenticWP
 */

/* global jQuery, wp */

(function ($) {
	'use strict';

	/**
	 * Initialize heartbeat health monitoring.
	 */
	function init() {
		// Ensure heartbeat API is available.
		if (typeof wp === 'undefined' || typeof wp.heartbeat === 'undefined') {
			return;
		}

		// Add health check flag to heartbeat data.
		$(document).on('heartbeat-send', function (e, data) {
			data.agenticwp_health_check = true;
		});

		// Handle heartbeat response.
		$(document).on('heartbeat-tick', function (e, data) {
			if (data.agenticwp_health) {
				handleHealthResponse(data);
			}
		});
	}

	/**
	 * Handle health check response from server.
	 *
	 * @param {Object} data Response data containing health info.
	 */
	function handleHealthResponse(data) {
		var health = data.agenticwp_health;

		// Log health status for debugging (only when WP_DEBUG is enabled).
		if (
			typeof window.agenticwpAdmin !== 'undefined' &&
			window.agenticwpAdmin.debug
		) {
			console.log('[AgenticWP Health]', {
				pending: health.pending,
				stale: health.stale,
				boostTriggered: data.agenticwp_boost_triggered || false,
			});
		}

		// Dispatch custom event for other components to react.
		$(document).trigger('agenticwp:health-check', [
			{
				pending: health.pending,
				stale: health.stale,
				boostTriggered: data.agenticwp_boost_triggered || false,
			},
		]);
	}

	// Initialize on document ready.
	$(document).ready(init);
})(jQuery);
