import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Button } from '@/components/ui/Button'

describe('Button', () => {
  it('renders children text', () => {
    render(<Button>Clicca qui</Button>)
    expect(screen.getByText('Clicca qui')).toBeTruthy()
  })

  it('is disabled when loading=true', () => {
    render(<Button loading>Salva</Button>)
    expect(screen.getByRole('button')).toBeDisabled()
  })

  it('shows spinner SVG when loading=true', () => {
    const { container } = render(<Button loading>Salva</Button>)
    expect(container.querySelector('svg')).toBeTruthy()
  })

  it('does not show spinner when not loading', () => {
    const { container } = render(<Button>Salva</Button>)
    expect(container.querySelector('svg')).toBeNull()
  })

  it('is disabled when disabled prop is set', () => {
    render(<Button disabled>Salva</Button>)
    expect(screen.getByRole('button')).toBeDisabled()
  })

  it('calls onClick when clicked', async () => {
    const onClick = vi.fn()
    render(<Button onClick={onClick}>Clic</Button>)
    await userEvent.click(screen.getByRole('button'))
    expect(onClick).toHaveBeenCalledOnce()
  })

  it('does not call onClick when disabled', async () => {
    const onClick = vi.fn()
    render(<Button disabled onClick={onClick}>Clic</Button>)
    await userEvent.click(screen.getByRole('button'))
    expect(onClick).not.toHaveBeenCalled()
  })

  it('applies primary variant class by default', () => {
    render(<Button>Primary</Button>)
    expect(screen.getByRole('button').className).toContain('bg-blue-600')
  })

  it('applies danger variant class', () => {
    render(<Button variant="danger">Elimina</Button>)
    expect(screen.getByRole('button').className).toContain('bg-red-600')
  })

  it('applies secondary variant class', () => {
    render(<Button variant="secondary">Annulla</Button>)
    expect(screen.getByRole('button').className).toContain('bg-gray-200')
  })
})
