import type { Locale } from '@ai-radar/shared';
import { getDictionary } from '@/lib/dictionary';

/**
 * Relative time, rendered on the server.
 *
 * Deliberately not a live-updating client component: a ticking timestamp
 * is exactly the kind of unnecessary UI the brief rules out, and pages
 * regenerate often enough that "2h" stays honest. The <time> element
 * carries the exact value for machines.
 */
export function TimeAgo({
  date,
  locale,
  className,
}: {
  date: string | null;
  locale: Locale;
  className?: string;
}) {
  if (!date) return null;

  const parsed = new Date(date);
  if (Number.isNaN(parsed.getTime())) return null;

  return (
    <time dateTime={parsed.toISOString()} className={className}>
      {formatRelative(parsed, locale)}
    </time>
  );
}

export function formatRelative(date: Date, locale: Locale, now = new Date()): string {
  const t = getDictionary(locale).time;
  const seconds = Math.max(0, Math.floor((now.getTime() - date.getTime()) / 1000));

  if (seconds < 90) return t.now;

  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}${t.minute}`;

  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}${t.hour}`;

  const days = Math.floor(hours / 24);
  if (days < 7) return `${days}${t.day}`;

  const weeks = Math.floor(days / 7);
  if (weeks < 5) return `${weeks}${t.week}`;

  // Past a month an absolute date is more useful. Arabic uses the
  // Gregorian calendar with Western numerals here, matching the
  // numeral decision in docs/DESIGN.md.
  return date.toLocaleDateString(locale === 'ar' ? 'ar' : 'en-US', {
    month: 'short',
    day: 'numeric',
    numberingSystem: 'latn',
  });
}
