<script setup lang="ts">
/**
 * B-17 fix: Added "Projects" and "Members" navigation items to sidebar.
 * Projects shows a collapsible sub-menu listing projects from the API.
 * Members links to the member list page (admin/manager only).
 */
import { computed, ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { NTag, NTooltip } from 'naive-ui';
import { useAuthStore } from '@/stores/auth';
import { useDashboardStore } from '@/stores/dashboard';
import { getAdminProjectsApi } from '@/api/admin';

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const dashStore = useDashboardStore();

// B-17: Track whether the Projects sub-menu is expanded
const projectsExpanded = ref(false);
const projectList = ref<Array<{ projectId: string; name: string; identifier: string; bizSystem: string | null }>>([]);

async function loadProjectList() {
  try {
    const res = await getAdminProjectsApi();
    const list = res.data.data || [];
    projectList.value = list.map((p: any) => ({
      projectId: p.id,
      name: p.name,
      identifier: p.identifier || '',
      bizSystem: p.bizSystem || null,
    }));
  } catch {
    // Silently fail
  }
}

// 按产品线分组
const BIZ_GROUPS: Array<{ key: 'airhubs' | 'airflow' | 'aircore' | 'uncategorized'; label: string; color: string }> = [
  { key: 'airhubs',       label: 'airhubs · 硬件与潮玩业务线',    color: '#0D9668' },
  { key: 'airflow',       label: 'airflow · 内容生成与效能线',    color: '#3B5998' },
  { key: 'aircore',       label: 'aircore · 底层技术基座',        color: '#D4920A' },
  { key: 'uncategorized', label: '未分类',                       color: '#6B7280' },
];

// 各分组的展开状态(默认全部展开,localStorage 持久化)
const groupOpenState = ref<Record<string, boolean>>(
  (() => {
    try { return JSON.parse(localStorage.getItem('sidebar-group-open') || '{}'); }
    catch { return {}; }
  })()
);

function isGroupOpen(key: string): boolean {
  return groupOpenState.value[key] !== false;  // 默认 true(undefined → 展开)
}

function toggleGroup(key: string) {
  groupOpenState.value = { ...groupOpenState.value, [key]: !isGroupOpen(key) };
  try { localStorage.setItem('sidebar-group-open', JSON.stringify(groupOpenState.value)); } catch {}
}

const projectGroups = computed(() => {
  const map: Record<string, typeof projectList.value> = {
    airhubs: [], airflow: [], aircore: [], uncategorized: [],
  };
  for (const p of projectList.value) {
    const k = p.bizSystem || 'uncategorized';
    if (!map[k]) map[k] = [];
    map[k].push(p);
  }
  return BIZ_GROUPS
    .map(g => ({ ...g, projects: map[g.key] }))
    .filter(g => g.projects.length > 0);
});

onMounted(loadProjectList);

// 路由变化时刷新项目列表（如从项目列表页返回时）
watch(() => route.path, (newPath) => {
  if (newPath === '/projects') loadProjectList();
});

interface NavItem {
  label: string;
  key: string;
  icon: string;
  /** If true, this item has a sub-menu (projects) */
  hasSubmenu?: boolean;
}

const menuOptions = computed(() => {
  const role = authStore.user?.role;
  const items: NavItem[] = [
    { label: '团队总览', key: '/', icon: 'grid' },
    // B-17: Projects nav item
    { label: '项目', key: '/projects', icon: 'folder', hasSubmenu: true },
    { label: 'OKR', key: '/okr', icon: 'target' },
  ];

  if (role === 'admin' || role === 'manager' || role === 'developer') {
    items.push({ label: 'Git 活动', key: '/git', icon: 'git-branch' });
  }

  // ROI 罗盘:仅 admin
  if (role === 'admin') {
    items.push({ label: 'ROI 罗盘', key: '/roi', icon: 'trending-up' });
  }

  // B-17: Members nav item (admin/manager only)
  if (role === 'admin' || role === 'manager') {
    items.push({ label: '成员', key: '/members', icon: 'users' });
  }

  if (role === 'admin') {
    items.push({ label: '管理后台', key: '/admin', icon: 'settings' });
  }

  return items;
});

const activeKey = computed(() => {
  if (route.path === '/') return '/';
  if (route.path === '/projects') return '/projects';
  if (route.path.startsWith('/projects/')) return '/projects';
  if (route.path === '/members') return '/members';
  if (route.path.startsWith('/members/')) return '/members';
  if (route.path.startsWith('/okr')) return '/okr';
  if (route.path.startsWith('/git')) return '/git';
  if (route.path.startsWith('/roi')) return '/roi';
  if (route.path.startsWith('/admin')) return '/admin';
  return '/';
});

function handleMenuSelect(item: NavItem) {
  if (item.hasSubmenu) {
    // Toggle sub-menu expansion; also navigate to the projects list
    projectsExpanded.value = !projectsExpanded.value;
    router.push(item.key);
  } else {
    router.push(item.key);
  }

  // On mobile, close sidebar after navigation (unless expanding sub-menu)
  if (dashStore.isMobile && !item.hasSubmenu) {
    dashStore.closeMobileSidebar();
  }
}

function handleProjectSelect(projectId: string) {
  router.push(`/projects/${projectId}`);
  if (dashStore.isMobile) {
    dashStore.closeMobileSidebar();
  }
}

const roleTagType = computed(() => {
  const role = authStore.user?.role;
  if (role === 'admin') return 'info';
  if (role === 'manager') return 'success';
  if (role === 'viewer') return 'warning';
  return 'default';
});
</script>

<template>
  <!-- Mobile hamburger button: visible only on mobile -->
  <button
    v-if="dashStore.isMobile"
    class="hamburger-btn"
    aria-label="打开侧边栏菜单"
    @click="dashStore.toggleSidebar"
  >
    <span class="hamburger-icon">&#9776;</span>
  </button>

  <aside
    class="sidebar"
    :class="{
      collapsed: !dashStore.isMobile && dashStore.sidebarCollapsed,
      'mobile-hidden': dashStore.isMobile && !dashStore.mobileSidebarOpen,
      'mobile-open': dashStore.isMobile && dashStore.mobileSidebarOpen,
    }"
  >
    <div class="sidebar-header">
      <div class="logo">
        <span class="logo-icon">DP</span>
        <span class="logo-text" v-if="!dashStore.sidebarCollapsed || dashStore.isMobile">DevPerf</span>
      </div>
      <button v-if="dashStore.isMobile" class="close-btn" @click="dashStore.closeMobileSidebar">&times;</button>
      <span v-else class="collapse-toggle" @click="dashStore.toggleSidebar" :title="dashStore.sidebarCollapsed ? '展开' : '收起'">
        {{ dashStore.sidebarCollapsed ? '»' : '«' }}
      </span>
    </div>

    <nav class="sidebar-nav">
      <template v-for="item in menuOptions" :key="item.key">
        <div
          class="nav-item"
          :class="{ active: activeKey === item.key }"
          @click="handleMenuSelect(item)"
        >
          <span class="nav-label" v-if="!dashStore.sidebarCollapsed || dashStore.isMobile">
            {{ item.label }}
            <!-- B-17: Show expand/collapse indicator for Projects -->
            <span v-if="item.hasSubmenu && (!dashStore.sidebarCollapsed || dashStore.isMobile)" class="submenu-arrow">
              {{ projectsExpanded ? '&#9660;' : '&#9654;' }}
            </span>
          </span>
          <NTooltip v-else placement="right">
            <template #trigger>
              <span class="nav-icon-only">{{ item.label[0] }}</span>
            </template>
            {{ item.label }}
          </NTooltip>
        </div>

        <!-- B-17: Projects sub-menu, grouped by bizSystem -->
        <div
          v-if="item.hasSubmenu && projectsExpanded && (!dashStore.sidebarCollapsed || dashStore.isMobile)"
          class="submenu"
        >
          <template v-for="group in projectGroups" :key="group.key">
            <div
              class="submenu-group-title"
              :class="{ 'group-collapsed': !isGroupOpen(group.key) }"
              :style="{ borderLeftColor: group.color }"
              @click="toggleGroup(group.key)"
            >
              <span class="group-dot" :style="{ background: group.color }"></span>
              <span class="group-arrow">{{ isGroupOpen(group.key) ? '▾' : '▸' }}</span>
              {{ group.label }}
              <span class="group-count">{{ group.projects.length }}</span>
            </div>
            <template v-if="isGroupOpen(group.key)">
              <div
                v-for="proj in group.projects"
                :key="proj.projectId"
                class="submenu-item"
                :class="{ active: route.path === `/projects/${proj.projectId}` }"
                @click="handleProjectSelect(proj.projectId)"
              >
                <span class="submenu-label">{{ proj.name }}</span>
              </div>
            </template>
          </template>
          <div v-if="!projectList.length" class="submenu-item submenu-empty">
            暂无项目
          </div>
        </div>
      </template>
    </nav>

    <div class="sidebar-footer">
      <div class="user-row" v-if="!dashStore.sidebarCollapsed || dashStore.isMobile">
        <div class="user-info">
          <span class="user-name">{{ authStore.user?.displayName }}</span>
          <span class="user-role">{{ authStore.user?.role }}</span>
        </div>
        <span class="logout-link" @click="authStore.logout" title="退出登录">退出</span>
      </div>
      <div v-else class="user-row-mini">
        <NTooltip placement="right">
          <template #trigger>
            <span class="user-initial">{{ authStore.user?.displayName?.[0] || '?' }}</span>
          </template>
          {{ authStore.user?.displayName }} · {{ authStore.user?.role }}
        </NTooltip>
      </div>
    </div>
  </aside>
