<template>
  <v-tooltip
    :value="show"
    :top="top"
    :bottom="bottom"
    :right="right"
    :left="leftOrDefault"
    :open-on-hover="false"
    :open-on-focus="false"
    :open-on-click="false"
    max-width="360px"
  >
    <template #activator="{}">
      <v-icon
        ref="iconRef"
        icon
        class="ml-3"
        size="18px"
        @click="onIconClicked"
      >
        {{ icon }}
      </v-icon>
    </template>

    <div ref="slotDiv" v-click-out="onClickOutside" class="tooltip">
      <slot />
    </div>
  </v-tooltip>
</template>

<script setup lang="ts">
import type { Ref } from 'vue'

const props = defineProps({
  left: {
    type: Boolean,
    required: false,
    default: false,
  },
  right: {
    type: Boolean,
    required: false,
    default: false,
  },
  top: {
    type: Boolean,
    required: false,
    default: false,
  },
  bottom: {
    type: Boolean,
    required: false,
    default: false,
  },
  icon: {
    type: String,
    required: false,
    default: 'mdi-help-circle',
  },
})

const { $refs } = useNuxtApp()

const show: Ref<boolean> = ref(false)

// Template reference to the icon object
const iconRef = ref(null)

// Left is the default, set it to true if not any other is true
const leftOrDefault: Ref<boolean> = ref(
  props.left || (!props.right && !props.bottom && !props.top),
)

const onIconClicked = (e: MouseEvent) => {
  show.value = !show.value
  e.stopPropagation()
}

const onClickOutside = (e: MouseEvent) => {
  if (show.value) {
    if (e.target === (iconRef.value as { $el: HTMLElement }).$el) {
      return
    }
    show.value = false
  }
}
</script>

<style>
.v-icon {
  cursor: pointer;
  height: 18px;
  width: 18px;
}
.v-tooltip__content {
  pointer-events: all !important;
}
</style>
