import { faNumber } from "@/lib/helpers/format.helper"

export function chatTime(iso: string): string {
  try {
    return new Intl.DateTimeFormat("fa-IR", { hour: "2-digit", minute: "2-digit", hour12: false }).format(new Date(iso))
  } catch {
    return ""
  }
}

/** The day a message belongs to, for grouping: Y-m-d in local time. */
export function chatDayKey(iso: string): string {
  const d = new Date(iso)
  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
}

export function chatDayLabel(iso: string): string {
  const d = new Date(iso)
  const today = new Date()
  const yesterday = new Date()
  yesterday.setDate(today.getDate() - 1)
  if (chatDayKey(iso) === chatDayKey(today.toISOString())) return "امروز"
  if (chatDayKey(iso) === chatDayKey(yesterday.toISOString())) return "دیروز"
  try {
    return new Intl.DateTimeFormat("fa-IR-u-ca-persian", { day: "numeric", month: "long" }).format(d)
  } catch {
    return ""
  }
}

export function chatListTime(iso: string | null): string {
  if (!iso) return ""
  const label = chatDayLabel(iso)
  return label === "امروز" ? chatTime(iso) : label
}

export function unreadLabel(count: number): string {
  return count > 9 ? "۹+" : faNumber(count)
}
