<template>
  <div v-if="breadcrumbList.length > 0" class="breadcrumb-warp">
    <span class="home"><router-link :to="{path : this.$filters.ctxPath('/adm/main.page')}">홈</router-link> &gt; </span>
    <span v-for="(crumb, index) in breadcrumbList" :key="index">
      {{ crumb.menuNm }}
      <span v-if="index < breadcrumbList.length - 1"> &gt; </span>
    </span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      breadcrumbList: [],
    };
  },
  watch: {
    // 페이지 이동 시 동작
    $route: {
      immediate: true,
      handler() {
        this.generateBreadcrumb();
      }
    },
    // 새로고침 시 동작
    '$store.state.menuList': {
      immediate: true,
      handler(val) {
        if (val && val.length > 0) {
          this.generateBreadcrumb();
        }
      }
    }
  },
  methods: {
    generateBreadcrumb() {
      const menuState = this.$store.state;
      const currentPath = this.$route.path;

      // 관리자: childList 기반
      const findFromTree = (menus, path, trail = []) => {
        for (const menu of menus) {
          const newTrail = [...trail, menu];
          if (menu.routerUrl === path) return newTrail;
          if (menu.childList?.length) {
            const found = findFromTree(menu.childList, path, newTrail);
            if (found) return found;
          }
        }
        return null;
      };

      // 사용자: upMenuId 기반
      const findFromFlat = (flatMenus, path) => {
        const findCurrent = flatMenus.find(menu => menu.routerUrl === path);
        if (!findCurrent) return [];

        const buildTrail = (menu, trail = []) => {
          const parent = flatMenus.find(m => m.menuId === menu.upMenuId);
          if (parent) {
            return buildTrail(parent, [parent, ...trail]);
          }
          return trail;
        };

        const trail = buildTrail(findCurrent);
        return [...trail, findCurrent];
      };

      let breadcrumb = [];

      // 구조 판단
      if (menuState.menuList?.length) {
        // 사용자용
        const flatMenus = menuState.menuList.flatMap(menu =>
          [menu, ...(menu.childList || [])]
        );
        breadcrumb = findFromFlat(flatMenus, currentPath);
      } else if (menuState.menu?.childList?.length) {
        // 관리자용
        breadcrumb = findFromTree(menuState.menu.childList, currentPath);
      }

      this.breadcrumbList = breadcrumb;
    },

  },
  mounted(){
    this.generateBreadcrumb();
  }
};
</script>