var Wick = Wick || {};

Wick.ModalObserver = (function () {
  const modal = $('.modal-scroll-observer');
    modalContent = modal.find('.modal-content'),
    modalBody = modal.find('.modal-body');

  $(document).ready(function () {
    if (!modal.length) {
      return;
    }

    function updateScrollFades() {
      const tolerance = 5;
      const scrollTop = modalBody.scrollTop();
      const scrollHeight = modalBody.prop('scrollHeight');
      const visibleHeight = modalBody.outerHeight();

      const isAtTop = scrollTop <= tolerance;
      const isAtBottom = scrollTop + visibleHeight >= scrollHeight - tolerance;

      let state;

      if (isAtTop && isAtBottom) {
        state = 'full';
      } else if (isAtTop) {
        state = 'top';
      } else if (isAtBottom) {
        state = 'bottom';
      } else {
        state = 'middle';
      }

      modalContent.attr('data-scroll-state', state);
    }

    modalBody.on('scroll', updateScrollFades);

    modal.on('shown.bs.modal', function() {
      updateScrollFades();
    });

    $(window).on('resize', function() {
      if (modal.is(':visible')) {
        updateScrollFades();
      }
    });

  });

})();
