<template>
  <li
    :class="classes"
    @mouseenter="onMouseEnter"
    @mouseleave="onMouseLeave"
  >
    <span class="c-context-menu-sub-menu__title">
      <slot name="title">{{title}}</slot>
    </span>
    
    <span class="c-context-menu-sub-menu__icon" />

    <ul
      v-show="hover"
      ref="submenu"
      :class="subMenuClasses"
    >
      <slot />
    </ul>
  </li>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      hover: false,
      subMenuPlacements: []
    }
  },
  computed: {
    classes() {
      return {
        'c-context-menu-item': true,
        'c-context-menu-sub-menu': true,
        'c-context-menu-item--hover': this.hover,
        'c-context-menu-item--disabled': this.disabled
      }
    },
    subMenuClasses() {
      return [
        'c-context-menu',
        ...this.subMenuPlacements
      ]
    }
  },
  methods: {
    onMouseEnter(event) {
      if (this.disabled) return

      const targetDimension = event.target.getBoundingClientRect()

      this.hover = true

      this.$emit('mouseenter', this, event)

      this.$nextTick(() => {
        const subMenuWidth = this.$refs.submenu.clientWidth
        const subMenuHeight = this.$refs.submenu.clientHeight
        const subMenuPlacements = []

        if (targetDimension.right + subMenuWidth >= window.innerWidth)
          subMenuPlacements.push('left')
        else
          subMenuPlacements.push('right')

        if (targetDimension.bottom + subMenuHeight >= window.innerHeight)
          subMenuPlacements.push('bottom')
        else
          subMenuPlacements.push('top')

        this.subMenuPlacements = subMenuPlacements
      })
    },
    onMouseLeave(event) {
      if (this.disabled) return

      this.hover = false

      this.$emit('mouseleave', this, event)
    }
  }
}
</script>
