<template>
 
    <a-breadcrumb class="container-breadcrumb">
      <a-breadcrumb-item>
        <icon-apps />
      </a-breadcrumb-item>
      <a-breadcrumb-item
        v-for="(item, index) in breadcrumbItems"
        :key="item.key"
      >
        <span
          class="item"
          :class="{ clickable: item.path && index !== breadcrumbItems.length - 1 }"
          @click="handleClick(item, index)"
        >
          {{ item.title }}
        </span>
      </a-breadcrumb-item>
    </a-breadcrumb>

</template>

<script setup>
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const buildPathByRecord = (recordPath, params) => {
  return recordPath.replace(/:([^/]+)/g, (_, paramKey) => {
    const value = params[paramKey];
    return value == null ? '' : String(value);
  });
};

const recordToItem = (record, params = {}) => {
  const path =
    typeof record.redirect === 'string'
      ? record.redirect
      : buildPathByRecord(record.path, params);

  return {
    key: record.name || record.path,
    title: record.meta.title,
    path,
  };
};

const resolveParentChain = (parentName) => {
  const parents = [];
  let name = parentName;

  while (name) {
    const resolved = router.resolve({ name });
    const record = resolved.matched.find((m) => m.name === name);
    if (!record?.meta?.title) break;

    parents.unshift({
      ...recordToItem(record, resolved.params),
      path: resolved.path,
    });
    name = record.meta.parent;
  }

  return parents;
};

const breadcrumbItems = computed(() => {
  const matchedWithTitle = route.matched.filter((record) => record.meta?.title);
  if (!matchedWithTitle.length) return [];

  const ancestors = matchedWithTitle.slice(0, -1).map((record) =>
    recordToItem(record, route.params),
  );
  const leaf = matchedWithTitle[matchedWithTitle.length - 1];
  const parentChain = leaf.meta?.parent
    ? resolveParentChain(leaf.meta.parent)
    : [];

  return [...ancestors, ...parentChain, recordToItem(leaf, route.params)];
});

const handleClick = (item, index) => {
  if (!item.path || index === breadcrumbItems.value.length - 1) return;
  if (item.path === route.path) return;
  router.push(item.path);
};
</script>

<style scoped lang="less">
.container-breadcrumb {
  margin: 16px 0;
  :deep(.arco-breadcrumb-item) {
    color: rgb(var(--gray-6));
    &:last-child {
      color: rgb(var(--gray-8));
    }
  }
}

.item {
  cursor: default;
}

.clickable {
  cursor: pointer;
}
</style>
