<template>
    <div>
      <h1>{{ title }}</h1>
      <RenderContentComponent :content="content" />
    </div>
  </template>
  
  <script>
  import axios from '@/axios';
  import { mapState, mapGetters } from 'vuex';
  import RenderContentComponent from '@/components/RenderContentComponent.vue';
  
  export default {
    name: 'ContentComponent',
    components: {
      RenderContentComponent
    },
    props: {
      link: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        content: '',
        title: '',
      };
    },
    computed: {
      ...mapState(['menuData']),
      ...mapGetters(['getMenuData']),
    },
    watch: {
      link: {
        immediate: true,
        handler(newLink) {
          this.fetchContent(newLink);
          this.setTitle(newLink);
        },
      },
    },
    methods: {
      async fetchContent(link) {
        try {
          const response = await axios.get(`/page-content?link=${link}`);
          this.content = response.data.content;
        } catch (error) {
          console.error('Fehler beim Abrufen des Inhalts:', error);
        }
      },
      setTitle(link) {
        const findTitle = (menuItems, link) => {
          for (const item of menuItems) {
            if (item.link === link) {
              return item.pageTitle || item.name;
            }
            if (item.submenu && item.submenu.length > 0) {
              const found = findTitle(item.submenu, link);
              if (found) {
                return `${found}`;
              }
            }
          }
          return '';
        };
        this.title = findTitle(this.menuData, link);
      },
    },
  };
  </script>
  
  <style scoped></style>
  