<template>
  <header>
    <div class="header-container w1500">
      <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 @click="updateMenuStats('MENU_00000001')" 
                @mouseover="showSubmenu('MENU_00000001')" @mouseleave="hideSubmenu('MENU_00000001')" :class="{ 'active-menu': isActiveMenu('MENU_00000001') }">
                기록물
                <div class="submenu" v-if="submenuVisible['MENU_00000001']"
                   @mouseover="showSubmenu('MENU_00000001')" @mouseleave="hideSubmenu('MENU_00000001')">
                  <p>• <router-link :to="{ path: '/PicHistorySearch.page' }"
                      @click.native="hideSubmenu('MENU_00000001')">
                      사진 기록물
                    </router-link>
                  </p>
                  <div class="hr"></div>
                  <p>• <router-link :to="{ path: '/VideoHistorySearch.page' }"
                      @click.native="hideSubmenu('MENU_00000001')" >
                      영상 기록물
                    </router-link>
                  </p>
                </div>
              </li>

              <li @click="updateMenuStats('MENU_00000004')" 
                @mouseover="showSubmenu('MENU_00000004')" @mouseleave="hideSubmenu('MENU_00000004')" :class="{ 'active-menu': isActiveMenu('MENU_00000004') }">
                언론에서 바라본 구미시
                <div class="submenu" v-if="submenuVisible['MENU_00000004']"
                   @mouseover="showSubmenu('MENU_00000004')" @mouseleave="hideSubmenu('MENU_00000004')">
                  <p>• <router-link :to="{ path: '/MediaVideoSearch.page' }"
                      @click.native="hideSubmenu('MENU_00000004')">
                      미디어 영상
                    </router-link>
                  </p>
                  <div class="hr"></div>
                  <p>• <router-link :to="{ path: '/NewsReleaseSearch.page' }"
                      @click.native="hideSubmenu('MENU_00000004')">
                      보도자료
                    </router-link>
                  </p>
                </div>
              </li>
              <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'"><router-link
                  :to="{ path: '/MemberManagement.page' }" @click.native="onMemberManagementClick"  exact-active-class="active-menu">회원관리</router-link></li>
              <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'"><router-link
                  :to="{ path: '/CategoryManagement.page' }" @click.native="onCategoryManagementClick"  exact-active-class="active-menu">카테고리 관리</router-link></li>
            </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>
            <ul>
              <li @click="updateMenuStats('MENU_00000001')">
                <h6>기록물</h6>
                <div class="submenu">
                  <p>• <router-link :to="{ path: '/PicHistorySearch.page' }" @click="closeMenu">사진 기록물</router-link></p>
                  <div class="hr pink"></div>
                  <p>• <router-link :to="{ path: '/VideoHistorySearch.page' }" @click="closeMenu">영상 기록물</router-link></p>
                </div>
              </li>
              <li @click="updateMenuStats('MENU_00000004')">
                <h6>언론에서 바라본 구미시</h6>
                <div class="submenu">
                  <p>• <router-link :to="{ path: '/MediaVideoSearch.page' }" @click="closeMenu">미디어 영상</router-link></p>
                  <div class="hr pink"></div>
                  <p>• <router-link :to="{ path: '/NewsReleaseSearch.page' }" @click="closeMenu">보도자료</router-link></p>
                </div>
              </li>
              <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">
                <h6>회원관리</h6>
                <div class="submenu">
                  <p>• <router-link :to="{ path: '/MemberManagement.page' }" @click="closeMenu">회원관리</router-link></p>
                </div>
              </li>
              <li v-if="$store.state.roles[0]?.authority === 'ROLE_ADMIN'">
                <h6>카테고리 관리</h6>
                <div class="submenu">
                  <p>• <router-link :to="{ path: '/CategoryManagement.page' }" @click="closeMenu">카테고리 관리</router-link>
                  </p>
                </div>
              </li>
            </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',
      activeMenu: null,
    };
  },
  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
    },
    setActiveMenu(menuId) {
      this.activeMenu = menuId;
    },
    onMemberManagementClick() {
      this.activeMenu = null; // Clear active menu
    },

    // Handle click on "카테고리 관리" and reset the active menu state
    onCategoryManagementClick() {
      this.activeMenu = null; // Clear active menu
    },
    // Check if the menu item is active
    isActiveMenu(menuId) {
      return this.activeMenu === menuId;
    },
    async updateMenuStats(menuId) {
      try {
        this.activeMenu = menuId;
        const response = await updateStatsByMenuId(menuId);
        if (response.status === 200) {
          console.log(`메뉴 ID ${menuId} 통계 업데이트 성공`);
        }
      } catch (error) {
        console.error(`메뉴 ID ${menuId} 통계 업데이트 중 오류:`, error);
      }
    },
    logout() {
      // 백엔드 로그아웃 API 호출
      logOutProc()
        .then(() => {
          console.log('로그아웃 성공 - 서버 측 쿠키 삭제 완료');
          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>