/**
 * Job Completion Monitor
 *
 * Polls background job status and displays toast notifications when jobs
 * complete or fail, with post title extraction for relevant job types.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 */

/**
 * Background job completion monitor.
 *
 * @class
 * @since 1.0.0
 */
class JobCompletionMonitor {
	/**
	 * Initializes job completion monitor.
	 */
	constructor() {
		this.lastJobStates = this.getStoredJobStates();
		this.pollInterval = 5000;
		this.intervalId = null;
		this.enabled = true;

		this.init();
	}

	/**
	 * Initializes monitoring if dependencies are available.
	 */
	init() {
		if (typeof agenticwp_ajax === 'undefined' || !agenticwp_ajax.ajax_url) {
			return;
		}

		if (typeof window.AgenticWPToast === 'undefined') {
			return;
		}

		this.startMonitoring();
	}

	/**
	 * Starts polling interval for job status.
	 */
	startMonitoring() {
		if (this.intervalId) {
			clearInterval(this.intervalId);
		}

		this.intervalId = setInterval(() => {
			if (this.enabled) {
				this.checkJobStatus();
			}
		}, this.pollInterval);

		if (this.enabled) {
			this.checkJobStatus();
		}
	}

	/**
	 * Stops polling interval.
	 */
	stopMonitoring() {
		if (this.intervalId) {
			clearInterval(this.intervalId);
			this.intervalId = null;
		}
	}

	/**
	 * Enables or disables monitoring.
	 *
	 * @param {boolean} enabled - Whether to enable monitoring.
	 */
	setEnabled(enabled) {
		this.enabled = enabled;
		if (enabled) {
			this.startMonitoring();
		} else {
			this.stopMonitoring();
		}
	}

	/**
	 * Checks current job status and processes updates.
	 *
	 * @return {Promise<void>}
	 */
	async checkJobStatus() {
		try {
			const response = await this.fetchJobStatus();
			if (response.success && response.data && response.data.jobs) {
				this.processJobUpdates(response.data.jobs);
			}
		} catch (error) {
		}
	}

	/**
	 * Fetches job status from API.
	 *
	 * @return {Promise<Object>} API response.
	 */
	async fetchJobStatus() {
		const formData = new FormData();
		formData.append('action', 'agenticwp_get_job_status');
		formData.append('_ajax_nonce', agenticwp_ajax.job_status_nonce);

		const response = await fetch(agenticwp_ajax.ajax_url, {
			method: 'POST',
			body: formData
		});

		if (!response.ok) {
			const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
			throw error;
		}

		return await response.json();
	}

	/**
	 * Processes job updates and shows notifications for newly completed/failed jobs.
	 *
	 * @param {Object} currentJobs - Current job states.
	 */
	processJobUpdates(currentJobs) {
		Object.entries(currentJobs).forEach(([jobId, jobData]) => {
			const lastState = this.lastJobStates[jobId];

			if (this.isNewlyCompleted(jobData, lastState)) {
				this.showCompletionToast(jobData);
			} else if (this.isNewlyFailed(jobData, lastState)) {
				this.showFailureToast(jobData);
			}
		});

		this.storeJobStates(currentJobs);
	}

	isNewlyCompleted(currentJob, lastJob) {
		if (!currentJob || !lastJob) return false;

		const wasInProgress = ['queued', 'polling'].includes(lastJob.status);
		const isNowComplete = currentJob.status === 'complete';

		return wasInProgress && isNowComplete;
	}

	isNewlyFailed(currentJob, lastJob) {
		if (!currentJob || !lastJob) return false;

		const wasInProgress = ['queued', 'polling'].includes(lastJob.status);
		const isNowFailed = currentJob.status === 'failed';

		return wasInProgress && isNowFailed;
	}

	showCompletionToast(jobData) {
		const message = this.getCompletionMessage(jobData);
		window.AgenticWPToast.showSuccess(message, {
			duration: 7000
		});
	}

	showFailureToast(jobData) {
		const message = this.getFailureMessage(jobData);
		window.AgenticWPToast.showError(message, {
			duration: 10000
		});
	}

	getCompletionMessage(jobData) {
		const jobType = this.extractJobType(jobData);

		switch (jobType) {
		case 'post_creation':
			const postTitle = this.extractPostTitle(jobData);
			return postTitle
				? `Post "${postTitle}" created successfully`
				: 'Post created successfully';


		case 'content_generation':
			return 'Content generation completed successfully';

		default:
			return 'Background task completed successfully';
		}
	}

	getFailureMessage(jobData) {
		const errorMessage = jobData.error_message || 'Unknown error';
		return `Background task failed: ${errorMessage}`;
	}

	extractJobType(jobData) {
		if (jobData.job_data) {
			const data = typeof jobData.job_data === 'string'
				? JSON.parse(jobData.job_data)
				: jobData.job_data;

			if (data.tools && data.tools.some(tool => tool.includes('start_post') || tool.includes('finalize_post'))) {
				return 'post_creation';
			}

		}

		return 'unknown';
	}

	extractPostTitle(jobData) {
		try {
			if (jobData.job_data) {
				const data = typeof jobData.job_data === 'string'
					? JSON.parse(jobData.job_data)
					: jobData.job_data;

				return data.post_title || data.title || null;
			}
		} catch (e) {
		}

		return null;
	}

	getStoredJobStates() {
		try {
			const stored = localStorage.getItem('agenticwp_job_states');
			return stored ? JSON.parse(stored) : {};
		} catch (e) {
			return {};
		}
	}

	storeJobStates(jobStates) {
		try {
			this.lastJobStates = { ...jobStates };
			localStorage.setItem('agenticwp_job_states', JSON.stringify(jobStates));
		} catch (e) {
		}
	}

}

window.AgenticWPJobMonitor = JobCompletionMonitor;