import { describe, it, expect, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { CategoryRowOther } from './category-row-other'

describe('<CategoryRowOther>', () => {
  it('renders the default label + bare count (no parentheses)', () => {
    render(<CategoryRowOther hiddenCount={7} />)
    expect(screen.getByText('Others')).toBeTruthy()
    expect(screen.getByText('7')).toBeTruthy()
    expect(screen.queryByText('(7 more)')).toBeNull()
  })

  it('honors custom labels with {count} placeholder', () => {
    render(
      <CategoryRowOther
        hiddenCount={3}
        otherLabel='Hidden'
        otherCountLabel='+{count} not shown'
      />,
    )
    expect(screen.getByText('Hidden')).toBeTruthy()
    expect(screen.getByText('+3 not shown')).toBeTruthy()
  })

  it('is not a button when onShowAll is omitted (static fallback)', () => {
    const { container } = render(<CategoryRowOther hiddenCount={1} />)
    expect(container.querySelectorAll('[role="button"]').length).toBe(0)
  })

  describe('when onShowAll is provided', () => {
    it('renders as a button', () => {
      render(<CategoryRowOther hiddenCount={4} onShowAll={vi.fn()} />)
      expect(screen.getByRole('button')).toBeTruthy()
    })

    it('fires onShowAll on click', () => {
      const onShowAll = vi.fn()
      render(<CategoryRowOther hiddenCount={4} onShowAll={onShowAll} />)
      fireEvent.click(screen.getByRole('button'))
      expect(onShowAll).toHaveBeenCalledTimes(1)
    })

    it('fires onShowAll on Enter and Space', () => {
      const onShowAll = vi.fn()
      render(<CategoryRowOther hiddenCount={4} onShowAll={onShowAll} />)
      const btn = screen.getByRole('button')
      fireEvent.keyDown(btn, { key: 'Enter' })
      fireEvent.keyDown(btn, { key: ' ' })
      expect(onShowAll).toHaveBeenCalledTimes(2)
    })

    it('is keyboard-focusable', () => {
      render(<CategoryRowOther hiddenCount={4} onShowAll={vi.fn()} />)
      expect(screen.getByRole('button').getAttribute('tabindex')).toBe('0')
    })
  })
})
