<template>
  <transition :name="transition">
    <!--
      v-on="$listeners" is getting depricated in vue 3 so this will need to updated as well.
      https://v3.vuejs.org/guide/migration/listeners-removed.html#listeners-removed
    -->
    <popper
      ref="tf-tooltip"
      :class="{ 'with-close': showClose }"
      v-bind="{
        ...$attrs,
        ...$props,
        forceShow: forceShow || showTooltip
      }"
      v-on="$listeners"
      @show="showTooltip = showClose"
    >
      <div
        class="tf-popper tf-tooltip wt-popper wt-tooltip"
        :class="customClass"
      >
        <div>
          <slot />
        </div>

        <TfButton
          v-if="showClose"
          :style="{
            top: `${closePosition.top}px`,
            right: `${closePosition.right}px`
          }"
          class="btn-popper-close"
          icon="times"
          size="icon-no-fill"
          type="primary"
          no-padding
          data-test="close tooltip"
          @click="$refs['tf-tooltip'].doClose()"
        />
      </div>

      <template slot="reference">
        <slot name="reference" />
      </template>
    </popper>
  </transition>
</template>

<script>
  export default {
    name: 'TfTooltip',
    inheritAttrs: false,
    props: {
      appendToBody: {
        type: Boolean,
        default: false,
      },
      closePosition: {
        type: Object,
        default: () => ({
          top: 4,
          right: 4,
        }),
      },
      customClass: {
        type: Object,
        default: () => ({}),
      },
      forceShow: {
        type: Boolean,
        default: false,
      },
      options: {
        type: Object,
        default: () => ({}),
      },
      showClose: {
        type: Boolean,
        default: false,
      },
      transition: {
        type: String,
        default: 'tf-fade-in-linear',
      },
      trigger: {
        type: String,
        default: 'hover',
      },
    },

    data: () => ({
      showTooltip: false,
    }),

    watch: {
      /**
       * Close the tooltip if showClose is changed from the parent.
       */
      showClose() {
        if (!this.showClose) {
          this.$refs['tf-tooltip'].doClose();
        }
      },
    },
  };
</script>

<style lang="scss">
  .tf-popper.tf-tooltip,
  .wt-popper.wt-tooltip {
    box-sizing: border-box;
    padding: 10px;
    font-size: 12px;
    border-radius: 3px;
  }

  .btn-popper-close {
    position: absolute;
  }
</style>
