<template>
  <li
    :class="[
      'mc-breadcrumb__item',
      { 'is-active': parentBreadcrumb?.props.responsive && last },
    ]"
  >
    <MLink
      v-if="!last"
      :theme="parentBreadcrumb?.props.dark ? 'light' : undefined"
      size="s"
      @click="emit('click', $event)"
    >
      <slot />
    </MLink>
    <span
      v-else
      :class="[
        'mc-link',
        'mc-link--s',
        'mc-breadcrumb__current',
        { 'mc-link--light': parentBreadcrumb?.props.dark },
      ]"
      aria-current="page"
    >
      <slot />
    </span>
  </li>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  inject,
  onBeforeMount,
  onUnmounted,
} from 'vue';
import { MLink } from '../index';
import { childItemsInjectionKey, parentInjectionKey } from './types';

const emit = defineEmits<{
  (e: 'click', open: FocusEvent): void;
}>();

const parentBreadcrumb = inject(parentInjectionKey);

const currentInstance = getCurrentInstance()!;
const otherItems = inject(childItemsInjectionKey)!;
onBeforeMount(() => otherItems.value.push(currentInstance));
onUnmounted(() => {
  const myIndex = otherItems.value.findIndex(
    (it) => it.uid === currentInstance.uid,
  );
  otherItems.value.splice(myIndex, 1);
});

const last = computed(
  () =>
    otherItems.value[otherItems.value.length - 1].uid === currentInstance.uid,
);
</script>

<style lang="scss" scoped>
@import '@mozaic-ds/styles/settings-tools/all-settings';

@import '@mozaic-ds/styles/components/c.breadcrumb';
@import '@mozaic-ds/styles/components/c.links';
</style>
