<template>
  <div
    :class="[`nice-select ${className}`, { open: open }]"
    tabindex="0"
    @click.prevent="open = !open"
    role="button"
    ref=""
  >
    <span class="current">{{ current?.text || placeholder }}</span>
    <ul class="list" role="menubar" @click.prevent="$event.stopPropagation()">
      <li
        v-for="(item, index) in options"
        :class="[`option`, { 'selected focus': current && item.value === current.value }]"
        :key="`option-${index}`"
        @click.prevent="currentHandler(item, index)"
        role="menuitem"
      >
        {{ item.text }}
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import type {ISelect} from "@/types/select-d-t";

export default defineComponent ({
  props: {
    options: {
      type: Array as () => ({value:any;text:string}| ISelect)[],
      required: true,
    },
    defaultCurrent: {
      type:Number,
      required: true,
    },
    placeholder: String,
    className: String,
    name: String,
  },
  name: "NiceSelect",
  data() {
    return {
      open: false,
      current: this.options[this.defaultCurrent],
    };
  },
  methods: {
    onClose() {
      this.open = false;
    },
    currentHandler(item:{value:string;text:string}, index:number) {
      this.current = this.options[index];
      this.$emit("onChange", item);
      this.onClose();
    },
  },
  mounted() {
    // console.log(59, this.current)
  },
  watch: {
    options(n,o) {
      this.current = this.options[this.defaultCurrent];
      // console.log(64, {
      //   current: this.current,
      //   defaultCurrent: this.defaultCurrent,
      //   options: this.options
      // })
    },
  }
});
</script>
