"use client";
import { useCallback, useSyncExternalStore } from "react";
import { fmtDateTimeUtc, fmtRelative } from "@/lib/format";
/**
* Hydration-safe relative time: SSR renders the deterministic UTC date; after mount we switch to
* "3 min ago" and refresh every `refreshMs`. Implemented as an external store (time bucket) so no
* setState runs inside effects. suppressHydrationWarning guards against locale drift.
*/
export function RelativeTime({ iso, className, refreshMs = 60_000 }: { iso: string | null | undefined; className?: string; refreshMs?: number }) {
const subscribe = useCallback(
(cb: () => void) => {
const t = setInterval(cb, refreshMs);
return () => clearInterval(t);
},
[refreshMs],
);
// snapshot = current time bucket (ms rounded to the refresh period); null on the server
const bucket = useSyncExternalStore(subscribe, () => Math.floor(Date.now() / refreshMs) * refreshMs, () => null);
if (!iso) return —;
return (
);
}