<template>
  <ul class="crumb-nav breadcrumb">
    <li><a href="/"><i class="fa fa-home"/></a></li>
    <li v-for="(route, index) in crumbs" :key="index">
      <span class="divider">/</span>
      <router-link :to="route">
        {{ route.text }}
      </router-link>
    </li>
  </ul>
</template>

<script>
import { computed, getCurrentInstance } from 'vue'

export default {
  setup: () => {

    const internalInstance = getCurrentInstance()


    const router = internalInstance.appContext.config.globalProperties.$router

    const crumbs = computed(function() {

      const route = internalInstance.appContext.config.globalProperties.$route

      const breadcrumbs = []
      
      route.matched.forEach((part) => {

        if(!part.name && part.children[0].path == ''){
          part = part.children[0]
        }
        if(part.name && (!breadcrumbs[breadcrumbs.length-1] || part.name != breadcrumbs[breadcrumbs.length-1].name)){
          const text = part.meta && part.meta.title ? typeof(part.meta.title) === 'function' ? part.meta.title(route) : part.meta.title : null

          const crumb = {
            name: part.name,
            text
          }
          breadcrumbs.push(crumb)
        }
      })

      return breadcrumbs
    })

    const goBackInBreadcrumb = function () {
      router.replace(crumbs.value[crumbs.value.length-2])
    }
    return {goBackInBreadcrumb, crumbs}
  },
  mounted: function() {
    window.addEventListener('go-back-in-breadcrumb',this.goBackInBreadcrumb)
  },
  unmounted: function() {
    window.removeEventListener('go-back-in-breadcrumb', this.goBackInBreadcrumb)
  },
}
</script>
