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

describe('SectionCard', () => {
  it('renders the title and children', () => {
    render(
      <SectionCard title="multideal">
        <div>body content</div>
      </SectionCard>,
    )
    expect(screen.getByText('multideal')).toBeInTheDocument()
    expect(screen.getByText('body content')).toBeInTheDocument()
  })

  it('hides the children when collapsed and reports aria-expanded', () => {
    const onToggle = vi.fn()
    render(
      <SectionCard title="multideal" collapsible={{ expanded: false, onToggle }}>
        <div>body content</div>
      </SectionCard>,
    )
    expect(screen.getByRole('button', { name: 'multideal' })).toHaveAttribute('aria-expanded', 'false')
    expect(screen.queryByText('body content')).toBeNull()
  })

  it('shows the children when expanded', () => {
    const onToggle = vi.fn()
    render(
      <SectionCard title="multideal" collapsible={{ expanded: true, onToggle }}>
        <div>body content</div>
      </SectionCard>,
    )
    expect(screen.getByRole('button', { name: 'multideal' })).toHaveAttribute('aria-expanded', 'true')
    expect(screen.getByText('body content')).toBeInTheDocument()
  })

  it('calls onToggle when the title button is clicked', () => {
    const onToggle = vi.fn()
    render(
      <SectionCard title="multideal" collapsible={{ expanded: false, onToggle }}>
        <div>body content</div>
      </SectionCard>,
    )
    screen.getByRole('button', { name: 'multideal' }).click()
    expect(onToggle).toHaveBeenCalledOnce()
  })

  it('keeps the title as plain text without collapsible props', () => {
    render(
      <SectionCard title="multideal">
        <div>body content</div>
      </SectionCard>,
    )
    expect(screen.queryByRole('button', { name: 'multideal' })).toBeNull()
  })

  it('renders a link action when href is given', () => {
    render(
      <SectionCard title="multideal" action={{ label: 'scoreboard →', href: '/scoreboard' }}>
        content
      </SectionCard>,
    )
    const link = screen.getByRole('link', { name: 'scoreboard →' })
    expect(link).toHaveAttribute('href', '/scoreboard')
  })

  it('renders a button action and fires onClick when no href is given', () => {
    const onClick = vi.fn()
    render(
      <SectionCard title="Bots" action={{ label: 'bots →', onClick }}>
        content
      </SectionCard>,
    )
    screen.getByRole('button', { name: 'bots →' }).click()
    expect(onClick).toHaveBeenCalledOnce()
  })

  it('renders a titleBadge inline with the title', () => {
    render(
      <SectionCard title="Limits" titleBadge={<span>stale · 2m</span>}>
        content
      </SectionCard>,
    )
    expect(screen.getByText('stale · 2m')).toBeInTheDocument()
  })
})
