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

const props = defineProps<{
  modelValue: string | number
  type?: 'text' | 'currency' | 'date'
  placeholder?: string
  readonly?: boolean
  required?: boolean
}>()

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

const isFocused = ref(false)

const formattedValue = computed(() => {
  if (props.type === 'currency' && props.modelValue) {
    const num = String(props.modelValue).replace(/[^0-9.-]/g, '')
    if (!num) return ''
    return Number(num).toLocaleString('ko-KR')
  }
  if (props.type === 'date' && String(props.modelValue).length === 8) {
    const v = String(props.modelValue)
    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
  emit('update:modelValue', target.value)
}

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

<template>
  <div style="display: inline-flex; align-items: center; width: 100%;">
    <input
      :value="formattedValue"
      :type="type === 'currency' ? 'text' : type === 'date' ? 'text' : 'text'"
      :placeholder="placeholder"
      :readonly="readonly"
      :style="{
        borderColor: isFocused ? '#2980B9' : '#CBD5E1',
        boxShadow: isFocused ? '0 0 4px rgba(41, 128, 185, 0.4)' : 'none',
        backgroundColor: readonly ? '#ECF0F1' : '#FFFFFF',
        textAlign: type === 'currency' ? 'right' : 'left',
        color: type === 'currency' && String(modelValue).startsWith('-') ? '#E74C3C' : '#2C3E50'
      }"
      style="width: 100%; padding: 4px 8px; border: 1px solid #CBD5E1; border-radius: 2px; font-size: 12px; font-weight: bold; outline: none; transition: border-color 0.2s;"
      @focus="isFocused = true"
      @blur="isFocused = false"
      @input="onInput"
      @keydown="onKeyDown"
    />
  </div>
</template>
