import { useEffect, useState } from "react";

/**
 * A Date that stays current: re-renders every `intervalMs` (default 1 min)
 * and immediately when the tab becomes visible again — so greetings and
 * date lines roll over even if the page sat open (or backgrounded on a
 * phone) across a morning/afternoon/midnight boundary.
 */
export function useNow(intervalMs = 60_000): Date {
  const [now, setNow] = useState(() => new Date());

  useEffect(() => {
    const update = () => setNow(new Date());
    const id = setInterval(update, intervalMs);
    const onVisibility = () => {
      if (document.visibilityState === "visible") update();
    };
    document.addEventListener("visibilitychange", onVisibility);
    return () => {
      clearInterval(id);
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, [intervalMs]);

  return now;
}
