/**
 * relative-time.ts — locale-aware relative time formatter.
 * (hebrew-locale-dates spec 117)
 *
 * Uses native Intl.RelativeTimeFormat — zero bundle cost.
 * { numeric: 'auto' } enables natural-language output:
 *   - Hebrew: 'אתמול', 'מחר', 'לפני 3 ימים', 'בעוד שעה'
 *   - English-IL: 'yesterday', 'tomorrow', '3 days ago', 'in 1 hour'
 *
 * Accepts a BCP-47 formatting tag from toFormattingLocale().
 * Sign is preserved: negative diff = past, positive diff = future.
 *
 * Bucketing thresholds (seconds):
 *   < 60s   → seconds bucket
 *   < 3600s → minutes bucket
 *   < 86400s → hours bucket
 *   else    → days bucket
 *
 * Weeks/months/years are intentionally omitted — 'days' is sufficient for the
 * relative-time contexts in Zync (audit logs, invoice ages, task due dates).
 * Extend this function if longer ranges are needed.
 */

/**
 * Format a date relative to now using locale-aware natural language.
 *
 * @param date   - The reference date (past or future)
 * @param locale - BCP-47 formatting tag from toFormattingLocale(): 'he-IL' | 'en-IL'
 * @returns Localized relative time string
 *
 * @example
 * const threeDaysAgo = new Date(Date.now() - 3 * 86400 * 1000)
 * relativeTime(threeDaysAgo, 'he-IL')  // 'לפני 3 ימים'
 * relativeTime(threeDaysAgo, 'en-IL')  // '3 days ago'
 *
 * const inOneHour = new Date(Date.now() + 3600 * 1000)
 * relativeTime(inOneHour, 'he-IL')     // 'בעוד שעה'
 * relativeTime(inOneHour, 'en-IL')     // 'in 1 hour'
 */
export function relativeTime(date: Date, locale: string): string {
  const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
  const diffSec = (date.getTime() - Date.now()) / 1000

  if (Math.abs(diffSec) < 60) {
    return rtf.format(Math.round(diffSec), 'second')
  }
  if (Math.abs(diffSec) < 3_600) {
    return rtf.format(Math.round(diffSec / 60), 'minute')
  }
  if (Math.abs(diffSec) < 86_400) {
    return rtf.format(Math.round(diffSec / 3_600), 'hour')
  }
  return rtf.format(Math.round(diffSec / 86_400), 'day')
}
