(function () {
  'use strict';

  function bindSecretCopyButton() {
    var button = document.querySelector('[data-pdt-copy-secret]');
    if (!button) {
      return;
    }

    button.addEventListener('click', function (event) {
      event.preventDefault();
      var secret = button.getAttribute('data-pdt-copy-secret') || '';
      if (!secret || !navigator.clipboard) {
        return;
      }

      var textSpan = button.querySelector('.pdt-copy-text');
      var iconSpan = button.querySelector('.dashicons');
      var originalText = textSpan ? textSpan.textContent : '';
      var originalIcon = iconSpan ? iconSpan.className : '';

      navigator.clipboard.writeText(secret).then(function () {
        if (textSpan) {
          textSpan.textContent = (window.pdtAuthenticatorI18n && window.pdtAuthenticatorI18n.copySuccess) || 'Copied!';
        }
        if (iconSpan) {
          iconSpan.className = 'dashicons dashicons-yes';
        }
        button.style.background = 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)';

        setTimeout(function () {
          if (textSpan) {
            textSpan.textContent = originalText;
          }
          if (iconSpan) {
            iconSpan.className = originalIcon;
          }
          button.style.background = '';
        }, 2000);
      });
    });
  }

  function bindCodeInputAutoSubmit() {
    var codeInput = document.getElementById('pdt_authenticator_code');
    if (!codeInput) {
      return;
    }

    codeInput.addEventListener('input', function () {
      this.value = this.value.replace(/[^0-9]/g, '');
    });
  }

  document.addEventListener('DOMContentLoaded', function () {
    bindSecretCopyButton();
    bindCodeInputAutoSubmit();
  });
})();
