<template>
  <div>

    <transition
      mode="in-out"
      enter-active-class="animated fadeIn _veryfast _delay-250ms"
      leave-active-class="animated fadeOut _veryfast"
    >
      <!-- Breadcrumb container -->
      <div v-if="breadcrumbs.length > 0" id="_breadcrumb-container">

        <!-- Breadcrumb item -->
        <div v-for="breadcrumb in breadcrumbs" :key="breadcrumb.text" class="_breadcrumb-item">

          <!-- Nav link / muted text -->
          <div class="_breadcrumb-text">
            <Link v-if="breadcrumb.to" :to="breadcrumb.to">{{ breadcrumb.text }}</Link>
            <span v-else>{{ breadcrumb.text }}</span>
          </div>

          <!-- Separator -->
          <div class="_breadcrumb-separator">&rsaquo;</div><!-- eslint-disable-line -->

        </div>

      </div>

    </transition>

  </div>
</template>

<script>
export default {
  name: 'Breadcrumb',
  computed: {
    breadcrumbs: function () {
      let built = []
      if (this.$route.meta.breadcrumb && this.$route.meta.breadcrumb.schema !== null) {
        // Get route meta
        const schema = this.$route.meta.breadcrumb.schema
        // Loop on array
        built = schema.reduce((array, current) => {
          // If find "[someroute]" -> Link to named route
          const re = /^\[(.*)\]$/
          if (re.test(current)) {
            const found = current.match(re)[1]
            const namedRoute = this.$router.getRoutes().find((route) => {
              return route.name === found
            })
            array.push({
              text: namedRoute.meta.breadcrumb.title(this),
              to: namedRoute.path === '' ? '/' : namedRoute.path // prevent Home link
            })
          }
          // If find "<this>" -> title of this route
          if (current === '<this>') {
            array.push({
              text: this.$route.meta.breadcrumb.title(this)
            })
          }
          return array
        }, [])
      }
      return built
    }
  }
}
</script>

<style lang="scss">
#_breadcrumb-container {
  @apply flex;
  @apply w-full;
  @apply bg-gray-100;
  @apply @dark:bg-@dark-primary;
  @apply px-2 py-2;

  ._breadcrumb-item {
    @apply flex;

    ._breadcrumb-text {
      @apply pr-2;
      @apply whitespace-nowrap;
    }

    ._breadcrumb-separator {
      @apply select-none;
      @apply pr-2;
    }

    // For the last item of .breadcrumb-item: hide separator
    &:first-child {
      @apply pl-2;
    }
    // For the last item of .breadcrumb-item: hide separator
    &:last-child {
      ._breadcrumb-separator {
        display: none;
      }
    }
  }
}
</style>
