<template>
  <header>
    <div class="header-container">
      <div class="logo-wrap">
        <router-link :to="{ path: '/' }" class="logo"><img :src="logo" alt=""></router-link>
      </div>
      <template v-if="!$isEmpty($store.state.userId)">
        <div class="nav-wrap">
          <nav>
            <ul v-if="$store.state.roles.length > 0">
              <li @mouseover="showSubmenu('MENU_00000001')" @mouseleave="hideSubmenu('MENU_00000001')">
                <p :class="{ 'active-menu': this.$route.path.startsWith('/PicHistory') || this.$route.path.startsWith('/VideoHistory') }">기록물</p>
                <div class="submenu" v-if="submenuVisible['MENU_00000001']" @mouseover="showSubmenu('MENU_00000001')" @mouseleave="hideSubmenu('MENU_00000001')">
                  <p :class="{ 'now-menu': this.$route.path.startsWith('/PicHistory') }" @click="moveTo('/PicHistorySearch.page', 'MENU_00000001')">• 사진 기록물</p>
                  <div class="hr"></div>
                  <p :class="{ 'now-menu': this.$route.path.startsWith('/VideoHistory') }" @click="moveTo('/VideoHistorySearch.page', 'MENU_00000001')">• 영상 기록물</p>
                </div>
              </li>
              <li @mouseover="showSubmenu('MENU_00000004')" @mouseleave="hideSubmenu('MENU_00000004')">
                <p :class="{ 'active-menu': this.$route.path.startsWith('/MediaVideo') || this.$route.path.startsWith('/NewsRelease') }">언론에서 바라본 구미시</p>
                <div class="submenu" v-if="submenuVisible['MENU_00000004']" @mouseover="showSubmenu('MENU_00000004')" @mouseleave="hideSubmenu('MENU_00000004')">
                  <p :class="{ 'now-menu': this.$route.path.startsWith('/MediaVideo') }" @click="moveTo('/MediaVideoSearch.page', 'MENU_00000004')">• 미디어 영상</p>
                  <div class="hr"></div>
                  <p :class="{ 'now-menu': this.$route.path.startsWith('/NewsRelease') }" @click="moveTo('/NewsReleaseSearch.page', 'MENU_00000004')">• 스크랩 자료</p>
                </div>
              </li>
              <template v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">
                <li><router-link :to="{ path: '/MemberManagement.page' }" :class="{ 'active-menu': this.$route.path === '/MemberManagement.page' }">회원관리</router-link></li>
                <li><router-link :to="{ path: '/CategoryManagement.page' }" :class="{ 'active-menu': this.$route.path === '/CategoryManagement.page' }">카테고리 관리</router-link></li>
              </template>
            </ul>
          </nav>
        </div>
        <div class="auth-area">
          <ul>
            <li>
              <img src="../../resources/images/icon/user-settings-line.png" alt="">
              <router-link :to="{ path: '/MyInfo.page' }">{{ $store.state.userNm }}</router-link>
            </li>
            <li>
              <div class="line"></div>
            </li>
            <li>
              <img src="../../resources/images/icon/logout-box-line.png" alt="">
              <a href="#" @click.prevent="logout">로그아웃</a>
            </li>
          </ul>
          <a href="#" class="all-menu-btn" @click="toggleMenu"><img src="../../resources/images/allmenu.png" alt=""></a>
        </div>
      </template>
    </div>
    <div class="overlay" v-if="isMenuOpen">
      <div class="all-menu">
        <button @click="closeMenu" class="closebtn">✕</button>
        <div class="nav-wrap">
          <nav class="flex">
            <div class="title"><img :src="title" alt=""></div>
            <ul>
              <li>
                <h6>기록물</h6>
                <div class="submenu">
                  <p :class="{ 'point-menu': this.$route.path.startsWith('/PicHistory') }">• <router-link :to="{ path: '/PicHistorySearch.page' }" @click="closeMenu">사진 기록물</router-link></p>
                  <div class="hr pink"></div>
                  <p :class="{ 'point-menu': this.$route.path.startsWith('/VideoHistory') }">• <router-link :to="{ path: '/VideoHistorySearch.page' }" @click="closeMenu">영상 기록물</router-link></p>
                </div>
              </li>
              <li>
                <h6>언론에서 바라본 구미시</h6>
                <div class="submenu">
                  <p :class="{ 'point-menu': this.$route.path.startsWith('/MediaVideo') }">• <router-link :to="{ path: '/MediaVideoSearch.page' }" @click="closeMenu">미디어 영상</router-link></p>
                  <div class="hr pink"></div>
                  <p :class="{ 'point-menu': this.$route.path.startsWith('/NewsRelease') }">• <router-link :to="{ path: '/NewsReleaseSearch.page' }" @click="closeMenu">스크랩 자료</router-link></p>
                </div>
              </li>
              <template v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">
                <li>
                  <h6>회원관리</h6>
                  <div class="submenu">
                    <p :class="{ 'point-menu': this.$route.path === '/MemberManagement.page' }">• <router-link :to="{ path: '/MemberManagement.page' }" @click="closeMenu">회원관리</router-link></p>
                  </div>
                </li>
                <li>
                  <h6>카테고리 관리</h6>
                  <div class="submenu">
                    <p :class="{ 'point-menu': this.$route.path === '/CategoryManagement.page' }">• <router-link :to="{ path: '/CategoryManagement.page' }" @click="closeMenu">카테고리 관리</router-link>
                    </p>
                  </div>
                </li>
              </template>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </header>
</template>
<script>
import { reactive } from 'vue';
import { logOutProc } from "../../resources/api/user"
import { updateStatsByMenuId } from "../../resources/api/main"

export default {
  data() {
    return {
      submenuVisible: reactive({}),
      isMenuOpen: false,
      // Define the image sources
      logo: 'client/resources/images/logo.png',
      title: 'client/resources/images/title.png',
    };
  },

  methods: {
    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen;
    },

    // 메뉴 닫기
    closeMenu() {
      this.isMenuOpen = false;
    },

    showSubmenu(menuId) {
      this.submenuVisible[menuId] = true;  // Directly mutate the reactive object
    },

    // Hide the submenu for the given menu ID
    hideSubmenu(menuId) {
      this.submenuVisible[menuId] = false;  // Directly mutate the reactive object
    },

    async updateMenuStats(menuId) {
      try {
        this.activeMenu = menuId;
        const response = await updateStatsByMenuId(menuId);
      } catch (error) {
        console.error(`메뉴 ID ${menuId} 통계 업데이트 중 오류:`, error);
      }
    },

    moveTo(path, menuId) {
      this.hideSubmenu(menuId);
      this.$router.push({ path });
    },

    logout() {
      // 백엔드 로그아웃 API 호출
      logOutProc()
        .then(() => {
          this.$store.commit('setStoreReset'); // 로그아웃 성공 후 스토어 초기화
          this.$router.push({ path: '/Login.page' }); // 로그인 페이지로 리다이렉트
        })
        .catch(err => {
          console.error('로그아웃 처리 중 오류:', err);
          this.$store.commit('setStoreReset'); // 오류가 있어도 스토어는 초기화
          this.$router.push({ path: '/Login.page' }); // 로그인 페이지로 리다이렉트
        });
    },
  },
  watch: {},
  computed: {},
  components: {},
  mounted() { },
};
</script>