<script setup lang="ts">
/**
 * Props-driven search input composition. Composes the shadcn `Input`
 * primitive (with `type="search"`) and a leading lucide Search icon.
 * Wrapped with `FieldFrame` chrome.
 *
 * Self-contained — usable directly in any Vue app:
 *
 *   <SearchInput v-model="query" label="Search" />
 */
import { onMounted, useTemplateRef } from "vue"
import { Search } from "@lucide/vue"
import { Input } from "@/components/ui/input"
import { FieldFrame } from "@/components/ui/field-frame"

export interface SearchInputProps {
  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<SearchInputProps>(), {
  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"
  >
    <div class="relative">
      <Search
        class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
      />
      <Input
        ref="inputRef"
        :model-value="model ?? undefined"
        :id="id"
        :name="name ?? undefined"
        type="search"
        :placeholder="placeholder ?? ''"
        :readonly="readonly"
        :disabled="disabled"
        :required="required"
        :maxlength="maxlength"
        :minlength="minlength"
        :data-element-name="name ?? undefined"
        :class="[
          'pl-9',
          errors.length ? 'border-destructive ring-destructive' : '',
        ]"
        @update:model-value="(v: string | number | undefined) => (model = v == null ? '' : String(v))"
      />
    </div>
  </FieldFrame>
</template>
