import { describe, test, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { ChatToolGroup } from './chat-tool-group'
import type { ChatToolItem } from '../types'

describe('ChatToolGroup', () => {
  const tools: ChatToolItem[] = [
    {
      id: '1',
      name: 'Tool #1',
      status: 'complete',
      reference: 'tool_1',
      duration: 1.2,
    },
    {
      id: '2',
      name: 'Tool #2',
      status: 'complete',
      reference: 'tool_2',
      duration: 0.8,
    },
    {
      id: '3',
      name: 'Tool #3',
      status: 'error',
      reference: 'tool_3',
      duration: 2.1,
    },
  ]

  test('renders "N tools used" label when collapsed', () => {
    render(<ChatToolGroup tools={tools} />)
    expect(screen.getByText('3 tools used')).toBeTruthy()
  })

  test('renders individual tool names when expanded', () => {
    render(<ChatToolGroup tools={tools} expanded />)
    expect(screen.getByText(/Tool #1/)).toBeTruthy()
    expect(screen.getByText(/Tool #2/)).toBeTruthy()
    expect(screen.getByText(/Tool #3/)).toBeTruthy()
  })

  test('shows "Error" label on failed tools in the expanded list', () => {
    render(<ChatToolGroup tools={tools} expanded />)
    expect(screen.getByText('Error')).toBeTruthy()
  })

  test('shows error count badge at group level when any tool has error', () => {
    render(<ChatToolGroup tools={tools} />)
    // New UI shows error count ("1") + error icon instead of "Error" text
    expect(screen.getByTestId('ErrorOutlineIcon')).toBeTruthy()
    expect(screen.getByText('1')).toBeTruthy()
  })

  test('calls onExpandedChange when group header is clicked', () => {
    const onChange = vi.fn()
    render(<ChatToolGroup tools={tools} onExpandedChange={onChange} />)
    const summary = screen.getByText('3 tools used').closest('button')
    if (summary) fireEvent.click(summary)
    expect(onChange).toHaveBeenCalled()
  })

  test('preserves individual tool expansion states via expandedTools prop', () => {
    render(
      <ChatToolGroup
        tools={tools}
        expanded
        expandedTools={{ '1': true, '2': false, '3': false }}
      />,
    )
    // Tool #1 should be expanded (shows its reference chip)
    expect(screen.getByText(/tool_1/)).toBeTruthy()
  })

  test('uses custom toolsUsed label', () => {
    render(
      <ChatToolGroup
        tools={tools}
        labels={{ toolsUsed: 'herramientas usadas' }}
      />,
    )
    expect(screen.getByText('3 herramientas usadas')).toBeTruthy()
  })
})
