<script setup lang="ts">
/**
 * Props-driven text input composition. Composes the shadcn `Input`
 * primitive with `FieldFrame` chrome (label + helpText + errors).
 *
 * Self-contained — usable directly in any Vue app:
 *
 *   <TextInput v-model="firstName" label="First name" required />
 *
 * The JSON-driven engine renders this via `ElementRenderer`, which
 * binds `modelValue` / `errors` to the form-data store automatically.
 */
import { onMounted, useTemplateRef } from "vue"
import { Input } from "@/components/ui/input"
import { FieldFrame } from "@/components/ui/field-frame"

export interface TextInputProps {
  modelValue?: string | number | null
  id?: string
  name?: string
  label?: string
  hideLabel?: boolean
  placeholder?: string
  required?: boolean
  readonly?: boolean
  disabled?: boolean
  maxlength?: number
  minlength?: number
  helpText?: string
  errors?: string[]
  autoFocus?: boolean
}

const props = withDefaults(defineProps<TextInputProps>(), {
  errors: () => [],
})

const model = defineModel<string | number | null>("modelValue")

const inputRef = useTemplateRef<HTMLInputElement>("inputRef")

onMounted(() => {
  if (props.autoFocus) {
    inputRef.value?.focus()
  }
})
</script>

<template>
  <FieldFrame
    :label="label"
    :required="required"
    :hide-label="hideLabel"
    :for="id"
    :help-text="helpText"
    :errors="errors"
  >
    <Input
      ref="inputRef"
      :model-value="model ?? undefined"
      :id="id"
      :name="name ?? undefined"
      type="text"
      :placeholder="placeholder ?? ''"
      :readonly="readonly"
      :disabled="disabled"
      :required="required"
      :maxlength="maxlength"
      :minlength="minlength"
      :data-element-name="name ?? undefined"
      :class="errors.length ? 'border-destructive ring-destructive' : ''"
      @update:model-value="(v: string | number | undefined) => (model = v ?? '')"
    />
  </FieldFrame>
</template>
