<script setup lang="ts">
import { computed } from 'vue'
import {
  Activity, Bell, Bot, Boxes, Command, FileText,
  LayoutDashboard, ListTodo, LogOut, Settings,
  Shield, SlidersHorizontal, BookOpen,
  AlertTriangle, Calendar, Workflow,
} from '@lucide/vue'
import { RouterLink, useRouter } from 'vue-router'
import { useAuthStore } from '../../stores/auth'
import { useNotificationSnapshot } from '../../api/notifications'
import { initials } from '../../utils/format'

const props = defineProps<{
  activeView: string
  mobileNavOpen: boolean
  queuedTasks: number
  incidents: number
}>()

const emit = defineEmits<{
  navigate: [label: string]
}>()

const auth = useAuthStore()
const router = useRouter()
const { query: notificationQuery } = useNotificationSnapshot({ limit: 1 })
const unreadNotifications = computed(() => notificationQuery.data.value?.unreadCount ?? 0)

const ownerInitials = computed(() =>
  auth.user?.displayName ? initials(auth.user.displayName) : 'OW'
)

const navigationGroups = [
  {
    id: 'operations',
    label: 'Operations',
    items: [
      { label: 'Dashboard', route: '/dashboard', icon: LayoutDashboard },
      { label: 'Agents', route: '/agents', icon: Bot },
      { label: 'Projects', route: '/projects', icon: Boxes },
      { label: 'Task Board', route: '/tasks', icon: ListTodo },
      { label: 'Run Control', route: '/runs', icon: Workflow },
    ],
  },
  {
    id: 'knowledge',
    label: 'Knowledge',
    items: [
      { label: 'Memory', route: '/memory', icon: FileText },
      { label: 'Docs', route: '/docs', icon: BookOpen },
    ],
  },
  {
    id: 'infrastructure',
    label: 'Infrastructure',
    items: [
      { label: 'Models', route: '/models', icon: SlidersHorizontal },
      { label: 'Activity', route: '/activity', icon: Activity },
      { label: 'Calendar', route: '/calendar', icon: Calendar },
    ],
  },
  {
    id: 'governance',
    label: 'Governance',
    items: [
      { label: 'Security', route: '/security', icon: Shield },
      { label: 'Incidents', route: '/incidents', icon: AlertTriangle },
      { label: 'Notifications', route: '/notifications', icon: Bell },
    ],
  },
]

function onNavigate(label: string) {
  emit('navigate', label)
}

async function logout() {
  await auth.logout()
  await router.replace('/login')
}
</script>

<template>
  <aside :class="['sidebar', { open: mobileNavOpen }]" aria-label="Nexus navigation">
    <div class="brand">
      <div class="brand-mark"><Command :size="18" /></div>
      <div>
        <strong>NEXUS</strong>
        <span>Noveria Operations</span>
      </div>
    </div>

    <nav class="nav" aria-label="Primary">
      <div
        v-for="group in navigationGroups"
        :key="group.id"
        class="nav-group"
        role="group"
        :aria-labelledby="`legacy-nav-${group.id}`"
      >
        <span :id="`legacy-nav-${group.id}`" class="nav-group-label">{{ group.label }}</span>
        <RouterLink
          v-for="item in group.items"
          :key="item.label"
          class="nav-link"
          :to="item.route ?? '/dashboard'"
          :class="{ active: activeView === item.label }"
          :aria-current="activeView === item.label ? 'page' : undefined"
          @click="onNavigate(item.label)"
        >
          <component :is="item.icon" :size="17" />
          <span>{{ item.label }}</span>
          <i v-if="item.label === 'Task Board'">{{ queuedTasks }}</i>
          <i v-if="item.label === 'Incidents'">{{ incidents }}</i>
          <i v-if="item.label === 'Notifications' && Number(unreadNotifications) > 0" class="badge-red">{{ unreadNotifications }}</i>
        </RouterLink>
      </div>
    </nav>

    <div class="sidebar-bottom">
      <RouterLink
        to="/settings"
        class="sidebar-settings"
        :class="{ active: activeView === 'Settings' }"
        :aria-current="activeView === 'Settings' ? 'page' : undefined"
        @click="onNavigate('Settings')"
      ><Settings :size="17" /> Settings</RouterLink>
      <button class="owner" type="button" aria-label="Sign out" title="Sign out" @click="logout">
        <div class="avatar">{{ ownerInitials }}</div>
        <div><strong>{{ auth.user?.displayName ?? 'Owner' }}</strong><span>{{ auth.user?.role ?? 'owner' }}</span></div>
        <LogOut :size="15" />
      </button>
    </div>
  </aside>
</template>

