<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router'
import { currentUser, defaultRouteFor, isAdmin, logout } from './auth'

const route = useRoute()
const router = useRouter()
const navOpen = ref(false)
const sidebarCollapsed = ref(false)
const currentTitle = computed(() => (route.meta.title as string) || 'SupplyAgent')
const SIDEBAR_STORAGE_KEY = 'supply-agent-sidebar-collapsed'

const adminNavItems = [
  { to: '/', label: '供给总览', icon: '◫', admin: true },
  { to: '/demand-map', label: '全局需求地图', icon: '⌁', admin: false },
  { to: '/video-discovery', label: '需求汇总', icon: '▷', admin: false },
  { to: '/pipeline-runs', label: '定时任务', icon: '◷', admin: true },
  { to: '/llm-billing', label: 'LLM 费用', icon: '＄', admin: true },
  { to: '/demand-process', label: 'Agent 审计', icon: '◎', admin: true },
  { to: '/find-agent-framework', label: '寻找 Agent 框架', icon: '⌬', admin: false },
  { to: '/find-agent-records', label: '找视频记录', icon: '⌕', admin: false },
  { to: '/admin/users', label: '用户管理', icon: '◇', admin: true },
]
const navItems = computed(() =>
  adminNavItems.filter((item) => isAdmin.value || !item.admin),
)
const appHome = computed(() =>
  currentUser.value ? defaultRouteFor(currentUser.value) : '/login',
)

async function signOut() {
  await logout()
  navOpen.value = false
  await router.replace('/login')
}

onMounted(() => {
  sidebarCollapsed.value = window.localStorage.getItem(SIDEBAR_STORAGE_KEY) === 'true'
})

watch(sidebarCollapsed, (collapsed) => {
  window.localStorage.setItem(SIDEBAR_STORAGE_KEY, String(collapsed))
})
</script>

<template>
  <div v-if="route.meta.layout === 'auth'" class="auth-shell">
    <RouterView />
  </div>
  <div v-else class="app-shell">
    <aside class="sidebar" :class="{ open: navOpen, collapsed: sidebarCollapsed }">
      <RouterLink class="brand" :to="appHome" @click="navOpen = false">
        <span class="brand-mark">S</span>
        <span class="brand-copy">
          <strong>SupplyAgent</strong>
          <small>CONTENT INTELLIGENCE</small>
        </span>
      </RouterLink>

      <nav class="side-nav">
        <span class="nav-section">工作台</span>
        <RouterLink
          v-for="item in navItems"
          :key="item.to"
          :to="item.to"
          :class="{ active: route.path === item.to }"
          active-class=""
          exact-active-class=""
          :title="sidebarCollapsed ? item.label : undefined"
          @click="navOpen = false"
        >
          <span class="nav-icon">{{ item.icon }}</span>
          <span class="nav-label">{{ item.label }}</span>
          <span class="nav-arrow">›</span>
        </RouterLink>
      </nav>

      <div class="sidebar-info">
        <div class="system-badge">
          <span class="pulse" />
          <span>
            <strong>系统服务</strong>
            <small>FastAPI · 8080</small>
          </span>
        </div>
        <p>将需求信号转化为可执行的内容供给。</p>
      </div>

      <button
        class="collapse-button"
        type="button"
        :aria-label="sidebarCollapsed ? '展开导航栏' : '收起导航栏'"
        :aria-expanded="!sidebarCollapsed"
        :title="sidebarCollapsed ? '展开导航栏' : '收起导航栏'"
        @click="sidebarCollapsed = !sidebarCollapsed"
      >
        {{ sidebarCollapsed ? '›' : '‹' }}
      </button>
    </aside>

    <div class="shell-content">
      <header class="topbar">
        <button class="menu-button" type="button" aria-label="打开导航" @click="navOpen = !navOpen">
          ☰
        </button>
        <div>
          <span class="breadcrumb">SUPPLYAGENT /</span>
          <strong>{{ currentTitle }}</strong>
        </div>
        <div class="topbar-meta">
          <span class="environment"><i /> PRODUCTION</span>
          <span class="clock">Asia / Shanghai</span>
          <button class="account-button" type="button" title="退出登录" @click="signOut">
            <span>{{ currentUser?.display_name?.slice(0, 1) || 'U' }}</span>
            <span class="account-copy">
              <strong>{{ currentUser?.display_name || currentUser?.username }}</strong>
              <small>{{ isAdmin ? '管理员 · 点击退出' : '普通用户 · 点击退出' }}</small>
            </span>
          </button>
        </div>
      </header>

      <main class="main">
        <RouterView />
      </main>
    </div>
    <button
      v-if="navOpen"
      class="nav-backdrop"
      type="button"
      aria-label="关闭导航"
      @click="navOpen = false"
    />
  </div>
