<template>
  <div>
    <ContentComponent v-if="isKnownMenuPath" :link="normalizedPath" />
    <div v-else class="not-found">
      <h1>Seite existiert nicht</h1>
      <p>Leider existiert die aufgerufene Seite nicht.</p>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import ContentComponent from '@/components/ContentComponent.vue';

function normalizePath(path) {
  if (!path || typeof path !== 'string') {
    return '/';
  }
  let value = path.trim();
  if (!value.startsWith('/')) {
    value = `/${value}`;
  }
  if (value.length > 1) {
    value = value.replace(/\/+$/, '');
  }
  return value || '/';
}

function findByPath(items, targetPath) {
  const normalizedTarget = normalizePath(targetPath);
  for (const item of items || []) {
    if (normalizePath(item?.link || '') === normalizedTarget) {
      return true;
    }
    if (Array.isArray(item?.submenu) && findByPath(item.submenu, normalizedTarget)) {
      return true;
    }
  }
  return false;
}

export default {
  name: 'DefaultComponent',
  components: {
    ContentComponent,
  },
  computed: {
    ...mapState(['menuData']),
    normalizedPath() {
      return normalizePath(this.$route.path);
    },
    isKnownMenuPath() {
      return findByPath(this.menuData, this.normalizedPath);
    },
  },
};
</script>

<style scoped>
.not-found {
  padding: 20px;
}
</style>