import moment from "moment";

/**
 * "3 hours ago", in the reader's language.
 *
 * Written out per language rather than through `moment.fromNow()`: the Arabic
 * strings are the client's wording, and `moment`'s own `ar` locale also
 * rewrites digits into Arabic-Indic, which this product does not use anywhere
 * (see the `postformat` override in `lib/i18n/config.ts`).
 *
 * Shared by `CommunityDetailPage`, which had it as a named function, and
 * `InnerPost`, which had the same rules inline as an IIFE.
 */
export function relativeTime(
  /* `| null` as well: `created_at` is `$post->created_at?->toIso8601String()`
     on every community resource, so it is genuinely nullable. The guard below
     already covered it; the signature did not. */
  createdAt: string | null | undefined,
  language: string,
  t: (k: string) => string
) {
  if (!createdAt || !moment(createdAt).isValid()) {
    return t("COMMON.LOADING_TIME") || "Invalid date";
  }

  const now = moment();
  const created = moment(createdAt);
  const secondsDiff = now.diff(created, "seconds");
  const minutesDiff = now.diff(created, "minutes");
  const hoursDiff = now.diff(created, "hours");
  const daysDiff = now.diff(created, "days");

  if (language === "ar") {
    if (secondsDiff < 60) return "منذ ثوانٍ";
    if (minutesDiff < 60)
      return `منذ ${minutesDiff} ${minutesDiff === 1 ? "دقيقة" : "دقائق"}`;
    if (hoursDiff < 24)
      return `منذ ${hoursDiff} ${hoursDiff === 1 ? "ساعة" : "ساعات"}`;
    return `منذ ${daysDiff} ${daysDiff === 1 ? "يوم" : "أيام"}`;
  }

  if (secondsDiff < 60) return "few seconds ago";
  if (minutesDiff < 60)
    return `${minutesDiff} ${minutesDiff === 1 ? "minute" : "minutes"} ago`;
  if (hoursDiff < 24)
    return `${hoursDiff} ${hoursDiff === 1 ? "hour" : "hours"} ago`;
  return `${daysDiff} ${daysDiff === 1 ? "day" : "days"} ago`;
}
