<template>
  <div class="pui-tooltip-wrapper">
    <transition name="fade">
      <div
        class="pui-tooltip"
        :class="[type, position, {
          'is-multiline': isMultiline || hasContentSlot
        }]"
        :style="customStyle"
        v-if="isActive"
      >
        <template v-if="hasContentSlot">
          <slot name="content" />
        </template>
        <template v-else>{{ label }}</template>
      </div>
    </transition>
    <div
      class="pui-tooltip-trigger"
      @click="onClick"
      @mouseenter="onHover"
      @mouseleave="close"
    >
      <slot />
    </div>
  </div>
</template>

<script>
export default {
  name: "PTooltip",
  props: {
    label: String,
    type: String,
    isMultiline: Boolean,
    width: {
      type: [String, Number],
      default: 'auto'
    },
    position: {
      type: String,
      default: 'is-top',
      validator(value) {
        return [
          'is-top',
          'is-bottom',
          'is-left',
          'is-right'
        ].indexOf(value) > -1
      }
    },
    trigger: {
      type: String,
      default: 'hover',
      validator(value) {
        return ['hover', 'click'].indexOf(value) > -1
      }
    },
  },
  data() {
    return {
      isActive: false,
      newWidth: typeof this.width === 'number'
                ? this.width + 'px'
                : this.width,
    }
  },
  methods: {
    onClick() {
      if (this.trigger === 'click') {
        this.isActive = !this.isActive;
      }
    },
    onHover() {
      if (this.trigger === 'hover') {
        this.isActive = true;
      }
    },
    close() {
      this.isActive = false;
    },
  },
  computed: {
    hasContentSlot() {
      return !!this.$slots.content
    },
    customStyle() {
      return { minWidth: this.newWidth }
    }
  }
}
</script>