/**
 * Dropdown Auto-Save functionality for AgenticWP admin settings.
 *
 * Provides debounced auto-save functionality for select and input fields
 * with visual feedback using border color changes.
 */

window.AgenticWPAdmin = window.AgenticWPAdmin || {};

AgenticWPAdmin.DropdownAutoSave = (function($) {
	'use strict';

	const fieldConfigs = {
		'agentic_wp_reasoning_effort': {
			action: 'agenticwp_save_reasoning_effort',
			nonce: 'save_reasoning_effort'
		},
		'agentic_wp_max_output_tokens': {
			action: 'agenticwp_save_max_output_tokens',
			nonce: 'save_max_output_tokens'
		},
		'agentic_wp_message_history_limit': {
			action: 'agenticwp_save_message_history_limit',
			nonce: 'save_message_history_limit'
		},
		'agentic_wp_enable_toast_notifications': {
			action: 'agenticwp_save_toast_notifications',
			nonce: 'save_toast_notifications'
		},
		'agentic_wp_enable_web_search': {
			action: 'agenticwp_save_web_search',
			nonce: 'save_web_search'
		},
		'agentic_wp_create_post_directions': {
			action: 'agenticwp_save_writing_directions',
			nonce: 'save_writing_directions',
			timeout: 3000,
			events: ['input', 'blur']
		}
	};

	const saveTimeouts = {};

	/**
	 * Get admin data from the global window object
	 */
	function getAdminData() {
		return window.agenticwpAdmin || {};
	}

	/**
	 * Initialize auto-save functionality
	 */
	function init() {
		Object.keys(fieldConfigs).forEach(function(fieldName) {
			const $field = $('[name="' + fieldName + '"]');
			if ($field.length) {
				const config = fieldConfigs[fieldName];
				const isCheckbox = $field.is(':checkbox');
				let events;
				if (config.events) {
					events = config.events.join(' ');
				} else {
					events = isCheckbox ? 'change' : 'change input';
				}

				$field.on(events, function(e) {
					handleFieldChange(this, fieldName, e.type);
				});
			}
		});
	}

	/**
	 * Handle field change with debouncing
	 * @param {HTMLElement} field - The field element that changed
	 * @param {string} fieldName - The field name from fieldConfigs
	 * @param {string} eventType - The type of event that triggered the change
	 */
	function handleFieldChange(field, fieldName, eventType) {
		const $field = $(field);
		const config = fieldConfigs[fieldName];
		const isCheckbox = $field.is(':checkbox');
		const value = isCheckbox ? ($field.is(':checked') ? '1' : '0') : $field.val();

		if (saveTimeouts[fieldName]) {
			clearTimeout(saveTimeouts[fieldName]);
		}

		updateFieldState(field, 'saving');

		if (isCheckbox || eventType === 'blur') {
			saveField(field, fieldName, value);
		} else {
			const timeout = config.timeout || 2000;
			saveTimeouts[fieldName] = setTimeout(function() {
				saveField(field, fieldName, value);
			}, timeout);
		}
	}

	/**
	 * Save field value via AJAX
	 * @param {HTMLElement} field - The field element
	 * @param {string} fieldName - The field name from fieldConfigs
	 * @param {string} value - The field value to save
	 */
	function saveField(field, fieldName, value) {
		const config = fieldConfigs[fieldName];
		const adminData = getAdminData();

		if (!config) {
			AgenticWPAdmin.utils.logError('dropdown_autosave', {
				error: 'configuration_error',
				field: fieldName,
				value: value
			});
			updateFieldState(field, 'error');
			return;
		}

		if (!adminData.nonces || !adminData.nonces[config.nonce]) {
			AgenticWPAdmin.utils.logError('dropdown_autosave', {
				error: 'missing_nonce',
				field: fieldName,
				nonce_key: config.nonce,
				value: value
			});
			updateFieldState(field, 'error');
			return;
		}

		AgenticWPAdmin.utils.postAction({
			action: config.action,
			nonce: adminData.nonces[config.nonce],
			data: { value: value },
			onSuccess: function(response) {
				if (response && response.success) {
					updateFieldState(field, 'saved');

					setTimeout(function() {
						updateFieldState(field, 'normal');
					}, 2000);
				} else {
					const message = response && response.data && response.data.message ? response.data.message : 'Failed to save field';
					const errorCode = response && response.data && response.data.code ? response.data.code : 'unknown';
					updateFieldState(field, 'error');
					AgenticWPAdmin.utils.logError('dropdown_autosave', {
						error: 'server_error',
						field: fieldName,
						action: config.action,
						value: value,
						message: message,
						code: errorCode
					});

					setTimeout(function() {
						updateFieldState(field, 'normal');
					}, 3000);
				}
			},
			onError: function(error) {
				updateFieldState(field, 'error');
				AgenticWPAdmin.utils.logError('dropdown_autosave', {
					error: 'ajax_error',
					field: fieldName,
					action: config.action,
					value: value,
					details: error
				});

				setTimeout(function() {
					updateFieldState(field, 'normal');
				}, 3000);
			}
		});
	}

	/**
	 * Update field visual state with CSS classes
	 * @param {HTMLElement} field - The field element
	 * @param {string} state - The state ('saving', 'saved', 'error', 'normal')
	 */
	function updateFieldState(field, state) {
		const $field = $(field);
		const isCheckbox = $field.is(':checkbox');
		const $targetElement = isCheckbox ? $field.closest('.agenticwp-checkbox-field') : $field;

		$targetElement.removeClass('agenticwp-field-saving agenticwp-field-saved agenticwp-field-error');

		switch (state) {
		case 'saving':
			$targetElement.addClass('agenticwp-field-saving');
			break;
		case 'saved':
			$targetElement.addClass('agenticwp-field-saved');
			break;
		case 'error':
			$targetElement.addClass('agenticwp-field-error');
			break;
		case 'normal':
		default:
			break;
		}
	}

	return {
		init: init
	};

})(jQuery);