</template>

<style scoped>
.sidebar {
  width: var(--sidebar-width);
  height: 100vh;
  background: var(--color-bg-sidebar);
  color: var(--color-text-onDark);
  display: flex;
  flex-direction: column;
  position: fixed;
  left: 0;
  top: 0;
  transition: width var(--duration-collapse) var(--ease-out),
              transform var(--duration-medium) var(--ease-out);
  z-index: var(--z-sticky);
  overflow: hidden;
  overflow-y: auto;
  border-right: 1px solid oklch(0.25 0.012 230);
}

.sidebar.collapsed {
  width: var(--sidebar-collapsed-width);
}

/* Mobile: sidebar is off-screen by default */
.sidebar.mobile-hidden {
  transform: translateX(-100%);
  width: var(--sidebar-width);
}

/* Mobile: sidebar slides in from the left */
.sidebar.mobile-open {
  transform: translateX(0);
  width: var(--sidebar-width);
  z-index: calc(var(--z-sticky) + 2);
}

.sidebar-header {
  padding: var(--space-4);
  border-bottom: 1px solid rgba(255,255,255,0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.collapse-toggle {
  font-size: 14px;
  color: #6B7280;
  cursor: pointer;
  padding: 4px 6px;
  border-radius: 4px;
  transition: color 0.15s, background 0.15s;
  user-select: none;
}
.collapse-toggle:hover { color: #E5E7EB; background: rgba(255,255,255,0.08); }

.logo {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.logo-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, var(--color-accent) 0%, var(--color-accent-hover) 100%);
  border-radius: var(--radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: var(--font-display);
  font-weight: var(--weight-semibold);
  font-size: 13px;
  color: var(--color-text-onDark);
  flex-shrink: 0;
  letter-spacing: -0.02em;
}

.logo-text {
  font-family: var(--font-display);
  font-weight: var(--weight-semibold);
  font-size: var(--text-md);
  letter-spacing: -0.01em;
  white-space: nowrap;
}

.sidebar-nav {
  flex: 1;
  padding: var(--space-4) var(--space-2);
  overflow-y: auto;
}

.nav-item {
  padding: var(--space-2) var(--space-4);
  margin-bottom: 2px;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: background var(--duration-fast) var(--ease-out),
              color var(--duration-fast) var(--ease-out);
  position: relative;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--text-sm);
  font-weight: var(--weight-medium);
  color: oklch(0.75 0.010 220);
}

.nav-item:hover {
  background: oklch(0.24 0.014 230);
  color: var(--color-text-onDark);
}

.nav-item.active {
  background: oklch(0.26 0.018 220);
  color: var(--color-accent);
  border-left: 2px solid var(--color-accent);
}

.nav-label {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  width: 100%;
}

/* B-17: Sub-menu arrow indicator */
.submenu-arrow {
  font-size: 10px;
  margin-left: auto;
  opacity: 0.6;
}

/* B-17: Projects sub-menu */
.submenu {
  padding-left: var(--space-4);
  margin-bottom: var(--space-2);
}

.submenu-item {
  padding: var(--space-2) var(--space-4);
  font-size: 12px;
  color: #9CA3AF;
  border-radius: var(--radius-btn);
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: background var(--duration-hover) var(--ease-default), color var(--duration-hover);
}

.submenu-item:hover {
  background: rgba(255,255,255,0.06);
  color: #E5E7EB;
}

.submenu-item.active {
  color: #E5E7EB;
  background: rgba(59,89,152,0.2);
}

.submenu-empty {
  cursor: default;
  font-style: italic;
  opacity: 0.5;
}

.submenu-label {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 产品线分组标题 */
.submenu-group-title {
  padding: 8px 12px 4px;
  margin-top: 4px;
  font-size: 11px;
  font-weight: 600;
  color: #9CA3AF;
  letter-spacing: 0.3px;
  border-left: 2px solid transparent;
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  user-select: none;
  transition: color 0.15s, background 0.15s;
  border-radius: 4px;
}
.submenu-group-title:hover {
  color: #E5E7EB;
  background: rgba(255,255,255,0.04);
}
.submenu-group-title.group-collapsed { opacity: 0.7; }
.group-arrow {
  font-size: 10px;
  width: 10px;
  display: inline-flex;
  justify-content: center;
  color: #6B7280;
}
.group-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  flex-shrink: 0;
}
.group-count {
  margin-left: auto;
  font-size: 10px;
  color: #6B7280;
  background: rgba(255,255,255,0.06);
  padding: 1px 6px;
  border-radius: 8px;
  font-weight: normal;
}

.nav-icon-only {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 24px;
  font-weight: 600;
}

.sidebar-footer {
  padding: var(--space-3) var(--space-4);
  border-top: 1px solid rgba(255,255,255,0.08);
}

.user-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.user-name {
  font-size: 13px;
  font-weight: 500;
  color: #E5E7EB;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-role {
  font-size: 11px;
  color: #6B7280;
}

.logout-link {
  font-size: 12px;
  color: #6B7280;
  cursor: pointer;
  padding: 3px 8px;
  border-radius: 4px;
  transition: color 0.15s, background 0.15s;
  flex-shrink: 0;
}
.logout-link:hover {
  color: #DC2626;
  background: rgba(220,38,38,0.1);
}

.user-row-mini {
  display: flex;
  justify-content: center;
}

.user-initial {
  width: 28px; height: 28px;
  display: flex; align-items: center; justify-content: center;
  background: rgba(59,89,152,0.3); border-radius: 50%;
  font-size: 12px; font-weight: 600; color: #E5E7EB; cursor: pointer;
}

/* Hamburger button - positioned fixed on mobile */
.hamburger-btn {
  position: fixed;
  top: 12px;
  left: 12px;
  z-index: var(--z-sticky);
  width: 40px;
  height: 40px;
  border: none;
  border-radius: var(--radius-btn);
  background: var(--color-bg-card);
  box-shadow: 0 2px 8px rgba(0,0,0,0.12);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.hamburger-icon {
  font-size: 20px;
  color: var(--color-text-primary);
  line-height: 1;
}

/* Close button inside mobile sidebar header */
.close-btn {
  background: none;
  border: none;
  color: #9CA3AF;
  font-size: 24px;
  cursor: pointer;
  padding: 0 4px;
  line-height: 1;
}

.close-btn:hover {
  color: #E5E7EB;
}
</style>