</template>

<style scoped>
.auth-shell {
  min-height: 100vh;
}

.app-shell {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background: #f5f6f8;
}

.sidebar {
  position: relative;
  display: flex;
  width: 222px;
  height: 100%;
  padding: 20px 14px 18px;
  flex-direction: column;
  flex-shrink: 0;
  border-right: 1px solid #e4e6eb;
  background: rgba(250, 250, 251, 0.96);
  backdrop-filter: blur(12px);
  transition: width 0.22s ease, padding 0.22s ease;
}

.brand {
  display: flex;
  align-items: center;
  gap: 11px;
  padding: 4px 8px 24px;
  color: #202739;
  text-decoration: none;
}

.brand-mark {
  display: grid;
  width: 35px;
  height: 35px;
  place-items: center;
  border-radius: 11px;
  background: linear-gradient(145deg, #6a6adb, #4f4fbf);
  color: #fff;
  font-size: 17px;
  font-weight: 800;
  box-shadow: 0 9px 20px rgba(91, 91, 214, 0.25);
}

.brand-copy strong,
.brand-copy small {
  display: block;
}

.brand-copy strong {
  font-size: 14px;
  letter-spacing: -0.02em;
}

.brand-copy small {
  margin-top: 2px;
  color: #9a9fad;
  font-size: 7px;
  font-weight: 800;
  letter-spacing: 0.14em;
}

.side-nav {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nav-section {
  margin: 0 10px 8px;
  color: #a1a6b1;
  font-size: 9px;
  font-weight: 700;
  letter-spacing: 0.12em;
}

.side-nav a {
  display: grid;
  min-height: 42px;
  grid-template-columns: 27px 1fr auto;
  align-items: center;
  padding: 0 10px;
  border-radius: 9px;
  color: #666e7e;
  font-size: 11px;
  font-weight: 600;
  text-decoration: none;
  transition: background 0.16s, color 0.16s;
}

.side-nav a:hover {
  background: #f0f1f5;
  color: #343b4b;
}

.side-nav a.active {
  background: #ececff;
  color: #5555cb;
}

.nav-icon {
  color: #8d94a3;
  font-size: 16px;
}

.side-nav a.active .nav-icon {
  color: #5b5bd6;
}

.nav-arrow {
  color: #abb0bb;
  font-size: 17px;
}

.collapse-button {
  position: absolute;
  z-index: 2;
  top: 72px;
  right: -13px;
  display: grid;
  width: 26px;
  height: 26px;
  place-items: center;
  padding: 0 0 2px;
  border: 1px solid #dfe2e8;
  border-radius: 8px;
  background: #fff;
  color: #7f8695;
  font-size: 17px;
  line-height: 1;
  box-shadow: 0 5px 15px rgba(36, 43, 62, 0.09);
  cursor: pointer;
  transition: border-color 0.16s, color 0.16s, transform 0.16s;
}

.collapse-button:hover {
  border-color: #7777d8;
  color: #5b5bd6;
  transform: scale(1.05);
}

.sidebar-info {
  margin-top: auto;
  padding: 14px 10px 4px;
  border-top: 1px solid #e8eaee;
}

.system-badge {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pulse {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #2ab282;
  box-shadow: 0 0 0 4px rgba(42, 178, 130, 0.1);
}

.system-badge strong,
.system-badge small {
  display: block;
}

.system-badge strong {
  color: #555c6c;
  font-size: 10px;
}

.system-badge small {
  margin-top: 2px;
  color: #a0a6b1;
  font-size: 8px;
}

.sidebar-info p {
  margin: 12px 0 0;
  color: #a2a7b2;
  font-size: 9px;
  line-height: 1.6;
}

.shell-content {
  display: flex;
  min-width: 0;
  flex: 1;
  flex-direction: column;
}

.topbar {
  display: flex;
  height: 56px;
  align-items: center;
  justify-content: space-between;
  padding: 0 26px;
  flex-shrink: 0;
  border-bottom: 1px solid #e6e8ed;
  background: rgba(255, 255, 255, 0.82);
  backdrop-filter: blur(12px);
}

.topbar > div:first-of-type {
  display: flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb {
  color: #a1a6b2;
  font-size: 9px;
  font-weight: 800;
  letter-spacing: 0.1em;
}

.topbar strong {
  color: #535a69;
  font-size: 10px;
}

.topbar-meta {
  display: flex;
  align-items: center;
  gap: 17px;
  color: #9ba1ad;
  font-size: 8px;
  font-weight: 700;
  letter-spacing: 0.08em;
}

.account-button {
  display: flex;
  height: 38px;
  align-items: center;
  gap: 8px;
  padding: 0 10px 0 6px;
  border: 1px solid #e1e4ea;
  border-radius: 10px;
  background: #fff;
  color: #545c6b;
  cursor: pointer;
}

.account-button > span:first-child {
  display: grid;
  width: 26px;
  height: 26px;
  place-items: center;
  border-radius: 8px;
  background: #ececff;
  color: #5b5cc9;
  font-size: 11px;
  font-weight: 800;
}

.account-copy {
  text-align: left;
}

.account-copy strong,
.account-copy small {
  display: block;
}

.account-copy strong {
  color: #444c5d;
  font-size: 10px;
}

.account-copy small {
  margin-top: 1px;
  color: #8c93a0;
  font-size: 8px;
}

.environment {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.environment i {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #2ab282;
}

.menu-button {
  display: none;
  width: 34px;
  height: 34px;
  border: 1px solid #e0e3e9;
  border-radius: 8px;
  background: #fff;
  color: #5f6675;
  cursor: pointer;
}

.main {
  min-height: 0;
  flex: 1;
  padding: 22px 24px 28px;
  overflow: auto;
}

.nav-backdrop {
  display: none;
}

@media (min-width: 821px) {
  .sidebar.collapsed {
    width: 72px;
    padding-right: 10px;
    padding-left: 10px;
  }

  .sidebar.collapsed .brand {
    justify-content: center;
    padding-right: 0;
    padding-left: 0;
  }

  .sidebar.collapsed .brand-copy,
  .sidebar.collapsed .nav-section,
  .sidebar.collapsed .nav-label,
  .sidebar.collapsed .nav-arrow,
  .sidebar.collapsed .system-badge > span:last-child,
  .sidebar.collapsed .sidebar-info p {
    display: none;
  }

  .sidebar.collapsed .side-nav a {
    display: grid;
    grid-template-columns: 1fr;
    justify-items: center;
    padding: 0;
  }

  .sidebar.collapsed .nav-icon {
    font-size: 18px;
  }

  .sidebar.collapsed .sidebar-info {
    display: flex;
    justify-content: center;
    padding-right: 0;
    padding-left: 0;
  }

  .sidebar.collapsed .system-badge {
    justify-content: center;
  }
}

@media (max-width: 820px) {
  .sidebar {
    position: fixed;
    z-index: 20;
    top: 0;
    left: 0;
    transform: translateX(-100%);
    transition: transform 0.2s ease;
  }

  .sidebar.open {
    transform: translateX(0);
  }

  .menu-button {
    display: block;
  }

  .collapse-button {
    display: none;
  }

  .topbar {
    justify-content: flex-start;
    gap: 14px;
    padding: 0 14px;
  }

  .topbar-meta {
    margin-left: auto;
  }

  .clock {
    display: none;
  }

  .environment,
  .account-copy {
    display: none;
  }

  .account-button {
    padding: 0 5px;
  }

  .main {
    padding: 14px;
  }

  .nav-backdrop {
    position: fixed;
    z-index: 15;
    inset: 0;
    display: block;
    border: 0;
    background: rgba(21, 27, 40, 0.35);
    backdrop-filter: blur(2px);
  }
}

/* Readability and contrast */
.brand-copy small {
  color: #626b7a;
  font-size: 10px;
}

.nav-section {
  color: #667085;
  font-size: 11px;
}

.side-nav a {
  color: #4b5565;
  font-size: 13px;
}

.nav-icon,
.nav-arrow {
  color: #687386;
}

.system-badge strong {
  color: #374151;
  font-size: 12px;
}

.system-badge small,
.sidebar-info p {
  color: #687386;
  font-size: 11px;
}

.breadcrumb {
  color: #667085;
  font-size: 11px;
}

.topbar strong {
  color: #374151;
  font-size: 12px;
}

.topbar-meta {
  color: #667085;
  font-size: 10px;
}
</style>
