import { act, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { LiveDuration } from './LiveDuration'

describe('LiveDuration', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.setSystemTime(Date.UTC(2026, 6, 19, 12))
  })

  afterEach(() => {
    vi.restoreAllMocks()
    vi.useRealTimers()
  })

  it('ticks elapsed time once per minute and clears its interval', () => {
    const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval')
    const { unmount } = render(
      <LiveDuration startAtMs={Date.UTC(2026, 6, 19, 11, 30)} />,
    )

    expect(screen.getByText('30m')).toHaveAttribute(
      'data-tipb',
      '2026-07-19T11:30:00.000Z',
    )
    act(() => vi.advanceTimersByTime(60_000))
    expect(screen.getByText('31m')).toBeInTheDocument()

    unmount()
    expect(clearIntervalSpy).toHaveBeenCalled()
  })

  it('renders an honest coverage gap when start time is unavailable', () => {
    render(<LiveDuration startAtMs={null} />)

    expect(screen.getByText('—')).toHaveAttribute(
      'data-tipb',
      'Missing harness /runs field: currentActivityStartedAt',
    )
  })
})