<style scoped>
.sidebar {
  width: var(--sidebar-w);
  flex: 0 0 var(--sidebar-w);
  height: 100dvh;
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 2;
  background: linear-gradient(
    180deg,
    color-mix(in srgb, var(--space-2) 92%, transparent),
    color-mix(in srgb, var(--space-0) 92%, transparent)
  );
  border-right: 1px solid var(--line);
  backdrop-filter: blur(14px);
  flex-shrink: 0;
  padding: 0 12px;
}
.brand {
  display: flex;
  align-items: center;
  gap: 11px;
  padding: 18px 6px 16px;
}
.brand-mark {
  width: 38px;
  height: 38px;
  display: grid;
  place-items: center;
  border-radius: 11px;
  background: var(--grad);
  color: var(--tx-on-accent);
  box-shadow: var(--glow-purple);
}
.brand div strong {
  display: block;
  font-family: var(--font-display);
  font-size: 17px;
  line-height: 1;
  letter-spacing: .14em;
}
.brand div span {
  display: block;
  margin-top: 3px;
  color: var(--tx-3);
  font-size: 10.5px;
  letter-spacing: .05em;
}
.nav {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0;
  padding: 6px 0 12px;
  overflow-y: auto;
}
.nav-group {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.nav-group-label {
  display: block;
  padding: 14px 10px 6px;
  color: var(--tx-3);
  font-family: var(--font-body);
  font-size: 10px;
  font-weight: 700;
  letter-spacing: .18em;
  line-height: 1.2;
  text-transform: uppercase;
}
.nav-group:first-child .nav-group-label {
  padding-top: 6px;
}
.nav-link {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  min-height: 38px;
  padding: 8px 10px;
  border: 1px solid transparent;
  border-radius: 10px;
  background: transparent;
  color: var(--tx-2);
  font-size: 12px;
  text-align: left;
  text-decoration: none;
  cursor: pointer;
  transition: background .15s, border-color .15s, color .15s;
}
.nav-link:hover {
  background: color-mix(in srgb, var(--a-mid) 8%, transparent);
  color: var(--tx);
}
.nav-link.active {
  border-color: var(--line-2);
  background: var(--grad-soft);
  color: var(--tx);
  font-weight: 650;
}
.nav-link.active::before,
.sidebar-settings.active::before {
  content: '';
  position: absolute;
  left: -13px;
  width: 3px;
  height: 22px;
  border-radius: 0 999px 999px 0;
  background: var(--grad);
  box-shadow: var(--glow-purple);
}
.nav-link i {
  margin-left: auto;
  min-width: 22px;
  background: color-mix(in srgb, var(--a-mid) 14%, transparent);
  border: 1px solid var(--line);
  color: var(--tx);
  font-style: normal;
  font-family: var(--font-mono-v2);
  font-size: 11px;
  font-weight: 700;
  padding: 2px 6px;
  border-radius: 999px;
  line-height: 1.2;
  text-align: center;
}
.nav-link i.badge-red {
  border-color: var(--status-block-line);
  background: var(--status-block-bg);
  color: var(--st-block);
}
.sidebar-bottom {
  padding: 10px 0 12px;
  border-top: 1px solid var(--line);
}
.sidebar-settings,
.owner {
  position: relative;
  display: flex;
  align-items: center;
  gap: 9px;
  width: 100%;
  min-height: 38px;
  padding: 8px 10px;
  border: 1px solid transparent;
  border-radius: 10px;
  background: transparent;
  color: var(--tx-2);
  font-size: 12px;
  text-decoration: none;
  cursor: pointer;
  transition: background .15s, border-color .15s, color .15s;
}
.sidebar-settings:hover,
.owner:hover {
  background: color-mix(in srgb, var(--a-mid) 8%, transparent);
  color: var(--tx);
}
.sidebar-settings.active {
  border-color: var(--line-2);
  background: var(--grad-soft);
  color: var(--tx);
  font-weight: 650;
}
.owner {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 6px;
}
.owner div strong { display: block; font-size: 12px; }
.owner div span {
  display: block;
  margin-top: 1px;
  color: var(--tx-3);
  font-size: 11px;
  text-transform: capitalize;
}
.owner > svg:last-child { margin-left: auto; opacity: .4; transition: opacity .15s; }
.owner:hover > svg:last-child { opacity: 1; }
.avatar {
  width: 34px;
  height: 34px;
  border-radius: 10px;
  display: grid;
  place-items: center;
  background: var(--grad-soft);
  border: 1px solid var(--line-2);
  color: var(--tx);
  font-size: 12px;
  font-weight: 700;
}

@media (max-width: 900px) {
  .sidebar {
    position: fixed;
    inset: 0 auto 0 0;
    left: 0;
    z-index: 100;
    width: min(280px, calc(100vw - 28px));
    flex-basis: auto;
    transform: translateX(-100%);
    transition: transform .25s ease;
    box-shadow: var(--panel-shadow);
  }
  .sidebar.open { transform: translateX(0); }
}
</style>
