<script setup lang="ts">
import { ref, computed } from 'vue'

const props = defineProps<{
  modelValue: string
  readonly?: boolean
}>()

const emit = defineEmits(['update:modelValue', 'enter'])

const isFocused = ref(false)

const formattedDate = computed(() => {
  const v = String(props.modelValue || '').replace(/[^0-9]/g, '')
  if (v.length === 8) {
    return `${v.substring(0,4)}-${v.substring(4,6)}-${v.substring(6,8)}`
  }
  return props.modelValue
})

const onInput = (e: Event) => {
  const target = e.target as HTMLInputElement
  const raw = target.value.replace(/[^0-9]/g, '')
  emit('update:modelValue', raw)
}

const onKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Enter') emit('enter')
}
</script>

<template>
  <div style="display: inline-flex; align-items: center; width: 100%;">
    <input
      :value="formattedDate"
      type="text"
      placeholder="YYYY-MM-DD"
      :readonly="readonly"
      :style="{
        borderColor: isFocused ? '#2980B9' : '#CBD5E1',
        boxShadow: isFocused ? '0 0 4px rgba(41, 128, 185, 0.4)' : 'none',
        backgroundColor: readonly ? '#ECF0F1' : '#FFFFFF'
      }"
      style="width: 100%; padding: 4px 8px; border: 1px solid #CBD5E1; border-radius: 2px; font-size: 12px; font-weight: bold; outline: none;"
      @focus="isFocused = true"
      @blur="isFocused = false"
      @input="onInput"
      @keydown="onKeyDown"
    />
  </div>
</template>
