/**
 * Sample Prompts Manager
 *
 * Manages sample writing style prompts with modal editor, card-based UI,
 * and dropdown selection for quick insertion into writing directions.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.samplePrompts
 */

(function($) {
	'use strict';

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

	/**
	 * Gets admin data from global object.
	 *
	 * @return {Object} Admin data object.
	 */
	function getAdminData() {
		return window.agenticwpAdmin || {};
	}

	let $modal;
	let $manager;
	let $select;
	let $textarea;
	let nextIndex = 0;
	let maxPrompts = 0;

	/**
	 * Initializes sample prompts manager.
	 */
	function init() {
		$modal = $('.agenticwp-prompts-modal');
		$manager = $('.agenticwp-sample-prompts-manager');
		$select = $('#agenticwp-sample-prompts');
		$textarea = $('#agentic_wp_create_post_directions');

		bindModal();
		bindCards();
		bindManager();
		bindDropdown();
	}

	function bindModal() {
		const $toggleButton = $('.agenticwp-manage-prompts-toggle');
		const $closeButton = $('.agenticwp-modal-close');
		const $backdrop = $('.agenticwp-modal-backdrop');
		const $saveButton = $('.agenticwp-save-prompts');

		if (!$modal.length || !$toggleButton.length) {
			return;
		}

		function openModal() {
			$modal.addClass('is-visible');
			$('body').addClass('modal-open');

			setTimeout(function() {
				const $firstInput = $modal.find('input, textarea').first();
				if ($firstInput.length) {
					$firstInput.trigger('focus');
				}
			}, 300);
		}

		function closeModal() {
			$modal.removeClass('is-visible');
			$('body').removeClass('modal-open');
			$toggleButton.trigger('focus');
		}

		$toggleButton.on('click', function(event) {
			event.preventDefault();
			openModal();
		});

		$closeButton.on('click', function(event) {
			event.preventDefault();
			closeModal();
		});

		$backdrop.on('click', function(event) {
			if (event.target === this) {
				closeModal();
			}
		});

		$(document).on('keydown', function(event) {
			if (event.key === 'Escape' && $modal.is(':visible')) {
				closeModal();
			}
		});

		$saveButton.on('click', function(event) {
			event.preventDefault();
			saveWritingDirectionsFromModal($saveButton, closeModal);
		});
	}

	function bindCards() {
		if (!$modal || !$modal.length) {
			return;
		}

		$modal.on('click', '.agenticwp-prompt-card', function(event) {
			const $target = $(event.target);
			if ($target.is('input, textarea, button') || $target.closest('input, textarea, button').length) {
				return;
			}

			const $card = $(this);
			const $expanded = $card.find('.agenticwp-prompt-card-expanded');
			if ($expanded.is(':visible')) {
				return;
			}

			event.preventDefault();
			toggleCard($card);
		});

		$modal.on('click', '.agenticwp-prompt-card-expand', function(event) {
			event.preventDefault();
			event.stopPropagation();

			const $card = $(this).closest('.agenticwp-prompt-card');
			toggleCard($card);
		});

		$modal.on('input', '.agenticwp-sample-prompt-label', function() {
			const $card = $(this).closest('.agenticwp-prompt-card');
			const $title = $card.find('.agenticwp-prompt-card-title');
			const value = $(this).val().trim();

			$title.text(value || 'Untitled Prompt');
		});

		$modal.on('input', '.agenticwp-sample-prompt-content', function() {
			const $card = $(this).closest('.agenticwp-prompt-card');
			updateCardPreview($card, $(this).val());
		});
	}

	function toggleCard($card) {
		const $expanded = $card.find('.agenticwp-prompt-card-expanded');
		const $preview = $card.find('.agenticwp-prompt-card-preview');
		const $expandButton = $card.find('.agenticwp-prompt-card-expand .dashicons');

		const isExpanded = $expanded.is(':visible');
		$expanded.toggle(!isExpanded);
		$preview.toggle(isExpanded);

		if (isExpanded) {
			$expandButton.removeClass('dashicons-no-alt').addClass('dashicons-edit');
			$card.find('.agenticwp-prompt-card-expand').attr('aria-label', 'Edit prompt');
		} else {
			$expandButton.removeClass('dashicons-edit').addClass('dashicons-no-alt');
			$card.find('.agenticwp-prompt-card-expand').attr('aria-label', 'Collapse prompt');
			const $labelInput = $expanded.find('.agenticwp-sample-prompt-label');
			if ($labelInput.length) {
				$labelInput.trigger('focus');
			}
		}
	}

	function updateCardPreview($card, content) {
		let $preview = $card.find('.agenticwp-prompt-card-preview');

		if (!content) {
			$preview.hide();
			return;
		}

		const previewText = content.length > 100 ? content.substring(0, 100) + '…' : content;

		if (!$preview.length) {
			$preview = $('<div class="agenticwp-prompt-card-preview"></div>');
			$card.find('.agenticwp-prompt-card-header').after($preview);
		}

		$preview.text(previewText).show();
	}

	function bindManager() {
		if (!$manager.length) {
			return;
		}

		const $grid = $manager.find('.agenticwp-prompts-grid');
		const $template = $('#agenticwp-sample-prompt-template');
		const $addButton = $('.agenticwp-add-sample-prompt');
		const adminData = getAdminData();

		nextIndex = parseInt($manager.data('nextIndex'), 10);
		if (isNaN(nextIndex)) {
			nextIndex = $grid.children('.agenticwp-prompt-card').length;
		}

		const localMax = parseInt($manager.data('maxPrompts'), 10);
		maxPrompts = !isNaN(localMax) ? localMax : parseInt(adminData.promptsMaxCount || 0, 10) || 0;

		function addPrompt(forceAdd) {
			if (!forceAdd && maxPrompts && $grid.children('.agenticwp-prompt-card').length >= maxPrompts) {
				return;
			}

			if (!$template.length) {
				return;
			}

			const index = nextIndex++;
			const html = $template.html().replace(/__index__/g, index);
			const $card = $(html);

			$grid.append($card);

			const $expanded = $card.find('.agenticwp-prompt-card-expanded');
			const $icon = $card.find('.agenticwp-prompt-card-expand .dashicons');

			$expanded.show();
			$icon.removeClass('dashicons-edit').addClass('dashicons-no-alt');

			const $label = $card.find('.agenticwp-sample-prompt-label');
			if ($label.length) {
				$label.trigger('focus');
			}

			triggerUpdate();
		}

		$addButton.on('click', function(event) {
			event.preventDefault();
			addPrompt(false);
		});

		$manager.on('click', '.agenticwp-remove-sample-prompt', function(event) {
			event.preventDefault();

			const $card = $(this).closest('.agenticwp-prompt-card');
			$card.remove();

			if (!$grid.children('.agenticwp-prompt-card').length) {
				addPrompt(true);
			} else {
				triggerUpdate();
			}
		});

		$manager.on('input change', '.agenticwp-sample-prompt-label, .agenticwp-sample-prompt-content', function() {
			triggerUpdate();
		});

		triggerUpdate();
	}

	function bindDropdown() {
		if (!$select.length || !$textarea.length) {
			if (!$manager.length && $select.length) {
				refreshOptions();
			}
			return;
		}

		if ($manager.length) {
			$manager.on('agenticwpPromptListUpdated', function() {
				refreshOptions();
			});
			refreshOptions();
		} else {
			refreshOptions();
		}

		$select.on('change', function() {
			const selectedPrompt = $(this).val();

			if (!selectedPrompt) {
				return;
			}

			$textarea.val(selectedPrompt).trigger('input');
			$textarea.trigger('focus');
			$select.val('');
		});
	}

	function collectPrompts() {
		const prompts = [];
		const adminData = getAdminData();

		if ($manager.length) {
			$manager.find('.agenticwp-prompt-card').each(function() {
				const $card = $(this);
				const label = $.trim($card.find('.agenticwp-sample-prompt-label').val());
				const content = $card.find('.agenticwp-sample-prompt-content').val();

				if (!content) {
					return;
				}

				prompts.push({
					label: label || adminData.promptsDefaultLabel || 'Sample prompt',
					content: content
				});
			});
		} else if ($select.length) {
			$select.find('option').each(function() {
				const value = $(this).val();
				if (!value) {
					return;
				}

				prompts.push({
					label: $(this).text(),
					content: value
				});
			});
		}

		return prompts;
	}

	function refreshOptions() {
		if (!$select.length) {
			return;
		}

		const prompts = collectPrompts();
		const previousValue = $select.val();

		$select.find('option').not(':first').remove();

		prompts.forEach(function(prompt) {
			const $option = $('<option></option>').text(prompt.label).val(prompt.content);
			$select.append($option);
		});

		if (previousValue && prompts.some(function(prompt) { return prompt.content === previousValue; })) {
			$select.val(previousValue);
		} else {
			$select.val('');
		}

		$select.prop('disabled', prompts.length === 0);
	}

	function triggerUpdate() {
		if ($manager.length) {
			$manager.trigger('agenticwpPromptListUpdated');
		}
	}


	function saveWritingDirectionsFromModal($button, closeModal) {
		const adminData = getAdminData();
		const currentValue = $textarea.val();

		if (!adminData.nonces || !adminData.nonces.save_writing_directions || !adminData.nonces.save_sample_prompts) {
			AgenticWPAdmin.utils.logError('sample_prompts', {
				error: 'missing_nonce',
				field: 'writing_directions_and_sample_prompts',
				nonce_keys: 'save_writing_directions, save_sample_prompts'
			});
			updateButtonState($button, 'error');
			return;
		}

		updateButtonState($button, 'saving');

		AgenticWPAdmin.utils.postAction({
			action: 'agenticwp_save_writing_directions',
			nonce: adminData.nonces.save_writing_directions,
			data: { value: currentValue },
			onSuccess: function(response) {
				if (response && response.success) {
					saveSamplePromptsFromModal($button, closeModal);
				} else {
					const message = response && response.data && response.data.message ? response.data.message : 'Failed to save writing directions';
					const errorCode = response && response.data && response.data.code ? response.data.code : 'unknown';
					updateButtonState($button, 'error');
					AgenticWPAdmin.utils.logError('sample_prompts', {
						error: 'server_error',
						action: 'agenticwp_save_writing_directions',
						field: 'writing_directions',
						context: 'modal',
						message: message,
						code: errorCode
					});

					setTimeout(function() {
						updateButtonState($button, 'normal');
					}, 3000);
				}
			},
			onError: function(error) {
				updateButtonState($button, 'error');
				AgenticWPAdmin.utils.logError('sample_prompts', {
					error: 'ajax_error',
					action: 'agenticwp_save_writing_directions',
					field: 'writing_directions',
					context: 'modal',
					details: error
				});

				setTimeout(function() {
					updateButtonState($button, 'normal');
				}, 3000);
			}
		});
	}

	function saveSamplePromptsFromModal($button, closeModal) {
		const adminData = getAdminData();
		const prompts = collectPrompts();

		AgenticWPAdmin.utils.postAction({
			action: 'agenticwp_save_sample_prompts',
			nonce: adminData.nonces.save_sample_prompts,
			data: { prompts: prompts },
			onSuccess: function(response) {
				if (response && response.success) {
					updateButtonState($button, 'saved');

					setTimeout(function() {
						updateButtonState($button, 'normal');
						closeModal();
					}, 2000);
				} else {
					const message = response && response.data && response.data.message ? response.data.message : 'Failed to save style examples';
					const errorCode = response && response.data && response.data.code ? response.data.code : 'unknown';
					updateButtonState($button, 'error');
					AgenticWPAdmin.utils.logError('sample_prompts', {
						error: 'server_error',
						action: 'agenticwp_save_sample_prompts',
						field: 'sample_prompts',
						prompt_count: prompts.length,
						message: message,
						code: errorCode
					});

					setTimeout(function() {
						updateButtonState($button, 'normal');
					}, 3000);
				}
			},
			onError: function(error) {
				updateButtonState($button, 'error');
				AgenticWPAdmin.utils.logError('sample_prompts', {
					error: 'ajax_error',
					action: 'agenticwp_save_sample_prompts',
					field: 'sample_prompts',
					prompt_count: prompts.length,
					details: error
				});

				setTimeout(function() {
					updateButtonState($button, 'normal');
				}, 3000);
			}
		});
	}

	function updateButtonState($button, state) {
		$button.removeClass('saving saved');

		if (!$button.data('original-text')) {
			$button.data('original-text', $button.text());
		}

		const originalText = $button.data('original-text');

		switch (state) {
		case 'saving':
			$button.addClass('saving');
			$button.text('Saving...');
			$button.prop('disabled', true);
			break;
		case 'saved':
			$button.addClass('saved');
			$button.text('Saved');
			$button.prop('disabled', true);
			break;
		case 'error':
			$button.text(originalText);
			$button.prop('disabled', false);
			break;
		case 'normal':
		default:
			$button.text(originalText);
			$button.prop('disabled', false);
			break;
		}
	}


	AgenticWPAdmin.samplePrompts = {
		init: init
	};
})(jQuery);
