import { RECHECK_EVENT } from "./constants";
import { getVirtualKeyboard } from "./virtual-keyboard";

export function addKeyboardRecheckListeners(handler: (event?: Event) => void) {
  const vv = window.visualViewport;
  if (vv) {
    vv.addEventListener("resize", handler);
    vv.addEventListener("scroll", handler);
  }

  const virtualKeyboard = getVirtualKeyboard();
  virtualKeyboard?.addEventListener("geometrychange", handler);
  window.addEventListener("resize", handler);
  window.addEventListener("orientationchange", handler);
  window.addEventListener("focusin", handler);
  window.addEventListener("focusout", handler);
  window.addEventListener("blur", handler);
  document.addEventListener("visibilitychange", handler);
  window.addEventListener(RECHECK_EVENT, handler);

  return () => {
    if (vv) {
      vv.removeEventListener("resize", handler);
      vv.removeEventListener("scroll", handler);
    }
    virtualKeyboard?.removeEventListener("geometrychange", handler);
    window.removeEventListener("resize", handler);
    window.removeEventListener("orientationchange", handler);
    window.removeEventListener("focusin", handler);
    window.removeEventListener("focusout", handler);
    window.removeEventListener("blur", handler);
    document.removeEventListener("visibilitychange", handler);
    window.removeEventListener(RECHECK_EVENT, handler);
  };
}
