(function (root, factory) {
  const exported = factory();
  if (typeof module === 'object' && module.exports) module.exports = exported;
  else root.createMobileSearchViewport = exported;
})(typeof self !== 'undefined' ? self : this, function () {
  return function createMobileSearchViewport(options) {
    const palette = options.palette;
    const results = options.results;
    const viewport = options.viewport;
    const mediaQuery = options.mediaQuery;
    const schedule = options.schedule || (callback => requestAnimationFrame(callback));
    let active = false;
    let scrollTop = 0;

    function applyGeometry() {
      if (!active || !mediaQuery.matches || !viewport) return;
      palette.style.setProperty('--search-viewport-top', `${viewport.offsetTop || 0}px`);
      palette.style.setProperty('--search-viewport-height', `${viewport.height}px`);
    }

    function onViewportChange() {
      schedule(applyGeometry);
    }

    return {
      open() {
        if (active || !mediaQuery.matches || !viewport) return;
        active = true;
        applyGeometry();
        viewport.addEventListener('resize', onViewportChange);
        viewport.addEventListener('scroll', onViewportChange);
      },
      close() {
        if (active && viewport) {
          viewport.removeEventListener('resize', onViewportChange);
          viewport.removeEventListener('scroll', onViewportChange);
        }
        active = false;
        palette.style.removeProperty('--search-viewport-top');
        palette.style.removeProperty('--search-viewport-height');
      },
      rememberScroll() {
        scrollTop = results.scrollTop;
      },
      restoreScroll() {
        schedule(() => { results.scrollTop = scrollTop; });
      },
    };
  };
});
