<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"
    />

    <!-- 관리자 정보수정 모달 -->
    <AdminModal
      v-if="showProfileModal"
      :admin="currentAdmin"
      @close="closeProfileModal"
      @saved="handleProfileSaved"
    />

    <!-- 알림 모달 -->
    <AdminAlertModal
      v-if="alertModal.show"
      :title="alertModal.title"
      :message="alertModal.message"
      :type="alertModal.type"
      @confirm="handleAlertConfirm"
      @cancel="handleAlertCancel"
      @close="closeAlertModal"
    />
  </div>
</template>

<script setup>
  import { ref, computed } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import AdminAlertModal from "~/components/admin/AdminAlertModal.vue";
  import AdminModal from "~/components/admin/AdminModal.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", pattern: /^\/admin\/basic\/site-info/ },
        { title: "팝업관리", path: "/admin/basic/popup", pattern: /^\/admin\/basic\/popup/ },
      ],
    },
    {
      id: "branch",
      title: "지점장관리",
      children: [
        { title: "지점목록", path: "/admin/branch/list", pattern: /^\/admin\/branch\/(list|create|edit)/ },
        { title: "지점장목록", path: "/admin/branch/manager", pattern: /^\/admin\/branch\/manager/ },
      ],
    },
    {
      id: "staff",
      title: "사원관리",
      children: [
        { title: "영업사원관리", path: "/admin/staff/sales", pattern: /^\/admin\/staff\/sales/ },
        { title: "어드바이저등록", path: "/admin/staff/advisor", pattern: /^\/admin\/staff\/advisor/ },
      ],
    },
    // {
    //   id: 'service',
    //   title: '서비스관리',
    //   children: [
    //     { title: '브로셔요청', path: '/admin/service/brochure', pattern: /^\/admin\/service\/brochure/ }
    //   ]
    // },
    {
      id: "board",
      title: "게시판관리",
      children: [
        { title: "이벤트", path: "/admin/board/event", pattern: /^\/admin\/board\/event/ },
        { title: "뉴스", path: "/admin/board/news", pattern: /^\/admin\/board\/news/ },
        { title: "IR", path: "/admin/board/ir", pattern: /^\/admin\/board\/ir/ },
      ],
    },
    {
      id: "system",
      title: "시스템관리",
      children: [{ title: "관리자관리", path: "/admin/admins", pattern: /^\/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 findCurrentMenu = () => {
    const currentPath = route.path;

    // 대시보드인 경우
    if (currentPath === '/admin/dashboard' || currentPath === '/admin') {
      return { menu: null, child: null };
    }

    for (const menu of menuItems.value) {
      for (const child of menu.children) {
        // pattern이 있으면 정규식으로 매칭, 없으면 정확히 일치하는지 확인
        if (child.pattern && child.pattern.test(currentPath)) {
          return { menu, child };
        } else if (currentPath === child.path) {
          return { menu, child };
        }
      }
    }

    return { menu: null, child: null };
  };

  // 페이지 타이틀 계산
  const pageTitle = computed(() => {
    const currentPath = route.path;

    // 대시보드
    if (currentPath === '/admin/dashboard' || currentPath === '/admin') {
      return "대시보드";
    }

    const { child } = findCurrentMenu();

    if (child) {
      // 상세 페이지 타이틀 처리
      if (currentPath.includes('/create')) {
        return `${child.title} 등록`;
      } else if (currentPath.includes('/edit/')) {
        return `${child.title} 수정`;
      } else if (currentPath.includes('/print/')) {
        return `${child.title} 인쇄`;
      } else if (currentPath.includes('/print-a2')) {
        return `${child.title} 인쇄 (A2)`;
      }
      return child.title;
    }

    return "대시보드";
  });

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

    // 대시보드인 경우 Home만 표시
    if (currentPath === '/admin/dashboard' || currentPath === '/admin') {
      return crumbs;
    }

    const { menu, child } = findCurrentMenu();

    if (menu && child) {
      // 메뉴 그룹 추가
      crumbs.push({ title: menu.title, path: null });

      // 현재 페이지 타이틀 추가
      if (currentPath.includes('/create')) {
        crumbs.push({ title: child.title, path: child.path });
        crumbs.push({ title: "등록", path: null });
      } else if (currentPath.includes('/edit/')) {
        crumbs.push({ title: child.title, path: child.path });
        crumbs.push({ title: "수정", path: null });
      } else if (currentPath.includes('/print/')) {
        crumbs.push({ title: child.title, path: child.path });
        crumbs.push({ title: "인쇄", path: null });
      } else if (currentPath.includes('/print-a2')) {
        crumbs.push({ title: child.title, path: child.path });
        crumbs.push({ title: "인쇄 (A2)", path: null });
      } else {
        crumbs.push({ title: child.title, path: null });
      }
    }

    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 showProfileModal = ref(false);
  const currentAdmin = ref(null);

  const { get } = useApi();

  // 알림 모달
  const alertModal = ref({
    show: false,
    title: '알림',
    message: '',
    type: 'alert',
    onConfirm: null
  });

  // 알림 모달 표시
  const showAlert = (message, title = '알림') => {
    alertModal.value = {
      show: true,
      title,
      message,
      type: 'alert',
      onConfirm: null
    }
  };

  // 알림 모달 닫기
  const closeAlertModal = () => {
    alertModal.value.show = false;
  };

  // 알림 모달 확인
  const handleAlertConfirm = () => {
    if (alertModal.value.onConfirm) {
      alertModal.value.onConfirm();
    }
    closeAlertModal();
  };

  // 알림 모달 취소
  const handleAlertCancel = () => {
    closeAlertModal();
  };

  // 현재 로그인한 관리자 ID 가져오기
  const getCurrentAdminId = () => {
    if (typeof window === 'undefined') return null;
    const user = localStorage.getItem('admin_user');
    if (!user) return null;
    try {
      return JSON.parse(user).id;
    } catch {
      return null;
    }
  };

  // 정보수정 버튼 클릭
  const goToProfile = async () => {
    const adminId = getCurrentAdminId();
    if (!adminId) {
      showAlert('로그인 정보를 찾을 수 없습니다.', '오류');
      return;
    }

    // 현재 관리자 정보 조회
    const { data, error } = await get(`/admin/${adminId}`);

    if (error) {
      showAlert('관리자 정보를 불러올 수 없습니다.', '오류');
      console.error('[Profile] 관리자 정보 조회 실패:', error);
      return;
    }

    if (data?.success && data?.data) {
      currentAdmin.value = data.data;
      showProfileModal.value = true;
    }
  };

  // 정보수정 모달 닫기
  const closeProfileModal = () => {
    showProfileModal.value = false;
    currentAdmin.value = null;
  };

  // 정보수정 완료
  const handleProfileSaved = (message) => {
    closeProfileModal();
    if (message) {
      showAlert(message, '성공');

      // 로컬스토리지의 사용자 정보도 업데이트
      if (currentAdmin.value) {
        localStorage.setItem('admin_user', JSON.stringify(currentAdmin.value));
      }
    }
  };
</script>
