<template>

  <component v-if="to && isNuxtRouter" is="NuxtLink" :to="linkUrl" class="relative" :class="classes" style="box-shadow: none">
    <AisItemLabel class="items-center" :class="labelClasses" v-bind="modifiedProps"><slot>{{ label }}</slot></AisItemLabel>
  </component>

  <component v-else-if="to && isVueRouter" is="RouterLink" :to="linkUrl" class="relative" :class="classes" style="box-shadow: none">
    <AisItemLabel class="items-center" :class="labelClasses" v-bind="modifiedProps"><slot>{{ label }}</slot></AisItemLabel>
  </component>

  <a v-else :href="linkUrl" class="relative" :class="classes" style="box-shadow: none">
    <AisItemLabel class="items-center" :class="labelClasses" v-bind="modifiedProps"><slot>{{ label }}</slot></AisItemLabel>
  </a>

</template>

<script setup>
  import { computed, getCurrentInstance, onMounted } from "vue";
  import { linkProps } from "@/components/link/link-props";
  import AisItemLabel from "@/components/item-label/AisItemLabel.vue";
  import {itemLabelProps} from "@/util/item-label-props";
  import {classToArray} from "@/util/class-util";

  const props = defineProps({
    ...linkProps,
    ...itemLabelProps,
    itemLabelClass: { type: [String, Array], default: () => '' },
  })

  const isNuxtRouter = computed(() => getCurrentInstance().appContext.components['NuxtLink'] !== undefined)
  const isVueRouter = computed(() => getCurrentInstance().appContext.components['RouterLink'] !== undefined)

  const linkUrl = computed(() => {
    if(props.to) return props.to
    if(props.href) return props.href

    return '/'
  })

  const classes = computed(() => props.iconOnly ? 'icon-only' : '' )
  const labelClasses = computed(() => {
    const classes = []
    if(props.icon)
      classes.push('gap-2')

    classes.push(...classToArray(props.itemLabelClass))

    return classes.join(' ')
  })

  const modifiedProps = computed(() => {
    let mProps = { ...props }
    delete mProps.itemLabelClass
    return mProps
  })

  onMounted(() => {
    // console.log(`link.mounted: isNuxtRouter=[${isNuxtRouter.value}], isVueRouter=[${isVueRouter.value}]`)
  })

</script>

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