<template>
  <div class="admin--layout">
    <!-- Header -->
    <header class="admin--header">
      <div class="admin--header-left">
        <div class="admin--logo">
          <h1>AUDI</h1>
          <span class="admin--logo-sub">고진모터스</span>
        </div>
      </div>
      <div class="admin--header-right">
        <button class="admin--header-btn" @click="goToProfile">정보수정</button>
        <button
          type="button"
          class="admin--header-btn admin--header-btn-logout"
          @click.prevent="handleLogout"
        >
          로그아웃
        </button>
      </div>
    </header>

    <!-- Main Content Area -->
    <div class="admin--content-wrapper">
      <!-- Sidebar GNB -->
      <aside class="admin--sidebar">
        <nav class="admin--gnb">
          <div v-for="menu in menuItems" :key="menu.id" class="admin--gnb-group">
            <div class="admin--gnb-title" @click="toggleMenu(menu.id)">
              {{ menu.title }}
              <span
                class="admin--gnb-arrow"
                :class="{ 'is-open': openMenus.includes(menu.id) }"
              >
                ▼
              </span>
            </div>
            <transition name="admin--submenu">
              <ul v-show="openMenus.includes(menu.id)" class="admin--gnb-submenu">
                <li
                  v-for="submenu in menu.children"
                  :key="submenu.path"
                  class="admin--gnb-item"
                  :class="{ 'is-active': isActiveRoute(submenu.path) }"
                >
                  <NuxtLink :to="submenu.path" class="admin--gnb-link">
                    {{ submenu.title }}
                  </NuxtLink>
                </li>
              </ul>
            </transition>
          </div>
        </nav>
      </aside>

      <!-- Content Area -->
      <main class="admin--main">
        <!-- Breadcrumb & Title -->
        <div class="admin--page-header">
          <h2 class="admin--page-title">{{ pageTitle }}</h2>
          <div class="admin--breadcrumb">
            <span v-for="(crumb, index) in breadcrumbs" :key="index">
              <NuxtLink v-if="crumb.path" :to="crumb.path" class="admin--breadcrumb-link">
                {{ crumb.title }}
              </NuxtLink>
              <span v-else class="admin--breadcrumb-current">{{ crumb.title }}</span>
              <span
                v-if="index < breadcrumbs.length - 1"
                class="admin--breadcrumb-separator"
                >/</span
              >
            </span>
          </div>
        </div>

        <!-- Page Content -->
        <div class="admin--page-content">
          <slot />
        </div>

        <!-- Admin Footer -->
        <footer class="admin--footer">
          <p>
            &copy; {{ new Date().getFullYear() }} Audi 고진모터스. All rights reserved.
          </p>
        </footer>
      </main>
    </div>

    <!-- 로그아웃 확인 모달 -->
    <AdminAlertModal
      v-if="showLogoutModal"
      title="로그아웃"
      message="로그아웃 하시겠습니까?"
      type="confirm"
      @confirm="confirmLogout"
      @cancel="closeLogoutModal"
      @close="closeLogoutModal"
    />
  </div>
</template>

<script setup>
  import { ref, computed } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import AdminAlertModal from "~/components/admin/AdminAlertModal.vue";

  const route = useRoute();
  const router = useRouter();

  // 메뉴 열림 상태 관리
  const openMenus = ref(["basic", "branch", "staff", "service", "board", "system"]);

  // GNB 메뉴 구조
  const menuItems = ref([
    {
      id: "basic",
      title: "기본정보관리",
      children: [
        { title: "사이트 정보", path: "/admin/basic/site-info" },
        { title: "팝업관리", path: "/admin/basic/popup" },
      ],
    },
    {
      id: "branch",
      title: "지점장관리",
      children: [
        { title: "지점목록", path: "/admin/branch/list" },
        { title: "지점장목록", path: "/admin/branch/manager" },
      ],
    },
    {
      id: "staff",
      title: "사원관리",
      children: [
        { title: "영업사원관리", path: "/admin/staff/sales" },
        { title: "어드바이저등록", path: "/admin/staff/advisor" },
      ],
    },
    // {
    //   id: 'service',
    //   title: '서비스관리',
    //   children: [
    //     { title: '브로셔요청', path: '/admin/service/brochure' }
    //   ]
    // },
    {
      id: "board",
      title: "게시판관리",
      children: [
        { title: "이벤트", path: "/admin/board/event" },
        { title: "뉴스", path: "/admin/board/news" },
        { title: "IR", path: "/admin/board/ir" },
      ],
    },
    {
      id: "system",
      title: "시스템관리",
      children: [{ title: "관리자관리", path: "/admin/admins" }],
    },
  ]);

  // 메뉴 토글
  const toggleMenu = (menuId) => {
    const index = openMenus.value.indexOf(menuId);
    if (index > -1) {
      openMenus.value.splice(index, 1);
    } else {
      openMenus.value.push(menuId);
    }
  };

  // 현재 활성 라우트 체크
  const isActiveRoute = (path) => {
    return route.path === path;
  };

  // 페이지 타이틀 계산
  const pageTitle = computed(() => {
    for (const menu of menuItems.value) {
      const found = menu.children.find((child) => child.path === route.path);
      if (found) return found.title;
    }
    return "대시보드";
  });

  // Breadcrumb 계산
  const breadcrumbs = computed(() => {
    const crumbs = [{ title: "Home", path: "/admin/dashboard" }];

    for (const menu of menuItems.value) {
      const found = menu.children.find((child) => child.path === route.path);
      if (found) {
        crumbs.push({ title: menu.title, path: null });
        crumbs.push({ title: found.title, path: null });
        break;
      }
    }

    return crumbs;
  });

  // 로그아웃 모달
  const showLogoutModal = ref(false);

  const handleLogout = () => {
    console.log("[Logout] 로그아웃 버튼 클릭");
    showLogoutModal.value = true;
    console.log("[Logout] showLogoutModal:", showLogoutModal.value);
  };

  const confirmLogout = () => {
    console.log("[Logout] 로그아웃 확인");
    localStorage.removeItem("admin_token");
    localStorage.removeItem("admin_user");
    router.push("/admin");
  };

  const closeLogoutModal = () => {
    console.log("[Logout] 모달 닫기");
    showLogoutModal.value = false;
  };

  // 정보수정
  const goToProfile = () => {
    router.push("/admin/profile");
  };
</script>
