import { useState } from 'react'
import { describe, expect, it, vi } from 'vitest'
import { render, fireEvent } from '@testing-library/react'
import { referenceInputs } from './render.js'
import { FIELD_TYPES } from '@platform-modules/fields'
import type { FieldValue } from '@platform-modules/fields'

describe('referenceInputs registry', () => {
  it('has an unstyled input for every FieldType', () => {
    for (const t of FIELD_TYPES) expect(referenceInputs[t]).toBeTruthy()
  })
  it('text input fires onChange with the new value', () => {
    const onChange = vi.fn()
    const Input = referenceInputs.text
    const { container } = render(
      <Input field={{ type: 'text', key: 'k', label: 'K' }} value={undefined} onChange={onChange} />,
    )
    fireEvent.change(container.querySelector('input')!, { target: { value: 'hi' } })
    expect(onChange).toHaveBeenCalledWith('hi')
  })
  it('relationship input commits both halves from an empty start (no bootstrap deadlock)', () => {
    const Input = referenceInputs.relationship
    // Controlled stateful host — onChange feeds the value back, mirroring real usage.
    function Host() {
      const [value, setValue] = useState<FieldValue | undefined>(undefined)
      return (
        <Input
          field={{ type: 'relationship', key: 'brand', label: 'Brand', targetEntityType: 'vendor' }}
          value={value}
          onChange={setValue}
        />
      )
    }
    const { container } = render(<Host />)
    const inputs = container.querySelectorAll('input')
    const typeInput = inputs[0]!
    const idInput = inputs[1]!
    fireEvent.change(typeInput, { target: { value: 'vendor' } })
    fireEvent.change(idInput, { target: { value: 'v9' } })
    expect(typeInput.value).toBe('vendor')
    expect(idInput.value).toBe('v9')
  })
})
