(function ($) {
  'use strict';

  function fallbackCopy(text) {
    var ta = document.createElement('textarea');
    ta.value = text;
    ta.setAttribute('readonly', 'readonly');
    ta.style.position = 'absolute';
    ta.style.left = '-9999px';
    document.body.appendChild(ta);
    ta.select();
    try {
      document.execCommand('copy');
    } catch (e) {}
    document.body.removeChild(ta);
  }

  function copyText(text) {
    if (!text) return Promise.resolve();
    if (navigator.clipboard && navigator.clipboard.writeText) {
      return navigator.clipboard.writeText(text);
    }
    fallbackCopy(text);
    return Promise.resolve();
  }

  function showStatus($el, msg) {
    if (!$el || !$el.length) return;
    if (msg) $el.text(msg);
    $el.show();
    window.setTimeout(function () {
      $el.hide();
    }, 1400);
  }

  $(function () {
    var cfg = window.wpsnCfTokenHelper || {};
    var ajaxUrl = cfg.ajaxUrl || (window.ajaxurl || '');

    var $type = $('#wpsn-cf-obj-type');
    var $postWrap = $('#wpsn-cf-post-wrap');
    var $termWrap = $('#wpsn-cf-term-wrap');
    var $taxWrap = $('#wpsn-cf-tax-wrap');

    var $btnTest = $('#wpsn-cf-token-test-btn');
    var $live = $('#wpsn-cf-token-live');
    var $status = $('#wpsn-cf-token-test-status');
    var $result = $('#wpsn-cf-token-test-result');

    var $btnCheatCopy = $('#wpsn-cf-cheat-copy');
    var $cheat = $('#wpsn-cf-cheat');
    var $cheatCopied = $('#wpsn-cf-cheat-copied');

    function updateMode() {
      var t = ($type.val() || 'post').toString();
      if (t === 'term') {
        $postWrap.hide();
        $termWrap.show();
        $taxWrap.show();
      } else {
        $postWrap.show();
        $termWrap.hide();
        $taxWrap.hide();
      }
    }

    if ($type.length) {
      $type.on('change', updateMode);
      updateMode();
    }

    if ($btnCheatCopy.length && $cheat.length) {
      $btnCheatCopy.on('click', function () {
        var text = ($cheat.text() || '').toString();
        if (!text) return;
        copyText(text)
          .then(function () {
            showStatus($cheatCopied, (cfg.i18n && cfg.i18n.copied) ? cfg.i18n.copied : 'Copied.');
          })
          .catch(function () {
            fallbackCopy(text);
            showStatus($cheatCopied, (cfg.i18n && cfg.i18n.copied) ? cfg.i18n.copied : 'Copied.');
          });
      });
    }

    function setStatus(msg, isError) {
      if (!$status.length) return;
      $status.removeClass('notice notice-error notice-success');
      if (isError) {
        $status.addClass('notice notice-error');
      }
      $status.text(msg);
      $status.show();
    }


    function submitDirect(objectType, objectId, taxonomy, token) {
      var form = document.createElement('form');
      form.method = 'post';
      form.action = cfg.directUrl || ajaxUrl || '';
      form.style.display = 'none';
      function addField(name, value) {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = name;
        input.value = value == null ? '' : String(value);
        form.appendChild(input);
      }
      addField('action', cfg.postAction || 'wpsn_cf_token_test_post');
      addField('wpsn_cf_nonce', cfg.postNonce || '');
      addField('object_type', objectType);
      addField('object_id', objectId);
      addField('taxonomy', taxonomy || '');
      addField('token', token || '');
      document.body.appendChild(form);
      form.submit();
    }

    if ($btnTest.length) {
      $btnTest.on('click', function () {
        var objectType = ($type.val() || 'post').toString();
        var token = ($('#wpsn-cf-token').val() || '').toString().trim();
        var objectId = 0;
        var taxonomy = '';

        if (objectType === 'term') {
          objectId = parseInt(($('#wpsn-cf-term-id').val() || '0').toString(), 10) || 0;
          taxonomy = ($('#wpsn-cf-taxonomy').val() || '').toString().trim();
        } else {
          objectId = parseInt(($('#wpsn-cf-post-id').val() || '0').toString(), 10) || 0;
        }

        $result.hide().text('');

        if (!token) {
          setStatus('Please enter a token.', true);
          return;
        }
        if (!objectId || objectId < 1) {
          setStatus(objectType === 'term' ? 'Please enter a Term ID.' : 'Please enter a Post ID.', true);
          return;
        }

        var liveMode = !!($live.length && $live.is(':checked'));
        if (!liveMode) {
          submitDirect(objectType, objectId, taxonomy, token);
          return;
        }

        setStatus((cfg.i18n && cfg.i18n.testing) ? cfg.i18n.testing : 'Testing…', false);

        $.post(
          ajaxUrl,
          {
            action: 'wpsn_cf_token_test',
            nonce: cfg.nonce || '',
            object_type: objectType,
            object_id: objectId,
            taxonomy: taxonomy,
            token: token
          },
          function (resp) {
            if (!resp) {
              setStatus('Empty response.', true);
              return;
            }

            if (resp.success) {
              var d = resp.data || {};
              var val = (d.value || '').toString();
              var lines = [];
              lines.push('Provider used: ' + ((d.provider_used || d.provider || '').toString() || '-'));
              lines.push('Token: ' + ((d.token_normalized || token).toString()));
              lines.push('Key: ' + ((d.key || '').toString() || '-'));
              lines.push('');
              lines.push('Value:');
              lines.push(val !== '' ? val : ((cfg.i18n && cfg.i18n.empty) ? cfg.i18n.empty : 'Empty (no value).'));

              $status.hide();
              $result.text(lines.join("\n")).show();
            } else {
              var msg = (resp.data && resp.data.message) ? resp.data.message : 'Request failed.';
              setStatus(((cfg.i18n && cfg.i18n.error) ? cfg.i18n.error : 'Error:') + ' ' + msg, true);
            }
          },
          'json'
        ).fail(function (xhr) {
          // Busy/shared hosts often fail admin-ajax. Fall back to a normal POST.
          if (xhr && (xhr.status === 0 || xhr.status === 429 || xhr.status === 503 || xhr.status >= 500)) {
            submitDirect(objectType, objectId, taxonomy, token);
            return;
          }
          var msg = 'Request failed.';
          if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
            msg = xhr.responseJSON.data.message;
          }
          setStatus(((cfg.i18n && cfg.i18n.error) ? cfg.i18n.error : 'Error:') + ' ' + msg, true);
        });
      });
    }
  });
})(jQuery);
