export function initialize(element) {
  if (!element) {
    return { dispose() {} };
  }

  const el = element;

  const update = () => {
    const rect = el.getBoundingClientRect();
    const available = Math.max(0, window.innerHeight - rect.top - 8); // leave 8px at bottom
    el.style.maxHeight = `${available}px`;
  };

  update();

  const onResize = () => update();

  window.addEventListener("resize", onResize, { passive: true });
  if (window.visualViewport) {
    window.visualViewport.addEventListener("resize", onResize, { passive: true });
    window.visualViewport.addEventListener("scroll", onResize, { passive: true });
  }

  return {
    dispose() {
      window.removeEventListener("resize", onResize);
      if (window.visualViewport) {
        window.visualViewport.removeEventListener("resize", onResize);
        window.visualViewport.removeEventListener("scroll", onResize);
      }
    }
  };
}