/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/* eslint-env browser */

const SyliusApiToggle = (el) => {
  const { url } = el.dataset;
  const toggleableElement = document.querySelector('#sylius-api-login-form');
  toggleableElement.classList.add('d-none');

  const findUser = (e) => {
    if (e.target.value.length > 3) {
      fetch(`${url}?email=${e.target.value}`)
        .then((response) => {
          if (String(response.status).match(/^2.*/)) {
            toggleableElement.classList.remove('d-none');
          } else {
            toggleableElement.classList.add('d-none');
          }
        });
    }
  };

  let timer = null;
  el.addEventListener('keyup', (e) => {
    clearTimeout(timer);
    timer = setTimeout(() => findUser(e), 1000);
  });
};

export default SyliusApiToggle;
