import { useEffect } from "react";

/**
 * Publishes the live visual-viewport geometry as CSS custom properties
 * on `<html>` so stylesheets can size dialogs/sheets correctly above
 * the iOS soft keyboard.
 *
 * Why a JS hook (not CSS `dvh`):
 * - Safari iOS/iPadOS ignores the `interactive-widget=resizes-content`
 *   viewport hint, so `100dvh` does NOT shrink when the soft keyboard
 *   opens — it stays equal to the full screen. Any layout pinned with
 *   `dvh` therefore sits behind the keyboard.
 * - `window.visualViewport` IS updated on iOS (including standalone
 *   PWAs) whenever the keyboard, page-pinch zoom, or browser chrome
 *   resizes the visible area. It's the only reliable signal.
 *
 * The hook writes two vars on `document.documentElement`:
 *   --vv-height      : current visualViewport.height in `px`
 *   --vv-offset-top  : current visualViewport.offsetTop in `px`
 * On browsers without `visualViewport` it falls back to `window.innerHeight`
 * and `0`, which matches the pre-existing `100vh` behaviour.
 *
 * Mount once at the app root (e.g. inside `NotificationsSocketBridge`).
 */
export function useVisualViewportVars(): void {
  useEffect(() => {
    if (typeof window === "undefined") return;
    const root = document.documentElement;
    const vv = window.visualViewport ?? null;

    const apply = () => {
      const h = vv ? vv.height : window.innerHeight;
      const top = vv ? vv.offsetTop : 0;
      root.style.setProperty("--vv-height", `${Math.round(h)}px`);
      root.style.setProperty("--vv-offset-top", `${Math.round(top)}px`);
    };

    apply();

    if (vv) {
      vv.addEventListener("resize", apply);
      vv.addEventListener("scroll", apply);
    }
    window.addEventListener("resize", apply);
    window.addEventListener("orientationchange", apply);

    return () => {
      if (vv) {
        vv.removeEventListener("resize", apply);
        vv.removeEventListener("scroll", apply);
      }
      window.removeEventListener("resize", apply);
      window.removeEventListener("orientationchange", apply);
    };
  }, []);
}
