/**
 * Duration computation utilities — time-management.
 */
import type { TimeRoundingMode } from '@zync/types'
import { TIME_ROUNDING_LABELS } from '@zync/types'
import { roundDuration } from './rounding'

/**
 * Compute raw elapsed seconds between two timestamps.
 * Returns 0 if stoppedAt is before startedAt.
 */
export function computeRawSeconds(
  startedAt: Date | string,
  stoppedAt: Date | string,
): number {
  const a = new Date(startedAt).getTime()
  const b = new Date(stoppedAt).getTime()
  return Math.max(0, Math.floor((b - a) / 1000))
}

/**
 * Format a live example for the rounding settings preview.
 * Uses 8 minutes 40 seconds (520 seconds) as the canonical demonstration input.
 *
 * @example formatRoundingExample('up_15') → "8m 40s → 15min"
 *          formatRoundingExample('none')  → "8m 40s → 8m 40s (raw)"
 */
export function formatRoundingExample(mode: TimeRoundingMode): string {
  const DEMO_SECONDS = 520 // 8 minutes 40 seconds
  const rounded = roundDuration(DEMO_SECONDS, mode)

  const inputStr = '8m 40s'

  if (mode === 'none') {
    return `${inputStr} → 8m 40s (raw)`
  }

  const totalMinutes = Math.round(rounded / 60)
  return `${inputStr} → ${totalMinutes}min`
}

/**
 * Format seconds as HH:MM:SS string for display.
 */
export function formatDuration(totalSeconds: number): string {
  const h = Math.floor(totalSeconds / 3600)
  const m = Math.floor((totalSeconds % 3600) / 60)
  const s = totalSeconds % 60
  return [h, m, s].map((v) => String(v).padStart(2, '0')).join(':')
}

/**
 * Format seconds as human-readable "{h}h {m}m" for aria-labels.
 * Returns "0m" for zero.
 */
export function formatDurationHuman(totalSeconds: number): string {
  const h = Math.floor(totalSeconds / 3600)
  const m = Math.floor((totalSeconds % 3600) / 60)
  const s = totalSeconds % 60
  if (h > 0) return `${h} hours ${m} minutes`
  if (m > 0) return `${m} minutes`
  return `${s} seconds`
}

/**
 * Get the locale-aware label for a rounding mode.
 */
export function getRoundingLabel(mode: TimeRoundingMode, locale: 'he' | 'en'): string {
  return TIME_ROUNDING_LABELS[mode][locale]
}
