<template>
  <div class="mm-selector-search__field__wrap">
    <input
      ref="current"
      :value="value"
      :disabled="disabled"
      :placeholder="placeholder"
      class="mm-selector-search__field"
      type="text"
      aria-label="filter select"
      aria-autocomplete="list"
      aria-multiline="false"
      @input="inputHandler"
      @keydown="onKeydown"
      @change="onChange" />
    <span
      ref="mirrorInput"
      class="mm-selector-search__field__mirror">
      &nbsp;{{ value || placeholder }}&nbsp;
    </span>
  </div>
</template>

<script>
export default {
  model: {
    prop: "value",
    event: "input",
  },
  props: {
    visible: Boolean,
    value: String,
    disabled: Boolean,
    renderPlaceholder: Function,
    needAlign: Boolean,
    ariaId: String,
    placeholder: String,
    onKeydown: {
      type: Function,
      default: () => {},
    },
    onChange: {
      type: Function,
      default: () => {},
    },
    onInput: {
      type: Function,
      default: () => {},
    },
  },
  watch: {
    placeholder: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          this.alignInputWidth()
        })
      },
    },
    value: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          this.alignInputWidth()
        })
      },
    },
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.focus()
          })
        }
      },
    },
  },
  methods: {
    focus() {
      this.$refs.current.focus()
    },

    blur() {
      this.$refs.current.blur()
    },

    inputHandler(event) {
      this.onInput(event)
      this.$emit("input", event.target.value)
    },

    alignInputWidth() {
      if (this.needAlign && !this.$isServer) {
        this.$refs.current.style.width = `${this.$refs.mirrorInput.clientWidth}px`
      }
    },
  },
}
</script>
