<template>
  <div>
    <span ref="target">
      <slot></slot>
    </span>

    <span ref="content" class="hidden">
      <slot name="content"></slot>
    </span>
  </div>
</template>

<script setup>
  import { computed, onMounted, ref } from "vue"
  import { defaultOptions, useAisTooltip } from "@/composables/tooltip";
  import { hasValue } from "@/util/util";
  import { getDomElement } from "@/util/ais-floater";

  const target = ref(null)
  const content = ref(null)


  const props = defineProps({
    /* The item that triggers the Tooltip to show, when hovered/clicked/etc */
    trigger: { type: String, default: undefined },
    /* The item that the Tooltip floats around - if target is undefined then the trigger will be the target */
    target: { type: String, default: undefined },
    content: { type: String, default: defaultOptions.content },
    placement: { type: String, default: defaultOptions.placement },
    triggers: { type: String, default: defaultOptions.triggers },
    disabled: { type: Boolean, default: defaultOptions.disabled },
    arrow: { type: Boolean, default: defaultOptions.arrow },
    offset: { type: Number, default: defaultOptions.offset },
    flip: { type: Boolean, default: defaultOptions.flip },
    shift: { type: Number, default: defaultOptions.shift },
    allowHtml: { type: Boolean, default: defaultOptions.allowHtml },
    showOnLoad: { type: Boolean, default: defaultOptions.showOnLoad },
  })

  const contentText = computed(() => content.value?.innerHTML? content.value.innerHTML: props.content)

  const options = computed(() => {
    const options = JSON.parse(JSON.stringify(defaultOptions))
    options.trigger = getDomElement(props.trigger)
    options.target = props.target
    options.content = contentText.value
    options.placement = hasValue(props.placement) ? props.placement : options.placement
    options.triggers = hasValue(props.triggers) ? props.triggers : options.triggers
    options.arrow = props.arrow
    options.flip = props.flip
    options.offset = props.offset ? props.offset : options.offset
    options.shift = props.shift ? props.shift : options.shift
    options.disabled = props.disabled
    options.allowHtml = props.allowHtml
    options.showOnLoad = props.showOnLoad
    return options
  })

  const getElement = computed(() => {
    let el = null;
    /* check slot first */
    if(target.value?.childElementCount > 0)
      el = target.value.children[0]

    /* then check target prop */
    if(el == null && props.target)
      el = getDomElement(props.target)

    return el;
  })

  onMounted(() => {
    useAisTooltip(getElement.value, options.value)
  })
</script>

<script>
export default {
  name: "AisTooltip"
}
</script>