import { useRevalidator } from "@remix-run/react";
import { useEffect } from "react";

export const useRevalidateTimePeriod = () => {
  const { revalidate } = useRevalidator();

  // 15 seconds
  const period = 15 * 1000;

  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === "visible" && !document.querySelector('[role="dialog"]')) {
        revalidate();
      }
    };

    const intervalId = setInterval(() => {
      if (document.visibilityState === "visible" && !document.querySelector('[role="dialog"]')) {
        revalidate();
      }
    }, period);

    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      clearInterval(intervalId);
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [revalidate]);
};
