<template>
    <div @click="emit('click')" class="input text" :class="{ suffix: $slots.icon || maxlength, disabled, right, 'pre-suffix': $slots.preIcon }" ref="textRef">
        <template v-if="type === 'password'">
            <div class="is-hidden">
                <input type="text" class="is-hidden" />
                <input type="password" class="is-hidden" />
            </div>
        </template>

        <span v-if="$slots.preIcon" class="pre-icon">
            <slot name="preIcon" />
        </span>
        <input
            class="ui-text"
            :class="{ icon: $slots.icon }"
            :type="type"
            :value="modelValue"
            autocomplete="off"
            @input="inputHandler"
            :placeholder="props.placeholder"
            :readonly="readonly"
            :maxlength="props.maxlength"
            @focus="emit('focus')"
            @blur="emit('blur')"
            ref="inputRef"
            v-bind="other"
        />
        <span v-if="$slots.icon || props.maxlength" class="retouch">
            <slot name="icon" />
            <span v-if="props.maxlength" class="len">
                <span>{{ modelValue.length }}</span> / {{ maxlength }}
            </span>
        </span>
        <slot />
    </div>
</template>

<script setup>
import { textPropsDesc } from './state'
import { defineProps, defineEmits, defineExpose, nextTick, ref } from 'vue'
const props = defineProps({
    type: {
        type: String,
        default: 'text',
    },
    ...textPropsDesc,
})
const emit = defineEmits(['update:modelValue', 'focus', 'blur', 'click'])
const test = () => {
    emit('focus')
}
const textRef = ref(null)
const inputRef = ref(null)

const inputHandler = ev => {
    emit('update:modelValue', ev.target.value)
    nextTick(() => {
        if (ev.target.value !== props.modelValue.toString()) {
            ev.target.value = props.modelValue.toString()
        }
    })
}

defineExpose({
    root: textRef,
    input: inputRef,
})
</script>
