/**
 * MasterQuiz AI - Admin JavaScript
 *
 * Handles API key testing from the settings page.
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

/* global jQuery, masterquizAdmin */
(function ($) {
	'use strict';

	$(document).ready(function () {
		// API Key Test Buttons
		$('.masterquiz-test-api-key').on('click', function (e) {
			e.preventDefault();

			var $button = $(this);
			var provider = $button.data('provider');
			var $result = $('#masterquiz-test-result-' + provider);
			var $input = $('#masterquiz_' + provider + '_api_key');
			var apiKey = $input.val();

			// Skip if input is empty or only the masked placeholder.
			if (!apiKey || apiKey.indexOf('********') === 0) {
				apiKey = '';
			}

			$button.prop('disabled', true);
			$result.removeClass('success error testing')
				.addClass('testing')
				.text(masterquizAdmin.i18n.testing);

			$.ajax({
				url: masterquizAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'masterquiz_test_api_key',
					nonce: masterquizAdmin.nonce,
					provider: provider,
					api_key: apiKey,
				},
				success: function (response) {
					$result.removeClass('testing');

					if (response.success) {
						$result.addClass('success').text(masterquizAdmin.i18n.success);
					} else {
						$result.addClass('error').text(
							response.data && response.data.message
								? response.data.message
								: masterquizAdmin.i18n.failed
						);
					}
				},
				error: function () {
					$result.removeClass('testing')
						.addClass('error')
						.text(masterquizAdmin.i18n.error);
				},
				complete: function () {
					$button.prop('disabled', false);
				},
			});
		});
	});
})(jQuery);
