import { type TFunction } from 'i18next';
import { toLocaleDigits } from './persianDigit';

export function formatDate(
  isoDate: string,
  lang: string,
  t: TFunction,
): string {
  const date = new Date(isoDate);
  const now = new Date();
  const diffInMinutes = Math.floor(
    (now.getTime() - date.getTime()) / (1000 * 60),
  );

  if (diffInMinutes < 1) return t('active.justNow');
  if (diffInMinutes < 60) {
    return toLocaleDigits(
      t('active.minutesAgo', { count: diffInMinutes }),
      lang,
    );
  }

  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
    calendar: lang.startsWith('fa') ? 'persian' : 'gregory',
    numberingSystem: lang.startsWith('fa') ? 'arab' : 'latn',
  };
  const displayLocale = lang.startsWith('fa') ? 'fa-IR' : 'en-US';
  const formattedDate = new Intl.DateTimeFormat(displayLocale, options).format(
    date,
  );
  return toLocaleDigits(formattedDate, lang);
}
