import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import OrgList from './OrgList'
import type { Org } from '../api/client'

const orgs: Org[] = [
  {
    id: 1, orgNo: '001_00', orgName: '국제방송교류재단', status: 'ACTIVE',
    applicant: null, mj: null, itn: null, lawyer: null, lawyerAssignedDate: null,
    channelIdMj: 'a', channelIdLaw: 'b', stage: 1,
  },
  {
    id: 2, orgNo: '008_01', orgName: '경찰청_치안정책연구소', status: 'INFO_PENDING',
    applicant: null, mj: null, itn: null, lawyer: null, lawyerAssignedDate: null,
    channelIdMj: null, channelIdLaw: null, stage: null,
  },
]

describe('OrgList', () => {
  it('연번과 기관명을 보여준다', () => {
    render(<OrgList orgs={orgs} selectedId={null} onSelect={() => {}} />)

    expect(screen.getByText('001_00')).toBeTruthy()
    expect(screen.getByText('국제방송교류재단')).toBeTruthy()
    expect(screen.getByText('경찰청_치안정책연구소')).toBeTruthy()
  })

  it('기관을 클릭하면 선택 콜백이 호출된다', () => {
    const onSelect = vi.fn()
    render(<OrgList orgs={orgs} selectedId={null} onSelect={onSelect} />)

    fireEvent.click(screen.getByText('국제방송교류재단'))

    expect(onSelect).toHaveBeenCalledWith(1)
  })

  it('검색어로 기관을 걸러낸다', () => {
    render(<OrgList orgs={orgs} selectedId={null} onSelect={() => {}} />)

    fireEvent.change(screen.getByPlaceholderText('기관명 검색'), {
      target: { value: '경찰' },
    })

    expect(screen.queryByText('국제방송교류재단')).toBeNull()
    expect(screen.getByText('경찰청_치안정책연구소')).toBeTruthy()
  })

  it('접힌 상태에서는 연번만 보이고 이름은 툴팁으로 남는다', () => {
    render(
      <OrgList orgs={orgs} selectedId={null} onSelect={() => {}} collapsed onToggle={() => {}} />,
    )

    expect(screen.getByText('001_00')).toBeTruthy()
    expect(screen.queryByText('국제방송교류재단')).toBeNull()
    expect(screen.queryByPlaceholderText('기관명 검색')).toBeNull()

    const item = screen.getByRole('button', { name: '001_00 국제방송교류재단' })
    expect(item).toHaveAttribute('title', '001_00 국제방송교류재단 (운영 중)')
  })

  it('접힌 상태에서도 기관을 선택할 수 있다', () => {
    const onSelect = vi.fn()
    render(<OrgList orgs={orgs} selectedId={null} onSelect={onSelect} collapsed />)

    fireEvent.click(screen.getByRole('button', { name: '001_00 국제방송교류재단' }))

    expect(onSelect).toHaveBeenCalledWith(1)
  })

  it('접기 버튼을 누르면 onToggle이 호출된다', () => {
    const onToggle = vi.fn()
    render(<OrgList orgs={orgs} selectedId={null} onSelect={() => {}} onToggle={onToggle} />)

    fireEvent.click(screen.getByRole('button', { name: '기관 목록 접기' }))

    expect(onToggle).toHaveBeenCalled()
  })
})
