<template>
  <div
    tabindex="-1"
    @focusout="onFocusOut"
    :class="['c-dropdown', expanded && 'expanded']"
    ref="maindiv"
    >
    <button
      @click="expanded = !expanded"
      class="c-dropdown-button"
      >
      {{labelMapper(currentOption)}}
      <span :class="expanded ? 'dropup' : 'dropdown'">
        &#xE904;
      </span>
    </button>
    <div
      :class="['c-dropdown-menu', expanded && 'expanded']"
      @focusout="onFocusOut"
      >
      <ul class="c-dropdown-list">
        <li
          class="c-dropdown-list-entry"
          v-for="(row, rowIndex) in options.filter(row => row != currentOption)"
          :key="rowIndex"
          @click="expanded = false"
          >
          <slot :row="row"/>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      componentClass: "c-dropdown",
      expanded: false,
    }
  },
  props: {
    options: {
      type: Array,
      required: true
    },
    currentRow: {
      type: Object,
      required: true
    },
    labelMapper: {
      type: Function,
      required: true
    }
  },
  computed: {
    currentOption: function() {
      return this.options.find(row => row._isCurrent)
    }
  },
  methods: {
    onFocusOut: function(evt) {
      if(this.$refs.maindiv?.contains(evt.relatedTarget)) {
        evt.stopPropagation()
        return
      }

      this.expanded = false
    }
  }
}
</script>
