<!-- src/components/layout/TopNav.vue -->
<script setup lang="ts">
import { ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { menuUtils } from "@/utils/menuUtils";
import { storage } from "@/utils/storage";

const route = useRoute();
const router = useRouter();
const drawer = ref(false);

// ===== 권한/활성 =====
function readRolesFromStorage(): string[] {
  try {
    const raw =
      storage.get?.("autoflow-auth") ??
      localStorage.getItem("autoflow-auth") ??
      null;
    const auth = typeof raw === "string" ? JSON.parse(raw) : raw;
    let roles = auth?.userInfo?.roles ?? auth?.roles ?? [];
    if (typeof roles === "string")
      roles = roles.split(",").map((s: string) => s.trim());
    return Array.isArray(roles) ? roles : [];
  } catch {
    return [];
  }
}
const isAdmin = computed(() => {
  const roles = readRolesFromStorage();
  return roles.some((r) => r === "ROLE_ADMIN" || r === "ADMIN");
});

const menus = computed(() => [
  ...menuUtils.menuItem,
  ...(isAdmin.value ? menuUtils.adminMenuItem : []),
]);

const isActive = (path?: string) => !!path && route.path.startsWith(path);
const go = (path: string) => {
  if (path && path !== route.path) router.push(path);
};
</script>

<template>
  <!-- 상단 앱바 -->
  <v-app-bar flat height="64" class="topbar">
    <!-- 모바일 햄버거 -->
    <v-app-bar-nav-icon class="d-md-none" @click="drawer = true" />

    <!-- 좌측 로고/타이틀 -->
    <v-toolbar-title class="text-subtitle-1 font-weight-bold">
      Autoflow Web Console
    </v-toolbar-title>

    <!-- 가로 메뉴(데스크탑) -->
    <div class="d-none d-md-flex align-center ml-4 ga-1">
      <template v-for="(m, i) in menus" :key="`m_${i}`">
        <!-- depth가 있는 메뉴: 드롭다운 -->
        <v-menu v-if="m.depth?.length" open-on-hover close-on-content-click>
          <template #activator="{ props }">
            <v-btn
              v-bind="props"
              variant="text"
              class="nav-btn"
              :class="{
                'nav-active': m.depth?.some((d: any) => isActive(d.path)),
              }"
              append-icon="mdi-chevron-down"
            >
              <v-icon start :icon="m.icon" class="mr-1" />
              {{ m.title }}
            </v-btn>
          </template>
          <v-list density="compact" class="min-w-48">
            <v-list-item
              v-for="(d, j) in m.depth"
              :key="`d_${j}`"
              :title="d.title"
              :to="d.path"
              :active="isActive(d.path)"
              :color="isActive(d.path) ? 'primary' : undefined"
            />
          </v-list>
        </v-menu>

        <!-- 단일 링크 -->
        <v-btn
          v-else
          variant="text"
          class="nav-btn"
          :class="{ 'nav-active': isActive(m.path) }"
          @click="go(m.path)"
        >
          <v-icon start :icon="m.icon" class="mr-1" />
          {{ m.title }}
        </v-btn>
      </template>
    </div>

    <v-spacer />

    <!-- 우측 액션 예시 -->
    <div class="d-none d-md-flex align-center ga-2">
      <v-btn icon variant="text" :to="'/home'"><v-icon>mdi-home</v-icon></v-btn>
      <v-btn icon variant="text"><v-icon>mdi-cog</v-icon></v-btn>
    </div>
  </v-app-bar>

  <!-- 모바일 드로어 -->
  <v-navigation-drawer v-model="drawer" temporary class="d-md-none" width="280">
    <v-list nav density="comfortable" class="pa-2">
      <template v-for="(m, i) in menus" :key="`sm_${i}`">
        <v-list-group v-if="m.depth?.length">
          <template #activator="{ props }">
            <v-list-item
              v-bind="props"
              :prepend-icon="m.icon"
              :title="m.title"
            />
          </template>
          <v-list-item
            v-for="(d, j) in m.depth"
            :key="`smd_${j}`"
            :title="d.title"
            :to="d.path"
            :active="isActive(d.path)"
            @click="drawer = false"
          />
        </v-list-group>

        <v-list-item
          v-else
          :prepend-icon="m.icon"
          :title="m.title"
          :to="m.path"
          :active="isActive(m.path)"
          @click="drawer = false"
        />
      </template>
    </v-list>
  </v-navigation-drawer>
</template>

<style scoped>
.topbar {
  background: rgba(18, 18, 18, 0.7) !important;
  backdrop-filter: saturate(140%) blur(8px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
.nav-btn {
  height: 40px;
  text-transform: none;
  border-radius: 10px;
  padding: 0 10px;
}
.nav-active {
  background: rgba(59, 130, 246, 0.15);
}
.min-w-48 {
  min-width: 12rem;
}
</style>
