import { useSyncExternalStore, useCallback, useRef } from 'react';
import { formatDateTime, formatRelative } from '@/lib/format';
import type { Locale } from '@/lib/i18n';

/**
 * Hydration-safe relative time label. SSR and first client paint use absolute
 * `formatDateTime`; live relative text appears only after mount.
 */
export function useRelativeTimeLabel(
  date: Date | string | null | undefined,
  locale: Locale,
): string {
  const stateRef = useRef({ label: '' });

  const getServerSnapshot = useCallback((): string => {
    if (!date) return '—';
    return formatDateTime(date, locale);
  }, [date, locale]);

  const getSnapshot = useCallback((): string => {
    if (!date) return '—';
    return stateRef.current.label || formatDateTime(date, locale);
  }, [date, locale]);

  const subscribe = useCallback(
    (onStoreChange: () => void) => {
      if (!date) {
        return () => {};
      }

      const tick = () => {
        const next = formatRelative(date, locale);
        if (next !== stateRef.current.label) {
          stateRef.current.label = next;
          onStoreChange();
        }
      };

      const initial = formatRelative(date, locale);
      if (initial !== stateRef.current.label) {
        stateRef.current.label = initial;
        onStoreChange();
      }

      const intervalId = setInterval(tick, 60_000);

      return () => {
        clearInterval(intervalId);
        stateRef.current.label = '';
      };
    },
    [date, locale],
  );

  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
