<template>
  <div class="non-selectable" @mouseleave="hideMenuDebounce()" @mouseenter="showMenu()">
    <q-btn v-if="labelField.to" :to="labelField.to" flat :label="labelField.label" class="cursor-inherit"/>
    <q-btn v-else flat :label="labelField.label" class="cursor-inherit"/>
    <q-menu :ref="labelField.label" @mouseleave="hideMenuDebounce()" @mouseenter="showMenu()" fit>
      <q-list>
        <q-item clickable v-close-popup :to="{name:item.name}" :class="`text-${$dark ? 'white' : 'black'}`" v-for="item in subFields" :key="item.name">
          <q-item-section class="text-capitalize">{{titleCase(item.meta.title)}}</q-item-section>
        </q-item>
      </q-list>
    </q-menu>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { title } from 'change-case'

export default {
  computed: {
    hideMenuDebounce () {
      return debounce(this.hideMenu, 300)
    },
    subFields () {
      return this.sub.map(item => {
        if (typeof item === 'string') return { name: item, meta: { title: item } }
        return item
      })
    },
    labelField () {
      if (typeof this.label === 'string') return { label: this.label }
      return this.label
    }
  },
  methods: {
    titleCase: title,
    hideMenu () {
      this.$refs[this.labelField.label].hide()
    },
    showMenu () {
      this.hideMenuDebounce.cancel()
      this.$refs[this.labelField.label].show()
    }
  },
  props: {
    sub: {
      type: Array,
      default: () => []
    },
    label: {
      type: [String, Object],
      required: true
    },
    to: [String, Object]
  }
}
</script>

<style lang="stylus" scoped>

</style>
<!-- USAGE -->
<!-- 
<nav-item
  :label="{label: 'Ticketing', to: {name:'ticketing'}}"
  :sub="[ 'first-item', { name: 'second-item', meta: { title: 'Second Item' } }]"
  />
-->
