document.addEventListener('DOMContentLoaded', async () => {
  if (!document.querySelector('#comments')) {
    return;
  }

  const commentForm = document.getElementById('commentform');
  commentForm.onsubmit = function (e) {
    e.preventDefault();
    async function classify(input) {
      let toxic = false;
      const model = await toxicity.load(80 / 100);
      const results = await model.classify(input);

      for (const r of results) {
        if (r.results[0].match) {
          toxic = true;
          break;
        }
      }

      return toxic;
    }

    try {
      const comment = commentForm.querySelector('#comment').value;
      classify([comment]).then((result) => {
        if (result) {
          alert(wp.i18n.__('Your comment contains inappropriate language. Please revise your comment and try again.', 'generatify'));
        } else {
          HTMLFormElement.prototype.submit.call(commentForm);
        }
      });
    } catch (error) {
      console.error(error);
      HTMLFormElement.prototype.submit.call(commentForm);
    }
  };
});
