export function initStickyObserver(observedElements, stickyElements, collapseSelector) {
  let io;

  const $observed = observedElements instanceof jQuery
    ? observedElements
    : $(observedElements);

  const $sticky = stickyElements instanceof jQuery
    ? stickyElements
    : $(stickyElements);

  if (!$observed.length || !$sticky.length) return;

  function toggle(hide) {
    $sticky.toggleClass('is-hidden', hide);
    $('body').toggleClass('summary-hidden', hide);
    if (hide) {
      $(collapseSelector).collapse('hide');
    }
  }

  if ('IntersectionObserver' in window) {
    io = new IntersectionObserver(
      entries => {
        const shouldBeHidden = entries.some(e => e.isIntersecting || e.boundingClientRect.y < 0);
        toggle(shouldBeHidden);
      },
      { rootMargin: '0px 0px -20% 0px', threshold: 0 }
    );
    $observed.each((_, el) => io.observe(el));
  } else {
    // Fallback for older browsers
    function check() {
      let anyInViewOrAbove = false;
      $observed.each(function () {
        const r = this.getBoundingClientRect();
        if ((r.top < window.innerHeight * 0.8 && r.bottom > 0) || r.bottom < 0) {
          anyInViewOrAbove = true;
          return false;
        }
      });
      toggle(anyInViewOrAbove);
    }
    $(window)
      .off('scroll.sticky resize.sticky')
      .on('scroll.sticky resize.sticky', check);
    check();
  }
}
