import { ref, onMounted, onUnmounted } from 'vue'

/**
 * Format a timestamp as a relative/short label (same logic as old client).
 * < 1 min  → "just now"
 * < 1 hour → "5m ago"
 * today    → "14:32"
 * older    → "12.04.2024"
 */
export function formatTimeLabel(ts) {
  if (!ts) return ''
  const d = new Date(ts)
  if (isNaN(d)) return ''
  const diff = Date.now() - d
  if (diff < 60_000)     return 'just now'
  if (diff < 3_600_000)  return `${Math.floor(diff / 60_000)}m ago`
  if (diff < 86_400_000) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  return d.toLocaleDateString()
}

/**
 * Reactive time label that auto-updates every minute.
 * Returns a ref that ticks so "5m ago" stays current.
 */
export function useTimeLabel(tsRef) {
  const label = ref(formatTimeLabel(tsRef.value))

  let timer = null

  function update() {
    label.value = formatTimeLabel(tsRef.value)
  }

  onMounted(() => {
    update()
    timer = setInterval(update, 30_000)
  })

  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })

  return label
}
