<script setup lang="ts">
/**
 * Props-driven telephone input composition. Composes the shadcn `Input`
 * primitive (with `type="tel"`) and `FieldFrame` chrome.
 *
 * Self-contained — usable directly in any Vue app:
 *
 *   <TelInput v-model="phone" label="Phone" />
 */
import { onMounted, useTemplateRef } from "vue"
import { Input } from "@/components/ui/input"
import { FieldFrame } from "@/components/ui/field-frame"

export interface TelInputProps {
  modelValue?: string
  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<TelInputProps>(), {
  errors: () => [],
})

const model = defineModel<string>("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="tel"
      :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 == null ? '' : String(v))"
    />
  </FieldFrame>
</template>
