<template>
    <MenuItem :as="as" :disabled="disabled" v-slot="{ active }">
      <div :class="[active ? activeClass : '']" @click="handleClick">
        <slot name="default" :active="active">

          <AisLink v-if="isLink"
                   :label="label"
                   :href="href"
                   :to="to"
                   :label-class="labelClass"
                   :item-label-class="[itemClass, active ? activeClass : '']"
                   :icon="icon"
                   :icon-class="iconClasses"
                   :arrow-icon="arrowIcon"
                   :arrow-class="arrowClass"
                   class="block no-underline hover:!no-underline"
          >
            <slot name="label">{{ label }}</slot>
          </AisLink>

          <AisItemLabel v-else
                        :class="[itemClass, active ? activeClass : '', 'cursor-pointer']"
                        :label="label"
                        :labelClass="labelClass"
                        :icon="icon"
                        :icon-class="iconClasses"
                        :arrow-icon="arrowIcon"
                        :arrow-class="arrowClass"
          >
            <slot name="label">{{ label }}</slot>
          </AisItemLabel>

        </slot>
      </div>
    </MenuItem>
</template>


<script setup>
  import { computed, inject, onMounted, provide } from "vue";
  import AisLink from "@/components/link/AisLink.vue";
  import AisItemLabel from "@/components/item-label/AisItemLabel.vue";
  import { MenuItem } from '@headlessui/vue'
  import { itemLabelProps } from "@/util/item-label-props";
  import { linkProps } from "@/components/link/link-props";


  const activeClass = inject('activeClass', '')
  const itemClass = inject('itemClass', '')
  const itemIconClass = inject('itemIconClass', '')
  const siblingIconCount = inject('siblingIconCount', 0)
  const incrementIconCount = inject('incrementIconCount', undefined)
  const hasIcon = !!props.icon

  const emit = defineEmits([ 'click'])

  const props = defineProps({
    as: { type: [String, Object], default: () => 'template' },
    disabled: { type: Boolean, default: () => false },
    ...itemLabelProps,
    ...linkProps,
  })

  const iconClasses = computed(() => {
    if(props.iconClass) return props.iconClass

    if(itemIconClass.value !== undefined)
      return itemIconClass.value

    return ''
  })

  const isLink = computed(() => props.href || props.to)

  const handleClick = (e) => { emit('click', e) }

  onMounted(() => { if(hasIcon) incrementIconCount(); })

  provide( 'hasSiblingIcon', computed(() => siblingIconCount.value > 0))
  provide( 'iconClass', computed(() => iconClasses.value) )
</script>

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