(function ($) {
	'use strict';

	$(function () {
		// Inicializa o Color Picker em qualquer campo com a classe
		if ($().wpColorPicker) {
			$('.wpcm-color-picker').wpColorPicker();
		}

		// Lida com o clique do botão de Sincronização
		$('#wpcm-hub-sync-button').on('click', function (e) {
			e.preventDefault();

			var confirmMsg =
				'Are you sure you want to force sync all connected sites?\n\nThis will clear the settings cache on all client sites immediately.';
			if (!window.confirm(confirmMsg)) {
				return; // O usuário clicou em "Cancelar"
			}

			var $button = $(this);
			var $spinner = $button.siblings('.spinner');
			var $notice = $('#wpcm-sync-notice');

			if ($button.is('.disabled')) {
				return;
			}

			$button.addClass('disabled');
			$spinner.css('visibility', 'visible');
			$notice
				.empty()
				.removeClass('notice-success notice-error')
				.addClass('notice-info')
				.html('<p>Scheduling sync jobs...</p>') // Mensagem atualizada
				.slideDown();

			var nonce = wpcm_hub_admin.sync_nonce;

			$.ajax({
				url: wpcm_hub_admin.ajax_url,
				type: 'POST',
				data: {
					action: 'wpcm_hub_sync_sites',
					_ajax_nonce: nonce,
				},
				success: function (response) {
					if (response.success) {
						$notice
							.removeClass('notice-info')
							.addClass('notice-success')
							.html('<p>' + response.data.message + '</p>');
					} else {
						var errorMsg = response.data.message || 'An unknown error occurred.';
						$notice
							.removeClass('notice-info')
							.addClass('notice-error')
							.html('<p>' + errorMsg + '</p>');
					}
				},
				error: function () {
					$notice
						.removeClass('notice-info')
						.addClass('notice-error')
						.html('<p>AJAX request failed.</p>');
				},
				complete: function () {
					$button.removeClass('disabled');
					$spinner.css('visibility', 'hidden');

					setTimeout(function () {
						$notice.slideUp();
					}, 5000);
				},
			});
		});

		// --- INÍCIO DA ADIÇÃO (Teste de Conexão) ---
		$('#wpcm-hub-test-connection').on('click', function (e) {
			e.preventDefault();

			var $button = $(this);
			var $spinner = $button.siblings('.spinner');
			var $status = $('#wpcm-hub-test-status');
			var post_id = $button.data('postid');
			
			// Pega o nonce da página (wpcm_hub_site_nonce)
			var nonce = $('#wpcm_hub_site_nonce').val();

			if ($button.is('.disabled')) {
				return;
			}

			$button.addClass('disabled');
			$spinner.css('visibility', 'visible');
			$status.css('color', '#555').text('Testing...');

			$.ajax({
				url: wpcm_hub_admin.ajax_url,
				type: 'POST',
				data: {
					action: 'wpcm_hub_test_connection',
					_ajax_nonce: wpcm_hub_admin.sync_nonce, // Usamos o nonce global do admin
					post_id: post_id,
					// Passa a URL e a chave atuais dos campos, caso não estejam salvas
					site_url: $('#wpcm_site_url').val(),
					api_key: $('#wpcm_api_key').val(),
					disable_ssl: $('#wpcm_disable_sslverify').is(':checked') ? '1' : '0'
				},
				success: function (response) {
					if (response.success) {
						$status.css('color', '#10b981').text('Success! ' + response.data.message);
						// Atualiza o status principal se o teste for bem-sucedido
						$('strong[style*="ef4444"]').css('color', '#10b981').text('Connected');
					} else {
						$status.css('color', '#ef4444').text('Error: ' + response.data.message);
					}
				},
				error: function () {
					$status.css('color', '#ef4444').text('Error: AJAX request failed.');
				},
				complete: function () {
					$button.removeClass('disabled');
					$spinner.css('visibility', 'hidden');
				},
			});
		});
		// --- FIM DA ADIÇÃO ---

	});
})(jQuery);