<script setup lang="ts">
interface Props {
  modelValue: string
  placeholder?: string
  useClearButton?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  useClearButton: false,
})

const emit = defineEmits(['update:modelValue', 'input', 'keydown', 'clear'])

const localValue = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value),
})

const onClickClearButton = () => {
  localValue.value = ''
  emit('clear')
}

const onInput = (event: Event) => {
  const target = event.target as HTMLInputElement | null
  if (target) {
    localValue.value = target.value
  }
  emit('input')
}
</script>

<template>
  <div class="group relative w-full">
    <input
      v-model="localValue"
      :type="typeof $attrs.type === 'string' ? $attrs.type : 'text'"
      :placeholder="props.placeholder"
      v-bind="$attrs"
      class="relative w-full h-[48px] px-[12px] outline-none border border-solid border-[1px] border-[#D9D9D9] rounded-[8px] bg-white text-left text-[#333333] text-[14px] font-[400] leading-[20px] tracking-[-0.42px] placeholder:text-[#B2B2B2] md:h-[56px] md:px-[16px] md:text-[16px] md:leading-[26px] md:tracking-[-0.48px] hover:[&:not([readonly])]:border-[#999999] focus:border-[#999999]"
      @input="onInput"
      @keydown="emit('keydown', $event)"
    />
    <AtomsButton
      v-if="props.useClearButton && localValue.length > 0"
      type="action"
      button-size="size-small"
      background-color="#00000000"
      text-color="transparent"
      class="!absolute top-[50%] right-[12px] translate-y-[-50%] flex items-center justify-center w-auto h-auto p-0 md:right-[16px]"
      @click="onClickClearButton"
    >
      <AtomsIconsCloseCircleFill :size="16" color="rgba(0,0,0,0.15)" />
    </AtomsButton>
  </div>
</template>

<style scoped></style>
