import { useCallback, useSyncExternalStore } from "react";
import { applyPollJitter } from "@/shared/config/polling";

function subscribeVisibility(callback: () => void) {
  if (typeof document === "undefined") return () => {};
  document.addEventListener("visibilitychange", callback);
  return () => document.removeEventListener("visibilitychange", callback);
}

function getDocumentVisibility(): DocumentVisibilityState {
  if (typeof document === "undefined") return "visible";
  return document.visibilityState;
}

/**
 * TanStack Query `refetchInterval` callback: polls only while the tab is visible
 * and applies light jitter. Re-subscribes on `visibilitychange` so intervals
 * resume when the user returns to the tab.
 */
export function useVisibilityAwareRefetchInterval(baseIntervalMs: number) {
  const visibility = useSyncExternalStore(
    subscribeVisibility,
    getDocumentVisibility,
    () => "visible" as DocumentVisibilityState,
  );

  return useCallback(
    () => (visibility === "visible" ? applyPollJitter(baseIntervalMs) : false),
    [visibility, baseIntervalMs],
  );
}
