import { ref } from "vue";
import { useSessions } from "./useSessions";

const appRef = ref(null);
let viewportFitTimer = null;

function updateAppHeight() {
  const { sessions, activeId, focusSession } = useSessions();
  const vv = window.visualViewport;
  const h = vv ? vv.height : window.innerHeight;
  const keyboard = vv && typeof vv.height === "number"
    ? Math.max(0, window.innerHeight - vv.height - (vv.offsetTop || 0))
    : 0;

  if (appRef.value) {
    appRef.value.style.height = h + "px";
    appRef.value.style.setProperty("--keyboard-inset", keyboard + "px");
    appRef.value.style.setProperty("--vvh", h + "px");
  }

  requestAnimationFrame(() => {
    const session = sessions.value.find((s) => s.id === activeId.value);
    if (session) focusSession(session);
  });

  if (viewportFitTimer) clearTimeout(viewportFitTimer);
  viewportFitTimer = setTimeout(() => {
    const session = sessions.value.find((s) => s.id === activeId.value);
    if (session) focusSession(session);
  }, 140);
}

function hideSplashScreen() {
  if (typeof window === "undefined") return;
  const hide = window.__hideSplash;
  if (typeof hide === "function") requestAnimationFrame(() => hide());
}

function setupViewport() {
  if (window.visualViewport) {
    window.visualViewport.addEventListener("resize", updateAppHeight);
    window.visualViewport.addEventListener("scroll", updateAppHeight);
  } else {
    window.addEventListener("resize", updateAppHeight);
  }
  updateAppHeight();
}

function teardownViewport() {
  if (viewportFitTimer) { clearTimeout(viewportFitTimer); viewportFitTimer = null; }
  if (window.visualViewport) {
    window.visualViewport.removeEventListener("resize", updateAppHeight);
    window.visualViewport.removeEventListener("scroll", updateAppHeight);
  } else {
    window.removeEventListener("resize", updateAppHeight);
  }
}

export function useViewport() {
  return { appRef, updateAppHeight, hideSplashScreen, setupViewport, teardownViewport };
}
