<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import { inject } from 'vue'
import { Primitive } from 'reka-ui'
import { useFieldError } from 'vee-validate'
import type { FormItemContext } from '.'
import { FORM_ITEM_INJECT_KEY } from '.'

/**
 * FormControl component - Wrapper for form input elements
 * Provides accessibility attributes and connects to form validation
 */

interface Props extends PrimitiveProps {}

const props = withDefaults(defineProps<Props>(), {
  as: 'div',
})

// Get the form item context for ID
const formItemContext = inject<FormItemContext>(FORM_ITEM_INJECT_KEY)

// Get field validation state from the nearest parent field
const error = useFieldError()
</script>

<template>
  <Primitive
    :id="formItemContext?.id"
    v-bind="props"
    :aria-describedby="error ? `${formItemContext?.id}-message` : undefined"
    :aria-invalid="!!error"
  >
    <slot />
  </Primitive>
</template>
