<template>
  <nav v-if="crumbs.length" class="breadcrumbs" aria-label="Brotkrumen">
    <ol>
      <li v-for="(c, idx) in crumbs" :key="c.to + '-' + idx">
        <router-link v-if="idx < crumbs.length - 1" :to="c.to">{{ c.label }}</router-link>
        <span v-else aria-current="page">{{ c.label }}</span>
      </li>
    </ol>
  </nav>
</template>

<script>
import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';

function findLabel(menuItems, link) {
  for (const item of menuItems) {
    if (item?.link === link) {
      return item.pageTitle || item.name || '';
    }
    if (item?.submenu?.length) {
      const found = findLabel(item.submenu, link);
      if (found) return found;
    }
  }
  return '';
}

export default {
  name: 'BreadcrumbsComponent',
  setup() {
    const route = useRoute();
    const store = useStore();

    const crumbs = computed(() => {
      const path = route.path || '/';
      const list = [{ label: 'Startseite', to: '/' }];

      if (path === '/') return [];

      const label = findLabel(store.state.menuData || [], path);
      list.push({ label: label || 'Seite', to: path });
      return list;
    });

    return { crumbs };
  },
};
</script>

<style scoped>
.breadcrumbs {
  margin: 0 var(--space-3) var(--space-2) var(--space-3);
  font-size: 0.875rem;
  color: var(--color-text-muted);
}

.breadcrumbs ol {
  list-style: none;
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
  margin: 0;
  padding: 0;
}

.breadcrumbs li {
  display: inline-flex;
  align-items: center;
  gap: var(--space-2);
}

.breadcrumbs li:not(:last-child)::after {
  content: '›';
  color: var(--color-text-muted);
}

.breadcrumbs a {
  color: var(--color-text-muted);
  text-decoration: none;
}

.breadcrumbs a:hover,
.breadcrumbs a:focus-visible {
  color: var(--color-text);
  text-decoration: underline;
  text-underline-offset: 2px;
}
</style>
