(function () {
  'use strict';

  function boot() {
    var form = document.querySelector('form.login-card');
    var input = document.getElementById('twofa-code-input');
    if (!form || !input) {
      return;
    }
    input.focus();
    input.select();

    function digitsOnly(val) {
      return String(val || '').replace(/\D/g, '').slice(0, 6);
    }

    function maybeSubmit() {
      if (input.value.length === 6) {
        if (typeof form.requestSubmit === 'function') {
          form.requestSubmit();
        } else {
          form.submit();
        }
      }
    }

    input.addEventListener('input', function () {
      var next = digitsOnly(input.value);
      if (next !== input.value) {
        input.value = next;
      }
      maybeSubmit();
    });

    input.addEventListener('paste', function (ev) {
      ev.preventDefault();
      var text = (ev.clipboardData && ev.clipboardData.getData('text')) || '';
      input.value = digitsOnly(text);
      maybeSubmit();
    });

    document.addEventListener('keydown', function (ev) {
      if (!/^[0-9]$/.test(ev.key)) {
        return;
      }
      var ae = document.activeElement;
      if (ae === input) {
        return;
      }
      var tag = ae && ae.tagName ? ae.tagName.toLowerCase() : '';
      if (tag === 'input' || tag === 'textarea' || tag === 'select' || (ae && ae.isContentEditable)) {
        return;
      }
      ev.preventDefault();
      input.focus();
      input.value = digitsOnly(input.value + ev.key);
      maybeSubmit();
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
