import { act, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { LIMITED_CODEX } from './fixtures/capacity'
import { WrapperCapacity } from './WrapperCapacity'

describe('WrapperCapacity', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.setSystemTime(1_700_000_000_000)
  })
  afterEach(() => vi.useRealTimers())

  it('renders healthy wrappers and opens the selected wrapper', () => {
    const onOpen = vi.fn()
    render(
      <WrapperCapacity
        wrappers={['cursor', 'codex']}
        ratelimits={[]}
        dataAvailable
        onOpen={onOpen}
      />,
    )

    fireEvent.click(screen.getByRole('button', { name: 'cursor ✓' }))
    expect(onOpen).toHaveBeenCalledWith('cursor')
    expect(screen.getByRole('button', { name: 'codex ✓' })).toBeInTheDocument()
  })

  it('renders and ticks a real limited-wrapper countdown', () => {
    render(
      <WrapperCapacity
        wrappers={['cursor', 'codex']}
        ratelimits={[LIMITED_CODEX]}
        dataAvailable
        onOpen={vi.fn()}
      />,
    )

    expect(screen.getByRole('button', { name: 'codex ⏳1:00' })).toBeInTheDocument()
    act(() => vi.advanceTimersByTime(1_000))
    expect(screen.getByRole('button', { name: 'codex ⏳0:59' })).toBeInTheDocument()
  })

  it('renders no countdown when B7 data is unavailable', () => {
    render(
      <WrapperCapacity
        wrappers={['cursor', 'codex']}
        ratelimits={[LIMITED_CODEX]}
        dataAvailable={false}
        onOpen={vi.fn()}
      />,
    )

    expect(screen.getByRole('button', { name: 'cursor' })).toHaveAttribute(
      'data-tips',
      'no limit data yet (B7)',
    )
    expect(screen.getByRole('button', { name: 'codex' })).toBeInTheDocument()
    expect(screen.queryByText(/\d:\d{2}/)).not.toBeInTheDocument()
  })
})
