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

describe('Field', () => {
  it('wires label htmlFor to the control id for an accessible name', () => {
    render(
      <Field label="Username">
        <Input />
      </Field>,
    )
    const input = screen.getByRole('textbox', { name: 'Username' })
    expect(screen.getByText('Username').getAttribute('for')).toBe(input.getAttribute('id'))
  })

  it('sets aria-invalid on control and role=alert on error text (edge: error set)', () => {
    render(
      <Field label="Email" error="Invalid email">
        <Input />
      </Field>,
    )
    const input = screen.getByRole('textbox', { name: 'Email' })
    expect(input.getAttribute('aria-invalid')).toBe('true')
    expect(screen.getByRole('alert')).toHaveTextContent('Invalid email')
    expect(input.getAttribute('aria-describedby')).toContain(screen.getByRole('alert').id)
  })

  it('connects hint text via aria-describedby', () => {
    render(
      <Field label="Password" hint="At least 8 characters">
        <Input type="password" />
      </Field>,
    )
    const input = screen.getByLabelText('Password')
    const hint = screen.getByText('At least 8 characters')
    expect(input.getAttribute('aria-describedby')).toContain(hint.id)
  })
})
