<script setup>
import { useRoute, useRouter } from "vue-router";
import { storage } from "@/utils/storage.js";
import DrawerComponent from "@/components/common/DrawerComponent.vue";
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { UserManagerService } from "@/components/service/management/userManagerService";

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

const username = ref("");
const projectName = ref(localStorage.getItem("projectName") || "");

// ----------------------
// Admin 판별 + Admin 모드
// ----------------------
const isAdmin = ref(false); // 관리자 계정 여부
const adminMode = ref(false); // 관리자 메뉴 표시 여부(설정 버튼을 눌렀을 때 true)

function computeIsAdmin() {
  try {
    const raw =
      typeof storage?.getAuth === "function"
        ? storage.getAuth()
        : JSON.parse(localStorage.getItem("autoflow-auth") || "null");

    const roles = raw?.userInfo?.roles ?? raw?.roles ?? [];
    const authCd = raw?.userInfo?.authCd ?? raw?.authCd ?? raw?.auth;

    const inRoles = Array.isArray(roles)
      ? roles.includes("ROLE_ADMIN")
      : roles === "ROLE_ADMIN";

    isAdmin.value = inRoles || authCd === "ADMIN";
  } catch {
    isAdmin.value = false;
  }
}

function enterAdmin() {
  if (!isAdmin.value) return; // 혹시라도 가드
  adminMode.value = true; // 사이드바를 관리자 메뉴로 전환
  router.push("/project"); // 관리자 첫 화면으로 이동
}
function exitAdmin() {
  adminMode.value = false; // 일반 메뉴로 복귀
  // 필요 시 원래 화면으로 유지하거나 홈으로 이동해도 됨
  // router.push("/home");
}

// ----------------------
// 상단 드롭다운 메뉴
// ----------------------
const menu = ref([]);
const menuItems = [
  { title: "Select Project", click: () => goSelect() },
  {
    title: "Change Password",
    click: () => {
      /* 비밀번호 모달 열기 등 */
    },
  },
  { title: "Logout", icon: "mdi-logout", click: () => logOut() },
];

const drawer = ref(null);
const pageTitle = computed(() => route.meta.title);
const pagePath = computed(() => route.path);

function updateUsername() {
  const auth = storage.getAuth?.() ?? null;
  username.value = auth?.userInfo?.username ?? auth?.username ?? "";
}
function refreshProjectName() {
  const v = localStorage.getItem("projectName");
  projectName.value = v ? v : "";
}
function goSelect() {
  router.push("/select");
}
function logOut() {
  UserManagerService.signOut()
    .catch(console.error)
    .finally(() => {
      localStorage.removeItem("autoflow-auth");
      localStorage.removeItem("projectName");
      localStorage.removeItem("projectId");
      username.value = "";
      projectName.value = "";
      sessionStorage.removeItem("initialRedirectDone");
      adminMode.value = false; // 로그아웃 시 관리자모드 해제
      router.push("/login");
    });
}

// storage 변경 반영
function onStorage(e) {
  if (!e.key || e.key === "projectName") refreshProjectName();
  if (!e.key || e.key === "autoflow-auth" || e.key === "auth") {
    updateUsername();
    computeIsAdmin();
  }
}

// mount
onMounted(() => {
  updateUsername();
  computeIsAdmin();
  refreshProjectName();
  menu.value = menuItems;
  window.addEventListener("storage", onStorage);
});
onBeforeUnmount(() => {
  window.removeEventListener("storage", onStorage);
});
// 라우트 바뀔 때 프로젝트명 갱신
watch(
  () => route.fullPath,
  () => refreshProjectName(),
);
</script>

<template>
  <v-app>
    <!-- 사이드바: adminMode에 따라 바꿔치기 -->
    <v-navigation-drawer
      v-model="drawer"
      border="0"
      hide-overlay
      permanent
      v-if="!route.meta.hideSidebar"
    >
      <!-- 기본(일반 사용자) 메뉴 -->
      <DrawerComponent v-if="!adminMode" />

      <!-- 관리자 메뉴 -->
      <template v-else>
        <v-list nav density="compact" class="pt-6">
          <v-list-subheader>Admin</v-list-subheader>
          <v-list-item
            to="/project"
            prepend-icon="mdi-briefcase"
            title="Projects"
          />
          <v-list-item
            to="/users"
            prepend-icon="mdi-account-multiple"
            title="Users"
          />
          <v-divider class="my-3" />
          <v-list-item
            prepend-icon="mdi-arrow-left-bold"
            title="Back to Console"
            @click="exitAdmin"
          />
        </v-list>
      </template>
    </v-navigation-drawer>

    <v-app-bar class="bg-shades-transparent" flat>
      <v-spacer />

      <!-- ✅ 설정 버튼: 관리자에게만 보임 / 누르면 관리자 모드 진입 -->
      <v-tooltip v-if="isAdmin" location="bottom" text="Settings">
        <template #activator="{ props }">
          <v-btn
            icon
            color="primary"
            class="mr-3"
            v-bind="props"
            @click="enterAdmin"
          >
            <v-icon>mdi-cog</v-icon>
          </v-btn>
        </template>
      </v-tooltip>

      <v-tooltip location="bottom" text="Project">
        <template #activator="{ props }">
          <v-btn
            icon
            color="primary"
            class="mr-3"
            @click="goSelect"
            v-bind="props"
          >
            <v-icon>mdi-home</v-icon>
          </v-btn>
        </template>
      </v-tooltip>

      <div style="min-width: 180px" class="d-flex flex-column align-end">
        <div class="font-weight-black">{{ username || "GUEST" }}</div>
        <div class="text-subtitle-2">
          {{ projectName || "No Project Selected" }}
        </div>
      </div>

      <v-menu location="bottom end">
        <template #activator="{ props }">
          <v-btn icon color="primary" v-bind="props" class="mr-3">
            <v-icon>mdi-arrow-down-drop-circle-outline</v-icon>
          </v-btn>
        </template>
        <v-list>
          <v-list-item
            v-for="(item, index) in menu"
            :key="index"
            :value="index"
            @click="item.click"
            :prepend-icon="item.icon"
          >
            <v-list-item-title>{{ item.title }}</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
    </v-app-bar>

    <v-main>
      <v-container
        fluid
        class="pa-16 background d-flex justify-center"
        style="width: 100%"
      >
        <slot></slot>
      </v-container>
    </v-main>
  </v-app>
</template>

<style scoped lang="sass"></style>
