import { useEffect, useState, type JSX } from 'react'
import { useDeckTooltip } from './DeckTooltip'
import { formatDurationMs } from './format'

const REFRESH_INTERVAL_MS = 60_000
const MISSING_START_FIELD = 'Missing harness /runs field: currentActivityStartedAt'
const DEFAULT_TOOLTIP_LABEL = 'Current activity started'

export function LiveDuration(props: {
  startAtMs: number | null
  /** Tooltip caption above the absolute timestamp. */
  tooltipLabel?: string
  /** Tooltip body when no start time is known — must name the missing field. */
  missingNote?: string
  /** How often the elapsed value re-renders; seconds-scale callers pass a smaller value. */
  refreshMs?: number
}): JSX.Element {
  const validStart = props.startAtMs !== null && Number.isFinite(props.startAtMs)
  const [nowMs, setNowMs] = useState(() => Date.now())
  const absoluteStart = validStart ? new Date(props.startAtMs!).toISOString() : ''
  const refreshMs = props.refreshMs ?? REFRESH_INTERVAL_MS
  const tooltip = useDeckTooltip(
    validStart ? absoluteStart : props.missingNote ?? MISSING_START_FIELD,
    validStart ? props.tooltipLabel ?? DEFAULT_TOOLTIP_LABEL : 'Data coverage gap',
  )

  useEffect(() => {
    if (!validStart) return
    const interval = window.setInterval(() => setNowMs(Date.now()), refreshMs)
    return () => window.clearInterval(interval)
  }, [validStart, refreshMs])

  if (!validStart) return <span {...tooltip}>—</span>

  return (
    <time dateTime={absoluteStart} {...tooltip}>
      {formatDurationMs(Math.max(0, nowMs - props.startAtMs!))}
    </time>
  )
}
