/**
 * Actions Manager
 *
 * Manages custom and built-in AI action shortcuts with categories, modal editor,
 * inline category management, and tabbed interface.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.actionsManager
 */

(function($) {
	'use strict';

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

	/**
	 * Actions manager object.
	 *
	 * @type {Object}
	 */
	AgenticWPAdmin.actionsManager = {
		init: function() {
			this.bindEvents();
		},

		bindEvents: function() {
			$(document).on('click', '.agenticwp-tab-button', this.handleTabSwitch.bind(this));
			$(document).on('change', '.agenticwp-category-select', this.handleCategoryFilter.bind(this));
			$(document).on('click', '.agenticwp-add-action', this.handleAddAction.bind(this));
			$(document).on('click', '.agenticwp-action-delete', this.handleDeleteAction.bind(this));
			$(document).on('input', '.agenticwp-action-name', this.handleActionNameChange.bind(this));
			$(document).on('click', '.agenticwp-manage-groups', this.handleManageGroups.bind(this));
			$(document).on('click', '.agenticwp-add-group-inline', this.handleAddGroupInline.bind(this));
			$(document).on('click', '.agenticwp-save-group-inline', this.handleSaveGroupInline.bind(this));
			$(document).on('click', '.agenticwp-cancel-group-inline', this.handleCancelGroupInline.bind(this));
			$(document).on('click', '.agenticwp-category-delete', this.handleDeleteCategory.bind(this));
			$(document).on('click', '.agenticwp-clear-unused-categories', this.handleClearUnusedCategories.bind(this));
			$(document).on('change', '#agenticwp-new-action-category', this.handleCategoryDropdownChange.bind(this));
			$(document).on('click', '.agenticwp-modal-close, .agenticwp-cancel-action', this.handleCloseModal.bind(this));
			$(document).on('click', '.agenticwp-modal-backdrop', this.handleBackdropClick.bind(this));
			$(document).on('click', '.agenticwp-save-action', this.handleSaveAction.bind(this));
			$(document).on('keydown', this.handleKeydown.bind(this));
			$(document).on('input keyup paste', '#agenticwp-new-action-prompt', this.handleNewActionPromptChange.bind(this));
			$(document).on('input keyup paste', '.agenticwp-action-prompt', this.handleActionPromptChange.bind(this));
		},

		handleTabSwitch: function(e) {
			e.preventDefault();
			const $button = $(e.currentTarget);
			const targetTab = $button.data('tab');

			if ($button.hasClass('active')) {
				return;
			}

			$('.agenticwp-tab-button').removeClass('active');
			$button.addClass('active');
			$('.agenticwp-tab-content').removeClass('active');
			$(`.agenticwp-tab-${targetTab}`).addClass('active');
			$(`.agenticwp-tab-${targetTab} .agenticwp-category-select`).val('').trigger('change');
		},

		handleCategoryFilter: function(e) {
			const $select = $(e.currentTarget);
			const selectedCategory = $select.val();
			const activeTab = $select.data('tab');
			const $tabContent = $(`.agenticwp-tab-${activeTab}`);
			const $cards = $tabContent.find('.agenticwp-action-card');

			if (!selectedCategory) {
				$tabContent.removeClass('filtered');
				$cards.removeClass('visible');
			} else {
				$tabContent.addClass('filtered');
				$cards.removeClass('visible');
				$cards.filter(`[data-category="${selectedCategory}"]`).addClass('visible');
			}
		},

		handleManageGroups: function(e) {
			e.preventDefault();
			this.openManageGroupsModal();
		},

		handleAddAction: function(e) {
			e.preventDefault();
			const $customTabButton = $('.agenticwp-tab-button[data-tab="custom"]');
			if (!$customTabButton.hasClass('active')) {
				$customTabButton.trigger('click');
			}
			this.openModal();
		},

		handleDeleteAction: function(e) {
			e.preventDefault();
			e.stopPropagation();

			const $button = $(e.currentTarget);
			const actionKey = $button.data('action-key');
			const $card = $button.closest('.agenticwp-action-card');
			const adminData = window.agenticwpAdmin || {};

			if (!adminData.nonces || !adminData.nonces.delete_action) {
				AgenticWPAdmin.utils.logError('missing_nonce', { operation: 'action_delete', action_key: actionKey });
				AgenticWPAdmin.utils.showNotice('Security check failed. Please refresh the page.', 'error');
				return;
			}

			AgenticWPAdmin.utils.toggleButtonLoading($button, true, '');
			$button.find('.dashicons').removeClass('dashicons-trash').addClass('dashicons-update');

			AgenticWPAdmin.utils.postAction({
				action: 'agenticwp_delete_action',
				nonce: adminData.nonces.delete_action,
				data: { action_key: actionKey },
				onSuccess: (response) => {
					if (response.success) {
						if (window.AgenticWPToast && typeof window.AgenticWPToast.showSuccess === 'function') {
							window.AgenticWPToast.showSuccess(response.data.message || 'Shortcut deleted successfully!');
						}
						$card.fadeOut(200, function() {
							$(this).remove();
							AgenticWPAdmin.actionsManager.updateCategoryFilter();
						});
					} else {
						AgenticWPAdmin.utils.logError('action_delete_failed', {
							action_key: actionKey,
							error_message: response.data.message || 'Unknown error',
							error_code: response.data.code || 'unknown'
						});
						AgenticWPAdmin.utils.toggleButtonLoading($button, false);
						$button.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-trash');
						AgenticWPAdmin.utils.showNotice(response.data.message || 'Failed to delete shortcut. Please try again.', 'error');
					}
				},
				onError: (error) => {
					AgenticWPAdmin.utils.logError('action_delete_error', {
						action_key: actionKey,
						error: String(error)
					});
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
					$button.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-trash');
					AgenticWPAdmin.utils.showNotice('Network error occurred. Please try again.', 'error');
				}
			});
		},


		handleActionNameChange: function(e) {
			const $input = $(e.currentTarget);
			const newName = $input.val();
			if (newName.length > 100) {
				$input.val(newName.substring(0, 100));
			}
		},

		handleAddGroupInline: function(e) {
			e.preventDefault();
			$('.agenticwp-add-group-form').slideDown(200);
			$('.agenticwp-add-group-inline').prop('disabled', true);
			$('#agenticwp-inline-group-name').focus();
		},

		handleCancelGroupInline: function(e) {
			e.preventDefault();
			$('.agenticwp-add-group-form').slideUp(200);
			$('.agenticwp-add-group-inline').prop('disabled', false);
			$('#agenticwp-inline-group-name').val('');
			$('.agenticwp-group-error').hide().text('');
		},

		handleSaveGroupInline: function(e) {
			e.preventDefault();
			const $button = $(e.currentTarget);
			const categoryName = $('#agenticwp-inline-group-name').val().trim();
			const $errorSpan = $('.agenticwp-group-error');

			$errorSpan.hide().text('');

			if (!categoryName) {
				$errorSpan.text('Group name is required.').show();
				return;
			}

			if (this.isCategoryNameExists(categoryName)) {
				$errorSpan.text('A group with this name already exists.').show();
				return;
			}

			AgenticWPAdmin.utils.toggleButtonLoading($button, true, 'Adding...');

			const adminData = window.agenticwpAdmin || {};

			if (!adminData.nonces || !adminData.nonces.save_category) {
				AgenticWPAdmin.utils.logError('missing_nonce', { operation: 'category_save', category_name: categoryName });
				AgenticWPAdmin.utils.toggleButtonLoading($button, false);
				$errorSpan.text('Security check failed. Please refresh the page.').show();
				return;
			}

			AgenticWPAdmin.utils.postAction({
				action: 'agenticwp_save_category',
				nonce: adminData.nonces.save_category,
				data: { name: categoryName },
				onSuccess: (response) => {
					if (response.success) {
						const categoryKey = response.data.category_key || this.sanitizeKey(categoryName);
						if ($('.agenticwp-groups-table').length) {
							const newRow = this.generateGroupTableRow(categoryKey, {
								name: categoryName,
								is_custom: true
							}, 0);
							$('.agenticwp-groups-table tbody').append(newRow);
						} else {
							const tableHtml = this.generateGroupsTable([{
								key: categoryKey,
								data: { name: categoryName, is_custom: true },
								count: 0
							}]);
							$('.agenticwp-empty-state').replaceWith(tableHtml);
						}
						this.updateCategoryOptions();
						if (window.AgenticWPToast && typeof window.AgenticWPToast.showSuccess === 'function') {
							window.AgenticWPToast.showSuccess(response.data.message || 'Group added successfully!');
						}
						this.handleCancelGroupInline(e);
					} else {
						AgenticWPAdmin.utils.logError('category_save_failed', {
							category_name: categoryName,
							error_message: response.data.message || 'Unknown error',
							error_code: response.data.code || 'unknown'
						});
						$errorSpan.text(response.data.message || 'Failed to save group. Please try again.').show();
					}
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
				},
				onError: (error) => {
					AgenticWPAdmin.utils.logError('category_save_error', {
						category_name: categoryName,
						error: String(error)
					});
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
					$errorSpan.text('Network error occurred. Please try again.').show();
				}
			});
		},

		handleDeleteCategory: function(e) {
			e.preventDefault();
			e.stopPropagation();

			const $button = $(e.currentTarget);
			const categoryKey = $button.data('category-key');
			const $card = $button.closest('.agenticwp-category-card');
			const adminData = window.agenticwpAdmin || {};

			if (!adminData.nonces || !adminData.nonces.delete_category) {
				AgenticWPAdmin.utils.logError('missing_nonce', { operation: 'category_delete', category_key: categoryKey });
				AgenticWPAdmin.utils.showNotice('Security check failed. Please refresh the page.', 'error');
				return;
			}

			AgenticWPAdmin.utils.toggleButtonLoading($button, true, '');
			$button.find('.dashicons').removeClass('dashicons-trash').addClass('dashicons-update');

			AgenticWPAdmin.utils.postAction({
				action: 'agenticwp_delete_category',
				nonce: adminData.nonces.delete_category,
				data: { category_key: categoryKey },
				onSuccess: (response) => {
					if (response.success) {
						if (window.AgenticWPToast && typeof window.AgenticWPToast.showSuccess === 'function') {
							window.AgenticWPToast.showSuccess(response.data.message || 'Group deleted successfully!');
						}
						const $row = $button.closest('tr');
						const $element = $row.length ? $row : $card;
						$element.fadeOut(200, function() {
							$(this).remove();
							AgenticWPAdmin.actionsManager.updateCategoryOptions();
							if ($('.agenticwp-groups-table tbody tr').length === 0) {
								$('.agenticwp-groups-table').replaceWith(
									'<div class="agenticwp-empty-state"><p>No custom groups yet. Create one when adding a new shortcut!</p></div>'
								);
							}
						});
					} else {
						AgenticWPAdmin.utils.logError('category_delete_failed', {
							category_key: categoryKey,
							error_message: response.data.message || 'Unknown error',
							error_code: response.data.code || 'unknown'
						});
						AgenticWPAdmin.utils.toggleButtonLoading($button, false);
						$button.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-trash');
						AgenticWPAdmin.utils.showNotice(response.data.message || 'Failed to delete group. Please try again.', 'error');
					}
				},
				onError: (error) => {
					AgenticWPAdmin.utils.logError('category_delete_error', {
						category_key: categoryKey,
						error: String(error)
					});
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
					$button.find('.dashicons').removeClass('dashicons-update').addClass('dashicons-trash');
					AgenticWPAdmin.utils.showNotice('Network error occurred. Please try again.', 'error');
				}
			});
		},

		handleClearUnusedCategories: function(e) {
			e.preventDefault();
			const $button = $(e.currentTarget);
			const adminData = window.agenticwpAdmin || {};

			if (!adminData.nonces || !adminData.nonces.clear_unused_categories) {
				AgenticWPAdmin.utils.logError('missing_nonce', { operation: 'clear_unused_categories' });
				AgenticWPAdmin.utils.showNotice('Security check failed. Please refresh the page.', 'error');
				return;
			}

			AgenticWPAdmin.utils.toggleButtonLoading($button, true, 'Clearing...');

			AgenticWPAdmin.utils.postAction({
				action: 'agenticwp_clear_unused_categories',
				nonce: adminData.nonces.clear_unused_categories,
				data: {},
				onSuccess: (response) => {
					if (response.success) {
						const removed = response.data.removed || 0;
						const categories = response.data.categories || [];
						if (window.AgenticWPToast && typeof window.AgenticWPToast.showSuccess === 'function') {
							window.AgenticWPToast.showSuccess(response.data.message || 'Unused groups cleared!');
						}
						if (removed > 0 && categories.length > 0) {
							categories.forEach(function(categoryKey) {
								const $row = $(`.agenticwp-groups-table tbody tr[data-category-key="${categoryKey}"]`);
								const $card = $(`.agenticwp-category-card[data-category-key="${categoryKey}"]`);
								const $element = $row.length ? $row : $card;
								$element.fadeOut(200, function() {
									$(this).remove();
									AgenticWPAdmin.actionsManager.updateCategoryOptions();
									if ($('.agenticwp-groups-table tbody tr').length === 0) {
										$('.agenticwp-groups-table').replaceWith(
											'<div class="agenticwp-empty-state"><p>No custom groups yet. Create one when adding a new shortcut!</p></div>'
										);
									}
								});
							});
						}
					} else {
						AgenticWPAdmin.utils.logError('clear_unused_categories_failed', {
							error_message: response.data.message || 'Unknown error',
							error_code: response.data.code || 'unknown'
						});
						AgenticWPAdmin.utils.showNotice(response.data.message || 'Failed to clear unused groups. Please try again.', 'error');
					}
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
				},
				onError: (error) => {
					AgenticWPAdmin.utils.logError('clear_unused_categories_error', {
						error: String(error)
					});
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
					AgenticWPAdmin.utils.showNotice('Network error occurred. Please try again.', 'error');
				}
			});
		},

		handleCategoryDropdownChange: function(e) {
			const $select = $(e.currentTarget);
			const $newCategoryField = $('.agenticwp-new-category-field');

			if ($select.val() === 'create_new') {
				$newCategoryField.slideDown(200);
				$('#agenticwp-new-category-input').focus();
			} else {
				$newCategoryField.slideUp(200);
			}
		},

		generateActionCardHtml: function(actionKey, actionData, categoryKey) {
			return `
                <div class="agenticwp-action-card"
                     data-action-key="${this.escapeAttr(actionKey)}"
                     data-category="${this.escapeAttr(categoryKey)}">

                    <div class="agenticwp-action-card-header">
                        <div class="agenticwp-action-meta">
                            <span class="agenticwp-action-category">${this.escapeHtml(actionData.category)}</span>
                            ${actionData.is_custom ? '<span class="agenticwp-action-badge">Custom</span>' : '<span class="agenticwp-action-badge">Built-in</span>'}
                        </div>
                        ${actionData.is_custom ? `
                            <button type="button"
                                    class="agenticwp-action-delete"
                                    data-action-key="${this.escapeAttr(actionKey)}">
                                <span class="dashicons dashicons-trash"></span>
                            </button>
                        ` : ''}
                    </div>

                    <div class="agenticwp-action-card-body">
                        <div class="agenticwp-field-group">
                            <label>Shortcut Name</label>
                            <input type="text"
                                   name="agentic_wp_actions[${this.escapeAttr(categoryKey)}][${this.escapeAttr(actionKey)}][name]"
                                   value="${this.escapeAttr(actionData.name || '')}"
                                   class="agenticwp-action-name"
                                   placeholder="Shortcut Name"
                                   ${actionData.is_custom ? '' : 'readonly'} />
                        </div>

                        <div class="agenticwp-field-group">
                            <label>Instructions for AI</label>
                            <textarea name="agentic_wp_actions[${this.escapeAttr(categoryKey)}][${this.escapeAttr(actionKey)}][prompt]"
                                      rows="4"
                                      placeholder="Enter clear instructions for the AI..."
                                      ${actionData.is_custom ? '' : 'readonly'}>${this.escapeHtml(actionData.prompt || '')}</textarea>
                        </div>
                        <input type="hidden"
                               name="agentic_wp_actions[${this.escapeAttr(categoryKey)}][${this.escapeAttr(actionKey)}][category]"
                               value="${this.escapeAttr(actionData.category || '')}" />
                        <input type="hidden"
                               name="agentic_wp_actions[${this.escapeAttr(categoryKey)}][${this.escapeAttr(actionKey)}][is_custom]"
                               value="${actionData.is_custom ? '1' : '0'}" />
                    </div>
                </div>
            `;
		},

		isCategoryNameExists: function(categoryName) {
			let exists = false;
			$('.agenticwp-category-name').each(function() {
				if ($(this).val().toLowerCase() === categoryName.toLowerCase()) {
					exists = true;
					return false;
				}
			});
			return exists;
		},

		updateCategoryOptions: function() {
			const $actionCategorySelect = $('#agenticwp-new-action-category');
			const $createNewOption = $actionCategorySelect.find('option[value="create_new"]');
			$actionCategorySelect.find('option[value!="create_new"]').remove();
			$('.agenticwp-category-name').each(function() {
				const categoryName = $(this).val();
				if (categoryName) {
					$createNewOption.before(`<option value="${AgenticWPAdmin.actionsManager.escapeAttr(categoryName)}">${AgenticWPAdmin.actionsManager.escapeHtml(categoryName)}</option>`);
				}
			});
		},

		updateCategoryFilter: function() {
			const defaultCategoryCounts = {};
			const customCategoryCounts = {};

			$('.agenticwp-tab-default .agenticwp-action-card').each(function() {
				const category = $(this).data('category');
				defaultCategoryCounts[category] = (defaultCategoryCounts[category] || 0) + 1;
			});

			$('.agenticwp-tab-custom .agenticwp-action-card').each(function() {
				const category = $(this).data('category');
				customCategoryCounts[category] = (customCategoryCounts[category] || 0) + 1;
			});

			const $defaultSelect = $('#agenticwp-category-select-default');
			$defaultSelect.find('option[value!=""]').each(function() {
				const categoryKey = $(this).val();
				const categoryName = $(this).text().split(' (')[0];
				const count = defaultCategoryCounts[categoryKey] || 0;
				$(this).text(`${categoryName} (${count})`);
			});

			const $customSelect = $('#agenticwp-category-select-custom');
			$customSelect.find('option[value!=""]').each(function() {
				const categoryKey = $(this).val();
				const categoryName = $(this).text().split(' (')[0];
				const count = customCategoryCounts[categoryKey] || 0;
				$(this).text(`${categoryName} (${count})`);
			});

			const totalDefault = Object.values(defaultCategoryCounts).reduce((a, b) => a + b, 0);
			const totalCustom = Object.values(customCategoryCounts).reduce((a, b) => a + b, 0);

			$('.agenticwp-tab-button[data-tab="default"]').html(
				`Built-in Shortcuts (${totalDefault})`
			);
			$('.agenticwp-tab-button[data-tab="custom"]').html(
				`My Shortcuts (${totalCustom})`
			);
		},

		openModal: function() {
			this.clearModalForm();
			$('.agenticwp-add-action-modal').addClass('is-visible');
			$('#agenticwp-new-action-name').focus();
		},

		closeModal: function() {
			$('.agenticwp-add-action-modal').removeClass('is-visible');
			this.clearModalForm();
		},

		clearModalForm: function() {
			$('#agenticwp-new-action-name').val('');
			$('#agenticwp-new-action-prompt').val('');
			$('#agenticwp-new-action-category').val($('#agenticwp-new-action-category option:first').val());
			$('.agenticwp-new-category-field').hide();
			$('#agenticwp-new-category-input').val('');
			$('.field-error').remove();
			$('.regular-text, .large-text').removeClass('invalid');
		},

		handleCloseModal: function(e) {
			e.preventDefault();
			if ($('.agenticwp-manage-groups-modal').is(':visible')) {
				this.closeManageGroupsModal();
			} else {
				this.closeModal();
			}
		},

		handleBackdropClick: function(e) {
			if (e.target === e.currentTarget) {
				if ($('.agenticwp-manage-groups-modal').is(':visible')) {
					this.closeManageGroupsModal();
				} else {
					this.closeModal();
				}
			}
		},

		handleKeydown: function(e) {
			if (e.key === 'Escape') {
				if ($('.agenticwp-manage-groups-modal').is(':visible')) {
					this.closeManageGroupsModal();
				} else if ($('.agenticwp-add-action-modal').is(':visible')) {
					this.closeModal();
				}
			}
		},

		handleSaveAction: function(e) {
			e.preventDefault();
			const $button = $(e.currentTarget);
			const actionName = $('#agenticwp-new-action-name').val().trim();
			const actionPrompt = $('#agenticwp-new-action-prompt').val().trim();
			let actionCategory = $('#agenticwp-new-action-category').val();

			if (actionCategory === 'create_new') {
				actionCategory = $('#agenticwp-new-category-input').val().trim();
			}

			$('.field-error').remove();
			$('.regular-text, .large-text').removeClass('invalid');

			let hasErrors = false;

			if (!actionName) {
				this.showFieldError('#agenticwp-new-action-name', 'Shortcut name is required.');
				hasErrors = true;
			}

			if (!actionPrompt) {
				this.showFieldError('#agenticwp-new-action-prompt', 'Instructions for AI are required.');
				hasErrors = true;
			} else if (actionPrompt.length > 500) {
				this.showFieldError('#agenticwp-new-action-prompt', 'Instructions must be 500 characters or less.');
				hasErrors = true;
			}

			if ($('#agenticwp-new-action-category').val() === 'create_new') {
				if (!actionCategory) {
					this.showFieldError('#agenticwp-new-category-input', 'New group name is required.');
					hasErrors = true;
				} else if (this.isCategoryNameExists(actionCategory)) {
					this.showFieldError('#agenticwp-new-category-input', 'A group with this name already exists.');
					hasErrors = true;
				}
			}

			if (hasErrors) {
				return;
			}

			AgenticWPAdmin.utils.toggleButtonLoading($button, true, 'Saving...');

			if ($('#agenticwp-new-action-category').val() === 'create_new') {
				this.saveNewCategoryForAction(actionCategory, actionName, actionPrompt, $button);
				return;
			}

			this.saveActionViaAjax(actionName, actionPrompt, actionCategory, $button);
		},

		saveNewCategoryForAction: function(categoryName, actionName, actionPrompt, $button) {
			const adminData = window.agenticwpAdmin || {};

			if (!adminData.nonces || !adminData.nonces.save_category) {
				AgenticWPAdmin.utils.logError('missing_nonce', {
					operation: 'category_save',
					category_name: categoryName,
					action_name: actionName
				});
				AgenticWPAdmin.utils.toggleButtonLoading($button, false);
				AgenticWPAdmin.utils.showNotice('Security check failed. Please refresh the page.', 'error');
				return;
			}

			AgenticWPAdmin.utils.postAction({
				action: 'agenticwp_save_category',
				nonce: adminData.nonces.save_category,
				data: { name: categoryName },
				onSuccess: (response) => {
					if (response.success) {
						this.updateCategoryOptions();
						this.saveActionViaAjax(actionName, actionPrompt, categoryName, $button);
					} else {
						AgenticWPAdmin.utils.logError('category_save_failed', {
							category_name: categoryName,
							action_name: actionName,
							error_message: response.data.message || 'Unknown error',
							error_code: response.data.code || 'unknown'
						});
						AgenticWPAdmin.utils.toggleButtonLoading($button, false);
						AgenticWPAdmin.utils.showNotice(response.data.message || 'Failed to save group. Please try again.', 'error');
					}
				},
				onError: (error) => {
					AgenticWPAdmin.utils.logError('category_save_error', {
						category_name: categoryName,
						action_name: actionName,
						error: String(error)
					});
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
					AgenticWPAdmin.utils.showNotice('Network error occurred. Please try again.', 'error');
				}
			});
		},

		saveActionViaAjax: function(actionName, actionPrompt, actionCategory, $button) {
			const adminData = window.agenticwpAdmin || {};

			if (!adminData.nonces || !adminData.nonces.save_action) {
				AgenticWPAdmin.utils.logError('missing_nonce', {
					operation: 'action_save',
					action_name: actionName,
					category: actionCategory
				});
				AgenticWPAdmin.utils.toggleButtonLoading($button, false);
				AgenticWPAdmin.utils.showNotice('Security check failed. Please refresh the page.', 'error');
				return;
			}

			AgenticWPAdmin.utils.postAction({
				action: 'agenticwp_save_action',
				nonce: adminData.nonces.save_action,
				data: {
					name: actionName,
					prompt: actionPrompt,
					category: actionCategory
				},
				onSuccess: (response) => {
					if (response.success) {
						const actionKey = response.data.action_key || 'custom_action_' + Date.now();
						const categoryKey = this.sanitizeKey(actionCategory);
						const actionHtml = this.generateActionCardHtml(actionKey, {
							name: actionName,
							prompt: actionPrompt,
							category: actionCategory,
							is_custom: true
						}, categoryKey);
						$('.agenticwp-tab-custom .agenticwp-actions-grid').append(actionHtml);
						$('.agenticwp-tab-custom .agenticwp-empty-state').hide();
						this.updateCategoryFilter();
						if (window.AgenticWPToast && typeof window.AgenticWPToast.showSuccess === 'function') {
							window.AgenticWPToast.showSuccess(response.data.message || 'Shortcut saved successfully!');
						}
						this.closeModal();
						$(`.agenticwp-action-card[data-action-key="${actionKey}"] .agenticwp-action-name`).focus();
					} else {
						AgenticWPAdmin.utils.logError('action_save_failed', {
							action_name: actionName,
							category: actionCategory,
							error_message: response.data.message || 'Unknown error',
							error_code: response.data.code || 'unknown'
						});
						AgenticWPAdmin.utils.showNotice(response.data.message || 'Failed to save shortcut. Please try again.', 'error');
					}
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
				},
				onError: (error) => {
					AgenticWPAdmin.utils.logError('action_save_error', {
						action_name: actionName,
						category: actionCategory,
						error: String(error)
					});
					AgenticWPAdmin.utils.toggleButtonLoading($button, false);
					AgenticWPAdmin.utils.showNotice('Network error occurred. Please try again.', 'error');
				}
			});
		},

		showFieldError: function(fieldSelector, message) {
			const $field = $(fieldSelector);
			$field.addClass('invalid');
			$field.after(`<span class="field-error">${this.escapeHtml(message)}</span>`);
		},

		sanitizeKey: function(str) {
			return str.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '');
		},

		escapeHtml: function(str) {
			const div = document.createElement('div');
			div.textContent = str;
			return div.innerHTML;
		},

		escapeAttr: function(str) {
			return String(str).replace(/[&<>"']/g, function(match) {
				const escape = {
					'&': '&amp;',
					'<': '&lt;',
					'>': '&gt;',
					'"': '&quot;',
					'\'': '&#39;'
				};
				return escape[match];
			});
		},

		handleNewActionPromptChange: function(e) {
			const $textarea = $(e.target);
			const $counter = $('#agenticwp-new-action-char-count');
			this.updateCharacterCount($textarea, $counter);
		},

		handleActionPromptChange: function(e) {
			const $textarea = $(e.target);
			const actionKey = $textarea.data('action-key');
			const $counter = $(`.agenticwp-action-char-count[data-action-key="${actionKey}"]`);
			this.updateCharacterCount($textarea, $counter);
		},

		updateCharacterCount: function($textarea, $counter) {
			if (!$textarea.length || !$counter.length) {
				return;
			}

			const currentLength = $textarea.val().length;
			const maxLength = parseInt($textarea.attr('maxlength'), 10) || 500;

			$counter.text(currentLength);

			const percentage = (currentLength / maxLength) * 100;

			$counter.removeClass('agenticwp-char-warning agenticwp-char-danger');

			if (percentage >= 90) {
				$counter.addClass('agenticwp-char-danger');
			} else if (percentage >= 75) {
				$counter.addClass('agenticwp-char-warning');
			}
		},

		openManageGroupsModal: function() {
			$('.agenticwp-manage-groups-modal').addClass('is-visible');
		},

		closeManageGroupsModal: function() {
			$('.agenticwp-manage-groups-modal').removeClass('is-visible');
		},

		generateGroupTableRow: function(categoryKey, categoryData, actionCount) {
			return `
                <tr data-category-key="${this.escapeAttr(categoryKey)}">
                    <td class="agenticwp-group-name-cell">
                        <input type="text"
                                name="agentic_wp_action_categories[${this.escapeAttr(categoryKey)}][name]"
                                value="${this.escapeAttr(categoryData.name || '')}"
                                class="agenticwp-group-name-input"
                                placeholder="Group Name" />
                        <input type="hidden"
                                name="agentic_wp_action_categories[${this.escapeAttr(categoryKey)}][is_custom]"
                                value="1" />
                    </td>
                    <td class="agenticwp-group-count-cell">
                        <span class="agenticwp-group-count">${actionCount}</span>
                    </td>
                    <td class="agenticwp-group-actions-cell">
                        <button type="button"
                                class="button button-link-delete agenticwp-category-delete"
                                data-category-key="${this.escapeAttr(categoryKey)}">
                            <span class="dashicons dashicons-trash"></span>
                            Delete
                        </button>
                    </td>
                </tr>
            `;
		},

		generateGroupsTable: function(groups) {
			let rowsHtml = '';
			groups.forEach(function(group) {
				rowsHtml += AgenticWPAdmin.actionsManager.generateGroupTableRow(group.key, group.data, group.count);
			});

			return `
                <table class="agenticwp-groups-table">
                    <thead>
                        <tr>
                            <th>Group Name</th>
                            <th>Shortcuts</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${rowsHtml}
                    </tbody>
                </table>
            `;
		}
	};
})(jQuery);