/**
 * API Keys Management
 *
 * Handles deletion and management of OpenAI API keys in the admin interface.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.apiKeys
 */

(function($) {
	'use strict';

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

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

	/**
	 * Initializes API keys management.
	 */
	function init() {
		$(document).on('click', '.agenticwp-delete-key', handleDeleteKey);
	}

	/**
	 * Handles API key deletion.
	 *
	 * @param {jQuery.Event} event - Click event.
	 */
	function handleDeleteKey(event) {
		event.preventDefault();

		const $button = $(this);
		const nonce = $button.data('nonce');

		if (!nonce) {
			return;
		}

		const adminData = getAdminData();
		const confirmText = adminData.deleteConfirmText || 'Are you sure you want to delete your API key?';
		if (!window.confirm(confirmText)) {
			return;
		}

		utils.toggleButtonLoading($button, true, adminData.deleteInProgressText || 'Deleting...');

		utils.postAction({
			action: 'agenticwp_delete_api_key',
			nonce: nonce,
			onSuccess: function(response) {
				if (response && response.success) {
					if (!response.data || !response.data.html) {
						utils.showNotice('API key deleted but page refresh needed.', 'warning');
						return;
					}

					const statusContainer = $button.closest('.agenticwp-api-key-status').parent();
					if (statusContainer.length) {
						statusContainer.html(response.data.html);
					}

					const successMessage = response.data.message || 'API key deleted successfully.';
					utils.showNotice(successMessage, 'success');
					return;
				}

				const errorMessage = response && response.data && response.data.message
					? response.data.message
					: 'Failed to delete API key. Please try again.';
				utils.showNotice(errorMessage, 'error');
			},
			onError: function(error) {
				const errorMessage = error && typeof error === 'string'
					? 'Network error: ' + error
					: 'Network error occurred. Please check your connection.';
				utils.showNotice(errorMessage, 'error');
			},
			onComplete: function() {
				utils.toggleButtonLoading($button, false);
			}
		});
	}

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