/**
 * Auto-expand textarea height as the user types,
 * up to a maximum height of 200px. Adds a scrollbar beyond that.
 */
document.addEventListener('input', function (e) {
  if (
    e.target.tagName === 'TEXTAREA' &&
    e.target.classList.contains('form-control')
  ) {
    const maxHeight = 200; // maximum height in pixels
    e.target.style.height = 'auto';
    e.target.style.overflowY = 'hidden';
    e.target.style.height = Math.min(e.target.scrollHeight, maxHeight) + 'px';
    e.target.style.overflowY = e.target.scrollHeight > maxHeight ? 'auto' : 'hidden';
  }
});

/**
 * Hide lingering success notices as soon as the user interacts with Next/Submit.
 * Prevents a previously displayed success message from sticking around
 * when the form is visited again without a full page refresh.
 */
(function () {
  function hideSuccessMessage(container) {
    if (!container) {
      return;
    }

    var formId = container.getAttribute('data-gf-form-id');
    var selector = '.griffinforms-form-submitted-success_message';

    if (formId) {
      selector += '[data-gf-form-id="' + formId + '"]';
    }

    document.querySelectorAll(selector).forEach(function (message) {
      message.style.display = 'none';
    });
  }

  document.addEventListener('click', function (event) {
    var button = event.target.closest('[data-gf-button-type="next"], [data-gf-button-type="submit"]');
    if (!button) {
      return;
    }
    var formContainer = button.closest('[data-gf-form-id]');
    hideSuccessMessage(formContainer);
  });
})();
