import { useEffect, useState } from "react";

const useNow = () => {
  const [now, setNow] = useState(new Date());

  useEffect(() => {
    const tick = () => {
      setNow((prev) => {
        const next = new Date();
        return Math.floor(prev.getTime() / 1000) === Math.floor(next.getTime() / 1000)
          ? prev
          : next;
      });
    };

    const intervalId = setInterval(() => {
      if (document.hidden) return;
      tick();
    }, 1000);

    const handleVisibilityChange = () => {
      if (!document.hidden) tick();
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);

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

  return now;
}


export default useNow;
