<?php
/**
 * Actions settings class for AgenticWP plugin.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

use Agentic_WP\Error_Handler;

/**
 * Handles action management settings interface.
 */
class Settings_Actions extends Settings_Base {

	/**
	 * Action Manager instance.
	 *
	 * @var Action_Manager
	 */
	private $action_manager;

	/**
	 * Registers actions settings hooks.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$this->action_manager = new Action_Manager();

		add_action( 'wp_ajax_agenticwp_save_action', array( $this, 'handle_ajax_save_action' ) );
		add_action( 'wp_ajax_agenticwp_delete_action', array( $this, 'handle_ajax_delete_action' ) );
		add_action( 'wp_ajax_agenticwp_save_category', array( $this, 'handle_ajax_save_category' ) );
		add_action( 'wp_ajax_agenticwp_delete_category', array( $this, 'handle_ajax_delete_category' ) );
		add_action( 'wp_ajax_agenticwp_clear_unused_categories', array( $this, 'handle_ajax_clear_unused_categories' ) );
	}

	/**
	 * Register action-related settings.
	 */
	public function register_settings(): void {
		register_setting(
			'agentic_wp',
			Action_Manager::ACTIONS_OPTION,
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_actions_data' ),
				'default'           => array(),
			)
		);

		register_setting(
			'agentic_wp',
			Action_Manager::CATEGORIES_OPTION,
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_categories_data' ),
				'default'           => array(),
			)
		);
	}

	/**
	 * Add actions-related settings fields.
	 *
	 * @param string $section_id The actions settings section ID.
	 */
	public function add_settings_fields( string $section_id ): void {
		add_settings_field(
			'categories_management',
			__( 'Organize Your Tasks', 'agenticwp' ),
			array( $this, 'categories_management_field' ),
			'agentic_wp',
			$section_id
		);

		add_settings_field(
			'actions_management',
			__( 'Your AI Shortcuts', 'agenticwp' ),
			array( $this, 'actions_management_field' ),
			'agentic_wp',
			$section_id
		);
	}

	/**
	 * Renders categories management field.
	 *
	 * @since 1.0.0
	 */
	public function categories_management_field(): void {
		$categories    = $this->action_manager->get_categories();
		$actions       = $this->action_manager->get_actions();
		$action_counts = array();

		foreach ( $actions as $category_key => $category_actions ) {
			$action_counts[ $category_key ] = count( $category_actions );
		}

		$custom_categories = array_filter(
			$categories,
			function ( $category_data ) {
				return $category_data['is_custom'] ?? true;
			}
		);
		?>
		<!-- Manage Groups Modal -->
		<div class="agenticwp-modal-backdrop agenticwp-manage-groups-modal" style="display: none;">
			<div class="agenticwp-modal-container agenticwp-modal-wide">
				<div class="agenticwp-modal-header">
					<h3><?php esc_html_e( 'Manage Groups', 'agenticwp' ); ?></h3>
					<button type="button" class="agenticwp-modal-close" aria-label="<?php esc_attr_e( 'Close modal', 'agenticwp' ); ?>">&times;</button>
				</div>
				<div class="agenticwp-modal-body">
					<div class="agenticwp-groups-actions">
						<button type="button" class="button button-secondary agenticwp-clear-unused-categories">
							<?php esc_html_e( 'Clear Unused Groups', 'agenticwp' ); ?>
						</button>
						<button type="button" class="button button-primary agenticwp-add-group-inline">
							<span class="dashicons dashicons-plus-alt2"></span>
							<?php esc_html_e( 'Add New Group', 'agenticwp' ); ?>
						</button>
					</div>

					<div class="agenticwp-add-group-form" style="display: none;">
						<div class="agenticwp-add-group-input-wrapper">
							<input type="text"
									id="agenticwp-inline-group-name"
									class="agenticwp-group-name-input"
									placeholder="<?php esc_attr_e( 'Enter group name...', 'agenticwp' ); ?>" />
							<div class="agenticwp-add-group-buttons">
								<button type="button" class="button button-primary agenticwp-save-group-inline">
									<?php esc_html_e( 'Add', 'agenticwp' ); ?>
								</button>
								<button type="button" class="button button-secondary agenticwp-cancel-group-inline">
									<?php esc_html_e( 'Cancel', 'agenticwp' ); ?>
								</button>
							</div>
						</div>
						<span class="agenticwp-group-error" style="display: none;"></span>
					</div>

					<?php if ( ! empty( $custom_categories ) ) : ?>
						<table class="agenticwp-groups-table">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Group Name', 'agenticwp' ); ?></th>
									<th><?php esc_html_e( 'Shortcuts', 'agenticwp' ); ?></th>
									<th><?php esc_html_e( 'Actions', 'agenticwp' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $custom_categories as $category_key => $category_data ) : ?>
									<tr data-category-key="<?php echo esc_attr( $category_key ); ?>">
										<td class="agenticwp-group-name-cell">
											<input type="text"
													name="<?php echo esc_attr( Action_Manager::CATEGORIES_OPTION ); ?>[<?php echo esc_attr( $category_key ); ?>][name]"
													value="<?php echo esc_attr( $category_data['name'] ?? '' ); ?>"
													class="agenticwp-group-name-input"
													placeholder="<?php esc_attr_e( 'Group Name', 'agenticwp' ); ?>" />
											<input type="hidden"
													name="<?php echo esc_attr( Action_Manager::CATEGORIES_OPTION ); ?>[<?php echo esc_attr( $category_key ); ?>][is_custom]"
													value="1" />
										</td>
										<td class="agenticwp-group-count-cell">
											<span class="agenticwp-group-count">
												<?php echo esc_html( $action_counts[ $category_key ] ?? 0 ); ?>
											</span>
										</td>
										<td class="agenticwp-group-actions-cell">
											<button type="button"
													class="button button-link-delete agenticwp-category-delete"
													data-category-key="<?php echo esc_attr( $category_key ); ?>">
												<span class="dashicons dashicons-trash"></span>
												<?php esc_html_e( 'Delete', 'agenticwp' ); ?>
											</button>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					<?php else : ?>
						<div class="agenticwp-empty-state">
							<p><?php esc_html_e( 'No custom groups yet. Create one when adding a new shortcut!', 'agenticwp' ); ?></p>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Renders actions management field.
	 *
	 * @since 1.0.0
	 */
	public function actions_management_field(): void {
		$actions_by_category = $this->action_manager->get_actions_by_category();
		$categories          = $this->action_manager->get_categories();

		$default_actions      = array();
		$custom_actions       = array();
		$default_action_count = 0;
		$custom_action_count  = 0;

		foreach ( $actions_by_category as $category => $actions ) {
			foreach ( $actions as $action_key => $action_data ) {
				if ( $action_data['is_custom'] ?? true ) {
					if ( ! isset( $custom_actions[ $category ] ) ) {
						$custom_actions[ $category ] = array();
					}
					$custom_actions[ $category ][ $action_key ] = $action_data;
					++$custom_action_count;
				} else {
					if ( ! isset( $default_actions[ $category ] ) ) {
						$default_actions[ $category ] = array();
					}
					$default_actions[ $category ][ $action_key ] = $action_data;
					++$default_action_count;
				}
			}
		}
		?>
		<div id="agenticwp-actions-manager" class="agenticwp-actions-manager">
			<!-- Tab Navigation -->
			<div class="agenticwp-actions-tabs">
				<button type="button"
						class="agenticwp-tab-button active"
						data-tab="default">
					<?php esc_html_e( 'Built-in Shortcuts', 'agenticwp' ); ?> (<?php echo esc_html( $default_action_count ); ?>)
				</button>
				<button type="button"
						class="agenticwp-tab-button"
						data-tab="custom">
					<?php esc_html_e( 'My Shortcuts', 'agenticwp' ); ?> (<?php echo esc_html( $custom_action_count ); ?>)
				</button>
			</div>

			<!-- Default Actions Tab -->
			<div class="agenticwp-tab-content agenticwp-tab-default active">
				<div class="agenticwp-actions-controls">
					<div class="agenticwp-category-filter">
						<label for="agenticwp-category-select-default"><?php esc_html_e( 'Show shortcuts for:', 'agenticwp' ); ?></label>
						<select id="agenticwp-category-select-default" class="agenticwp-category-select" data-tab="default">
							<option value=""><?php esc_html_e( 'All Groups', 'agenticwp' ); ?></option>
							<?php foreach ( $default_actions as $category => $actions ) : ?>
								<option value="<?php echo esc_attr( sanitize_key( $category ) ); ?>">
									<?php echo esc_html( $category ); ?> (<?php echo count( $actions ); ?>)
								</option>
							<?php endforeach; ?>
						</select>
					</div>
				</div>

				<div class="agenticwp-actions-grid">
					<?php foreach ( $default_actions as $category => $actions ) : ?>
						<?php foreach ( $actions as $action_key => $action_data ) : ?>
							<?php $this->render_action_card( $action_key, $action_data, $category ); ?>
						<?php endforeach; ?>
					<?php endforeach; ?>
				</div>
			</div>

			<!-- Custom Actions Tab -->
			<div class="agenticwp-tab-content agenticwp-tab-custom">
				<div class="agenticwp-actions-controls">
					<div class="agenticwp-category-filter">
						<label for="agenticwp-category-select-custom"><?php esc_html_e( 'Show shortcuts for:', 'agenticwp' ); ?></label>
						<select id="agenticwp-category-select-custom" class="agenticwp-category-select" data-tab="custom">
							<option value=""><?php esc_html_e( 'All Groups', 'agenticwp' ); ?></option>
							<?php foreach ( $custom_actions as $category => $actions ) : ?>
								<option value="<?php echo esc_attr( sanitize_key( $category ) ); ?>">
									<?php echo esc_html( $category ); ?> (<?php echo count( $actions ); ?>)
								</option>
							<?php endforeach; ?>
						</select>
					</div>
					<div class="agenticwp-actions-buttons">
						<button type="button"
								class="button button-secondary agenticwp-manage-groups">
							<span class="dashicons dashicons-category"></span>
							<?php esc_html_e( 'Manage Groups', 'agenticwp' ); ?>
						</button>
						<button type="button"
								class="button button-primary agenticwp-add-action">
							<?php esc_html_e( 'Add New Shortcut', 'agenticwp' ); ?>
						</button>
					</div>
				</div>

				<div class="agenticwp-actions-grid">
					<?php if ( ! empty( $custom_actions ) ) : ?>
						<?php foreach ( $custom_actions as $category => $actions ) : ?>
							<?php foreach ( $actions as $action_key => $action_data ) : ?>
								<?php $this->render_action_card( $action_key, $action_data, $category ); ?>
							<?php endforeach; ?>
						<?php endforeach; ?>
					<?php else : ?>
						<div class="agenticwp-empty-state">
							<p><?php esc_html_e( 'No custom shortcuts yet. Create your first shortcut to speed up your workflow!', 'agenticwp' ); ?></p>
						</div>
					<?php endif; ?>
				</div>
			</div>

			<!-- Add Action Modal -->
			<div class="agenticwp-modal-backdrop agenticwp-add-action-modal" style="display: none;">
				<div class="agenticwp-modal-container">
					<div class="agenticwp-modal-header">
						<h3><?php esc_html_e( 'Add New Shortcut', 'agenticwp' ); ?></h3>
						<button type="button" class="agenticwp-modal-close" aria-label="<?php esc_attr_e( 'Close modal', 'agenticwp' ); ?>">&times;</button>
					</div>
					<div class="agenticwp-modal-body">
						<div class="agenticwp-field-group">
							<label for="agenticwp-new-action-name"><?php esc_html_e( 'Shortcut Name', 'agenticwp' ); ?> <span class="required">*</span></label>
							<p class="description"><?php echo esc_html__( 'Give your shortcut a clear, descriptive name (e.g., \'Product Review\', \'SEO Audit\', \'Image Alt Text\')', 'agenticwp' ); ?></p>
							<input type="text"
									id="agenticwp-new-action-name"
									class="regular-text"
									placeholder="<?php esc_attr_e( 'Enter shortcut name...', 'agenticwp' ); ?>" />
						</div>

						<div class="agenticwp-field-group">
							<label for="agenticwp-new-action-category"><?php esc_html_e( 'Group', 'agenticwp' ); ?></label>
							<p class="description"><?php echo esc_html__( 'Choose which group this shortcut belongs to', 'agenticwp' ); ?></p>
							<select id="agenticwp-new-action-category" class="regular-text">
								<?php foreach ( $categories as $category_key => $category_data ) : ?>
									<option value="<?php echo esc_attr( $category_data['name'] ); ?>"><?php echo esc_html( $category_data['name'] ); ?></option>
								<?php endforeach; ?>
								<option value="create_new"><?php esc_html_e( 'Create New Group...', 'agenticwp' ); ?></option>
							</select>
						</div>

						<div class="agenticwp-field-group agenticwp-new-category-field" style="display: none;">
							<label for="agenticwp-new-category-input"><?php esc_html_e( 'New Group Name', 'agenticwp' ); ?></label>
							<input type="text"
									id="agenticwp-new-category-input"
									class="regular-text"
									placeholder="<?php esc_attr_e( 'Enter new group name...', 'agenticwp' ); ?>" />
						</div>

						<div class="agenticwp-field-group">
							<label for="agenticwp-new-action-prompt"><?php esc_html_e( 'Instructions for AI', 'agenticwp' ); ?> <span class="required">*</span></label>
							<p class="description"><?php echo esc_html__( 'Write clear instructions telling the AI what task to complete and how to approach it (maximum 500 characters)', 'agenticwp' ); ?></p>
							<textarea id="agenticwp-new-action-prompt"
										rows="6"
										class="large-text"
										maxlength="500"
										placeholder="<?php esc_attr_e( 'Enter clear instructions for the AI...', 'agenticwp' ); ?>"></textarea>
							<div class="agenticwp-character-counter">
								<span id="agenticwp-new-action-char-count">0</span>/500
							</div>
						</div>
					</div>
					<div class="agenticwp-modal-footer">
						<button type="button" class="button button-secondary agenticwp-cancel-action">
							<?php esc_html_e( 'Cancel', 'agenticwp' ); ?>
						</button>
						<button type="button" class="button button-primary agenticwp-save-action">
							<span class="dashicons dashicons-plus-alt2"></span>
							<?php esc_html_e( 'Add Shortcut', 'agenticwp' ); ?>
						</button>
					</div>
				</div>
			</div>

			<!-- Manage Groups Modal -->
			<?php $this->categories_management_field(); ?>
		</div>
		<?php
	}

	/**
	 * Renders action card HTML.
	 *
	 * @since 1.0.0
	 * @param string $action_key  Action identifier.
	 * @param array  $action_data Action configuration.
	 * @param string $category    Category name.
	 */
	private function render_action_card( string $action_key, array $action_data, string $category ): void {
		$is_custom    = $action_data['is_custom'] ?? true;
		$category_key = sanitize_key( strtolower( str_replace( ' ', '_', $category ) ) );
		?>
		<div class="agenticwp-action-card"
			data-action-key="<?php echo esc_attr( $action_key ); ?>"
			data-category="<?php echo esc_attr( sanitize_key( $category ) ); ?>">

			<div class="agenticwp-action-card-header">
				<div class="agenticwp-action-meta">
					<span class="agenticwp-action-category"><?php echo esc_html( $category ); ?></span>
					<?php if ( $is_custom ) : ?>
						<span class="agenticwp-action-badge"><?php esc_html_e( 'Custom', 'agenticwp' ); ?></span>
					<?php else : ?>
						<span class="agenticwp-action-badge"><?php esc_html_e( 'Built-in', 'agenticwp' ); ?></span>
					<?php endif; ?>
				</div>
				<?php if ( $is_custom ) : ?>
					<button type="button"
							class="agenticwp-action-delete"
							aria-label="<?php esc_attr_e( 'Delete action', 'agenticwp' ); ?>"
							data-action-key="<?php echo esc_attr( $action_key ); ?>">
						<span class="dashicons dashicons-trash"></span>
					</button>
				<?php endif; ?>
			</div>

			<div class="agenticwp-action-card-body">
				<div class="agenticwp-field-group">
					<label><?php esc_html_e( 'Shortcut Name', 'agenticwp' ); ?></label>
					<input type="text"
							name="<?php echo esc_attr( Action_Manager::ACTIONS_OPTION ); ?>[<?php echo esc_attr( $category_key ); ?>][<?php echo esc_attr( $action_key ); ?>][name]"
							value="<?php echo esc_attr( $action_data['name'] ?? '' ); ?>"
							class="agenticwp-action-name"
							placeholder="<?php esc_attr_e( 'Shortcut Name', 'agenticwp' ); ?>"
							<?php echo $is_custom ? '' : 'readonly'; ?> />
				</div>


				<div class="agenticwp-field-group agenticwp-mb-0">
					<label><?php esc_html_e( 'Instructions for AI', 'agenticwp' ); ?></label>
					<textarea name="<?php echo esc_attr( Action_Manager::ACTIONS_OPTION ); ?>[<?php echo esc_attr( $category_key ); ?>][<?php echo esc_attr( $action_key ); ?>][prompt]"
								class="agenticwp-action-prompt"
								rows="4"
								maxlength="500"
								data-action-key="<?php echo esc_attr( $action_key ); ?>"
								placeholder="<?php esc_attr_e( 'Enter clear instructions for the AI...', 'agenticwp' ); ?>"
								<?php echo $is_custom ? '' : 'readonly'; ?>><?php echo esc_textarea( $action_data['prompt'] ?? '' ); ?></textarea>
					<div class="agenticwp-character-counter">
						<span class="agenticwp-action-char-count" data-action-key="<?php echo esc_attr( $action_key ); ?>"><?php echo esc_html( strlen( $action_data['prompt'] ?? '' ) ); ?></span>/500
					</div>
				</div>

				<input type="hidden"
						name="<?php echo esc_attr( Action_Manager::ACTIONS_OPTION ); ?>[<?php echo esc_attr( $category_key ); ?>][<?php echo esc_attr( $action_key ); ?>][category]"
						value="<?php echo esc_attr( $category ); ?>" />
				<input type="hidden"
						name="<?php echo esc_attr( Action_Manager::ACTIONS_OPTION ); ?>[<?php echo esc_attr( $category_key ); ?>][<?php echo esc_attr( $action_key ); ?>][is_custom]"
						value="<?php echo $is_custom ? '1' : '0'; ?>" />
			</div>
		</div>
		<?php
	}

	/**
	 * Sanitize actions data.
	 *
	 * @param array $input Raw actions data.
	 * @return array Sanitized actions data.
	 */
	public function sanitize_actions_data( $input ): array {
		if ( ! is_array( $input ) ) {
			return $this->action_manager->get_actions();
		}

		$sanitized = array();
		foreach ( $input as $category_key => $category_actions ) {
			if ( ! is_array( $category_actions ) ) {
				continue;
			}

			$sanitized[ sanitize_key( $category_key ) ] = array();
			foreach ( $category_actions as $action_key => $action_data ) {
				if ( ! is_array( $action_data ) || empty( $action_data['name'] ) ) {
					continue;
				}

				$prompt = wp_kses_post( $action_data['prompt'] ?? '' );
				if ( strlen( $prompt ) > 500 ) {
					$prompt = substr( $prompt, 0, 500 );
				}

				$sanitized[ sanitize_key( $category_key ) ][ sanitize_key( $action_key ) ] = array(
					'name'      => sanitize_text_field( $action_data['name'] ),
					'prompt'    => $prompt,
					'category'  => sanitize_text_field( $action_data['category'] ?? 'Custom' ),
					'is_custom' => (bool) ( $action_data['is_custom'] ?? true ),
				);
			}
		}

		return $sanitized;
	}

	/**
	 * Sanitize categories data.
	 *
	 * @param array $input Raw categories data.
	 * @return array Sanitized categories data.
	 */
	public function sanitize_categories_data( $input ): array {
		if ( ! is_array( $input ) ) {
			return $this->action_manager->get_categories();
		}

		$sanitized = array();
		foreach ( $input as $category_key => $category_data ) {
			if ( ! is_array( $category_data ) || empty( $category_data['name'] ) ) {
				continue;
			}

			$sanitized[ sanitize_key( $category_key ) ] = array(
				'name'      => sanitize_text_field( $category_data['name'] ),
				'is_custom' => (bool) ( $category_data['is_custom'] ?? true ),
			);
		}

		return $sanitized;
	}

	/**
	 * Handle AJAX save action request.
	 */
	public function handle_ajax_save_action(): void {
		try {
			$this->verify_ajax_request( 'agenticwp_save_action' );

			// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified via verify_ajax_request() above.
			$name     = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );
			$prompt   = wp_kses_post( wp_unslash( $_POST['prompt'] ?? '' ) );
			$category = sanitize_text_field( wp_unslash( $_POST['category'] ?? 'Custom' ) );
			// phpcs:enable WordPress.Security.NonceVerification.Missing

			if ( empty( $name ) || empty( $prompt ) ) {
				Error_Handler::log_error(
					'ajax_validation',
					'Missing required fields for save action',
					array(
						'has_name'   => ! empty( $name ),
						'has_prompt' => ! empty( $prompt ),
					)
				);
				wp_send_json_error(
					array( 'message' => __( 'Action name and prompt are required.', 'agenticwp' ) ),
					400
				);
			}

			$name_length = function_exists( 'mb_strlen' ) ? mb_strlen( $name ) : strlen( $name );
			if ( $name_length > 100 ) {
				Error_Handler::log_error(
					'ajax_validation',
					'Action name exceeds maximum length',
					array(
						'name_length' => $name_length,
					)
				);
				wp_send_json_error(
					array( 'message' => __( 'Action name cannot exceed 100 characters.', 'agenticwp' ) ),
					400
				);
			}

			if ( strlen( $prompt ) > 500 ) {
				$prompt = substr( $prompt, 0, 500 );
			}

			$action_key = sanitize_key( strtolower( str_replace( ' ', '_', $name ) ) );

			$action_data = array(
				'name'      => $name,
				'prompt'    => $prompt,
				'category'  => $category,
				'is_custom' => true,
			);

			$result = $this->action_manager->save_action( $action_key, $action_data );

			if ( $result ) {
				wp_send_json_success(
					array(
						'message'    => __( 'Shortcut saved successfully.', 'agenticwp' ),
						'action_key' => $action_key,
					)
				);
			} else {
				Error_Handler::log_error(
					'database',
					'Failed to save action',
					array(
						'action_key' => $action_key,
						'category'   => $category,
					)
				);
				wp_send_json_error(
					array( 'message' => __( 'Failed to save shortcut.', 'agenticwp' ) ),
					500
				);
			}
		} catch ( \Throwable $e ) {
			Error_Handler::log_error(
				'ajax_exception',
				$e->getMessage(),
				array(
					'action' => 'save_action',
					'file'   => $e->getFile(),
					'line'   => $e->getLine(),
				)
			);
			wp_send_json_error(
				array( 'message' => __( 'An error occurred while saving the shortcut.', 'agenticwp' ) ),
				500
			);
		}
	}

	/**
	 * Handle AJAX delete action request.
	 */
	public function handle_ajax_delete_action(): void {
		try {
			$this->verify_ajax_request( 'agenticwp_delete_action' );

			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified via verify_ajax_request() above.
			$action_key = sanitize_key( wp_unslash( $_POST['action_key'] ?? '' ) );

			if ( empty( $action_key ) ) {
				Error_Handler::log_error(
					'ajax_validation',
					'Missing action key for delete action',
					array( 'has_action_key' => ! empty( $action_key ) )
				);
				wp_send_json_error(
					array( 'message' => __( 'Action key is required.', 'agenticwp' ) ),
					400
				);
			}

			$result = $this->action_manager->delete_action( $action_key );

			if ( $result ) {
				wp_send_json_success( array( 'message' => __( 'Shortcut deleted successfully.', 'agenticwp' ) ) );
			} else {
				Error_Handler::log_error(
					'database',
					'Failed to delete action',
					array( 'action_key' => $action_key )
				);
				wp_send_json_error(
					array( 'message' => __( 'Failed to delete shortcut.', 'agenticwp' ) ),
					500
				);
			}
		} catch ( \Throwable $e ) {
			Error_Handler::log_error(
				'ajax_exception',
				$e->getMessage(),
				array(
					'action' => 'delete_action',
					'file'   => $e->getFile(),
					'line'   => $e->getLine(),
				)
			);
			wp_send_json_error(
				array( 'message' => __( 'An error occurred while deleting the shortcut.', 'agenticwp' ) ),
				500
			);
		}
	}

	/**
	 * Handle AJAX save category request.
	 */
	public function handle_ajax_save_category(): void {
		try {
			$this->verify_ajax_request( 'agenticwp_save_category' );

			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified via verify_ajax_request() above.
			$name = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );

			if ( empty( $name ) ) {
				Error_Handler::log_error(
					'ajax_validation',
					'Missing category name for save category',
					array( 'has_name' => ! empty( $name ) )
				);
				wp_send_json_error(
					array( 'message' => __( 'Category name is required.', 'agenticwp' ) ),
					400
				);
			}

			$name_length = function_exists( 'mb_strlen' ) ? mb_strlen( $name ) : strlen( $name );
			if ( $name_length > 50 ) {
				Error_Handler::log_error(
					'ajax_validation',
					'Category name exceeds maximum length',
					array( 'name_length' => $name_length )
				);
				wp_send_json_error(
					array( 'message' => __( 'Category name cannot exceed 50 characters.', 'agenticwp' ) ),
					400
				);
			}

			$category_key = sanitize_key( strtolower( str_replace( ' ', '_', $name ) ) );

			$category_data = array(
				'name'      => $name,
				'is_custom' => true,
			);

			$result = $this->action_manager->save_category( $category_key, $category_data );

			if ( $result ) {
				wp_send_json_success(
					array(
						'message'      => __( 'Group saved successfully.', 'agenticwp' ),
						'category_key' => $category_key,
					)
				);
			} else {
				Error_Handler::log_error(
					'database',
					'Failed to save category',
					array( 'category_key' => $category_key )
				);
				wp_send_json_error(
					array( 'message' => __( 'Failed to save group.', 'agenticwp' ) ),
					500
				);
			}
		} catch ( \Throwable $e ) {
			Error_Handler::log_error(
				'ajax_exception',
				$e->getMessage(),
				array(
					'action' => 'save_category',
					'file'   => $e->getFile(),
					'line'   => $e->getLine(),
				)
			);
			wp_send_json_error(
				array( 'message' => __( 'An error occurred while saving the group.', 'agenticwp' ) ),
				500
			);
		}
	}

	/**
	 * Handle AJAX delete category request.
	 */
	public function handle_ajax_delete_category(): void {
		try {
			$this->verify_ajax_request( 'agenticwp_delete_category' );

			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified via verify_ajax_request() above.
			$category_key = sanitize_key( wp_unslash( $_POST['category_key'] ?? '' ) );

			if ( empty( $category_key ) ) {
				Error_Handler::log_error(
					'ajax_validation',
					'Missing category key for delete category',
					array( 'has_category_key' => ! empty( $category_key ) )
				);
				wp_send_json_error(
					array( 'message' => __( 'Category key is required.', 'agenticwp' ) ),
					400
				);
			}

			$result = $this->action_manager->delete_category( $category_key );

			if ( $result ) {
				wp_send_json_success( array( 'message' => __( 'Group deleted successfully.', 'agenticwp' ) ) );
			} else {
				Error_Handler::log_error(
					'database',
					'Failed to delete category',
					array( 'category_key' => $category_key )
				);
				wp_send_json_error(
					array( 'message' => __( 'Failed to delete group.', 'agenticwp' ) ),
					500
				);
			}
		} catch ( \Throwable $e ) {
			Error_Handler::log_error(
				'ajax_exception',
				$e->getMessage(),
				array(
					'action' => 'delete_category',
					'file'   => $e->getFile(),
					'line'   => $e->getLine(),
				)
			);
			wp_send_json_error(
				array( 'message' => __( 'An error occurred while deleting the group.', 'agenticwp' ) ),
				500
			);
		}
	}

	/**
	 * Handle AJAX clear unused categories request.
	 */
	public function handle_ajax_clear_unused_categories(): void {
		try {
			$this->verify_ajax_request( 'agenticwp_clear_unused_categories' );

			$result = $this->action_manager->clear_unused_categories();

			if ( $result['success'] ) {
				if ( 0 === $result['removed'] ) {
					wp_send_json_success(
						array(
							'message'    => __( 'No unused groups found.', 'agenticwp' ),
							'removed'    => 0,
							'categories' => array(),
						)
					);
				} else {
					/* translators: %d: number of groups removed */
					$message = sprintf( _n( 'Removed %d unused group.', 'Removed %d unused groups.', $result['removed'], 'agenticwp' ), $result['removed'] );
					wp_send_json_success(
						array(
							'message'    => $message,
							'removed'    => $result['removed'],
							'categories' => $result['categories'],
						)
					);
				}
			} else {
				Error_Handler::log_error(
					'database',
					'Failed to clear unused categories',
					array( 'result' => $result )
				);
				wp_send_json_error(
					array( 'message' => __( 'Failed to clear unused groups.', 'agenticwp' ) ),
					500
				);
			}
		} catch ( \Throwable $e ) {
			Error_Handler::log_error(
				'ajax_exception',
				$e->getMessage(),
				array(
					'action' => 'clear_unused_categories',
					'file'   => $e->getFile(),
					'line'   => $e->getLine(),
				)
			);
			wp_send_json_error(
				array( 'message' => __( 'An error occurred while clearing unused groups.', 'agenticwp' ) ),
				500
			);
		}
	}
}
