<template>
  <div :class="getModifiersClass('o-input-search', modifiers)">
    <input type="search" name="query" class="o-input-search__input" :value="modelValue || value" ref="inputField"
      v-bind="$attrs" @keyup.enter="emitSearchValue" @input="handleInput" />
    <button type="button" v-if="linkText"
      class="o-input-search__link o-text-link o-text-link--large o-text-link--forward-icon o-text-link--bounce"
      @click="emitSearchValue">
      {{ linkText }}
    </button>
    <button v-else type="button" class="o-input-search__button" @click="emitSearchValue"></button>
  </div>
</template>

<script setup lang="ts">
import type { ModifierItems } from './input-search.config';
import { useTemplateRef } from 'vue';
import useComponentModifiers from '../../composable/useComponentModifiers';

const props = withDefaults(
  defineProps<{
    value?: string;
    modelValue?: string;
    minInputLength?: number;
    linkText?: string;
    modifiers?: ModifierItems;
  }>(),
  {
    minInputLength: 1,
  }
);

const emit = defineEmits<{
  (e: 'input', value: string): void;
  (e: 'update:modelValue', value: string): void;
  (e: 'search', value: string): void;
}>();

const inputField = useTemplateRef('inputField');

const handleInput = (event: Event) => {
  const value = (event.target as HTMLInputElement).value;
  emit('input', value);
  if (props.modelValue !== undefined) {
    emit('update:modelValue', value);
  }
};

const emitSearchValue = () => {
  const value = inputField.value.value;
  if (value.length >= props.minInputLength) {
    emit('search', value.trim());
  }
};

const { getModifiersClass } = useComponentModifiers();
</script>
