<script setup lang="ts">
/**
 * Props-driven textarea input composition. Composes the shadcn
 * `Textarea` primitive and `FieldFrame` chrome.
 *
 * Self-contained — usable directly in any Vue app:
 *
 *   <TextareaInput v-model="bio" label="Bio" :rows="5" />
 */
import { onMounted, useTemplateRef } from "vue"
import { Textarea } from "@/components/ui/textarea"
import { FieldFrame } from "@/components/ui/field-frame"

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

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

const model = defineModel<string>("modelValue")

const textareaRef = useTemplateRef<HTMLTextAreaElement>("textareaRef")

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

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