(function () {
  const initials = document.querySelector('#ows-initials');

  if (!initials) {
    return;
  }

  const initialsInput = document.querySelector(
    'input.wc-pao-addon-custom-text'
  );
  const inputWrap = document.querySelector('.wc-pao-addon-wrap');

  const restrictions = JSON.parse(initialsInput.dataset.restrictions);
  const maxlength = restrictions.max;

  const initialsChanged = new Event('change', {
    view: window,
    bubbles: true,
    cancelable: true,
  });

  if (inputWrap) {
    clear = document.createElement('a');
    clear.classList.add('ows-reset_variations');
    clear.setAttribute('href', '#');
    clear.innerText = 'Clear';

    clear.addEventListener('click', function (evt) {
      evt.preventDefault();
      initialsInput.value = '';
      this.classList.remove('show');
      initialsInput.dispatchEvent(initialsChanged);
    });

    inputWrap.appendChild(clear);
  }

  if (initials && initialsInput) {
    const clear = document.querySelector('.ows-reset_variations');
    initials.addEventListener('click', function (evt) {
      if (evt.target.tagName.toLowerCase() !== 'span') {
        return;
      }

      clear.classList.add('show');

      console.log(evt.target.innerText);
      if (initialsInput.value.length < maxlength) {
        initialsInput.value = initialsInput.value + evt.target.innerText;
        initialsInput.dispatchEvent(initialsChanged);
      }
    });
  }
})();
