jQuery(function ($) {
  const button = $('#willro-test-api');
  if (!button.length || typeof WillroReviewsAdmin === 'undefined') return;

  button.on('click', function (e) {
    e.preventDefault();

    const result = $('#willro-api-result');
    if (!result.length) return;

    result.text(WillroReviewsAdmin.testingText || '').css({ color: '' });

    $.post(WillroReviewsAdmin.ajaxUrl, {
      action: 'willro_test_api',
      nonce: WillroReviewsAdmin.nonce
    })
      .done(function (response) {
        result.empty();

        const msg =
          response && response.data && response.data.message ? response.data.message : '';
        if (!msg) return;

        if (response.success) {
          result.text(msg).css({ color: 'green' });

          if (response.data.linkUrl && response.data.linkText) {
            const link = $('<a/>', {
              href: response.data.linkUrl,
              target: '_blank',
              rel: 'noopener noreferrer',
              text: response.data.linkText
            }).css({
              fontWeight: 'bold',
              textDecoration: 'underline',
              marginLeft: '6px'
            });

            result.append(link);
          }
        } else {
          result.text(msg).css({ color: 'red' });
        }
      })
      .fail(function () {
        result.text(WillroReviewsAdmin.ajaxFailedText || '').css({ color: 'red' });
      });
  });
});
