<script setup lang="ts">
import {
  AppstoreOutlined,
  LinkOutlined,
  LogoutOutlined,
  RobotOutlined,
  SendOutlined,
  SettingOutlined,
} from '@ant-design/icons-vue'
import { computed } from 'vue'
import { RouterLink, RouterView, useRoute } from 'vue-router'

import { useDesktopRuntime } from '../composables/useDesktopRuntime'
import { useDesktopSession } from '../composables/useDesktopSession'
import { desktopMonitoringMediaCatalog, desktopPublishMediaCatalog } from '../lib/media-catalog'

const route = useRoute()
const { snapshot, error, refreshAccounts } = useDesktopRuntime()
const { session, logout } = useDesktopSession()

const accountAwareRoutes = new Set(['/media-platforms', '/ai-platforms'])

function handleNavClick(target: string) {
  if (accountAwareRoutes.has(target)) {
    void refreshAccounts()
  }
}

const navItems = computed(() => {
  const data = snapshot.value
  const accounts = data?.accounts ?? []
  const publishIDs = new Set(desktopPublishMediaCatalog.map((item) => item.id))
  const monitoringIDs = new Set(desktopMonitoringMediaCatalog.map((item) => item.id))

  return [
    {
      to: '/',
      title: '控制台',
      description: '运行总览、活动流和总体健康度',
      count: data?.summary.issuesOpen ?? 0,
      icon: AppstoreOutlined,
    },
    {
      to: '/publish-management',
      title: '发布管理',
      description: '查看待发布队列、历史发送结果，并对文章再次发送',
      count: data?.summary.queuedTasks ?? 0,
      icon: SendOutlined,
    },
    {
      to: '/media-platforms',
      title: '媒体账号',
      description: '发布媒体授权、多个账号绑定管理',
      count: accounts.filter((item) => publishIDs.has(item.platform)).length,
      icon: LinkOutlined,
    },
    {
      to: '/ai-platforms',
      title: 'AI 平台',
      description: 'AI 平台一平台一授权，按卡片查看状态与归属',
      count: accounts.filter((item) => monitoringIDs.has(item.platform)).length,
      icon: RobotOutlined,
    },
  ]
})

const operatorName = computed(() => {
  const user = session.value?.user
  return (
    user?.name?.trim() ||
    user?.phone?.trim() ||
    user?.email?.trim() ||
    '未命名操作员'
  )
})
const operatorEmail = computed(() => {
  const user = session.value?.user
  const email = user?.email?.trim()
  const phone = user?.phone?.trim()
  if (email && phone && email !== operatorName.value) {
    return email
  }
  return phone && phone !== operatorName.value ? phone : ''
})
const liveClientLabel = computed(() => snapshot.value?.clients[0]?.deviceName ?? null)
const clientLabel = computed(
  () =>
    liveClientLabel.value ?? session.value?.desktopClient?.device_name ?? '当前设备尚未注册 client',
)

function openSettingsWindow() {
  void window.desktopBridge.app.openSettingsWindow()
}
</script>

<template>
  <div class="app-shell">
    <div class="window-drag-bar" aria-hidden="true"></div>
    <aside class="sidebar">
      <div class="brand-block">
        <div class="brand-mark">
          <span class="brand-ring"></span>
          <span class="brand-core"></span>
        </div>
        <div>
          <p class="eyebrow">Workspace Cockpit</p>
          <h1>省心推</h1>
        </div>
      </div>

      <nav class="nav">
        <RouterLink
          v-for="item in navItems"
          :key="item.to"
          :to="item.to"
          class="nav-link"
          :class="{ active: route.path === item.to }"
          @click="handleNavClick(item.to)"
        >
          <div class="nav-copy">
            <component :is="item.icon" class="nav-icon" />
            <strong>{{ item.title }}</strong>
          </div>
          <span class="nav-count">{{ item.count }}</span>
        </RouterLink>
      </nav>

      <footer class="sidebar-footer">
        <section class="user-profile-panel">
          <div class="user-info-row">
            <div class="user-avatar">{{ operatorName.charAt(0).toUpperCase() }}</div>
            <div class="user-details">
              <strong>{{ operatorName }}</strong>
              <p>{{ operatorEmail }}</p>
            </div>
          </div>
          <div class="user-actions-row">
            <a-tooltip :title="clientLabel" placement="top">
              <div class="device-tag">
                <span class="status-dot"></span>
                <span class="device-name-text">{{ clientLabel }}</span>
              </div>
            </a-tooltip>
            <div class="action-cluster">
              <a-tooltip title="设置" placement="top">
                <button type="button" class="footer-icon-btn" @click="openSettingsWindow">
                  <SettingOutlined />
                </button>
              </a-tooltip>
              <a-tooltip title="退出登录" placement="top">
                <button
                  type="button"
                  class="footer-icon-btn footer-icon-btn--danger"
                  @click="logout"
                >
                  <LogoutOutlined />
                </button>
              </a-tooltip>
            </div>
          </div>
        </section>

        <div class="footer-bottom-row">
          <span class="version-label">Version</span>
          <strong class="version-value">{{ snapshot?.app.version ?? '0.1.0' }}</strong>
        </div>
        <p v-if="error" class="error-text">{{ error }}</p>
      </footer>
    </aside>

    <main class="content">
      <div class="content-dragbar" aria-hidden="true"></div>
      <RouterView />
    </main>
  </div>
</template>

<style scoped>
.app-shell {
  display: flex;
  height: 100vh;
  overflow: hidden;
  background: #f0f2f5;
  color: #1a1a1a;
  position: relative;
}

/* Real drag handle for the macOS hidden title bar — must be above content
   but only spans the empty zone behind the traffic lights. */
.window-drag-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 144px;
  height: 24px;
  z-index: 1000;
  -webkit-app-region: drag;
}

:global(html[data-platform='darwin']) .window-drag-bar {
  left: 80px;
  right: 0;
  height: 28px;
}

.app-shell :where(button, a, input, select, textarea, [role='button'], [role='link']) {
  -webkit-app-region: no-drag;
}

.sidebar {
  width: 320px;
  height: 100vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  padding: 24px;
  padding-top: 44px;
  border-right: 1px solid #e6edf5;
  background: #ffffff;
  flex-shrink: 0;
}

.brand-block {
  display: flex;
  gap: 16px;
  align-items: center;
  -webkit-app-region: drag;
}

.brand-mark {
  position: relative;
  width: 40px;
  height: 40px;
  display: grid;
  place-items: center;
}

.brand-ring,
.brand-core {
  position: absolute;
  border-radius: 50%;
}

.brand-ring {
  inset: 0;
  border: 1px solid #91caff;
  background: #e6f4ff;
}

.brand-core {
  width: 16px;
  height: 16px;
  background: #1677ff;
  box-shadow: 0 2px 6px rgba(22, 119, 255, 0.4);
}

.eyebrow {
  margin: 0 0 4px;
  color: #8c8c8c;
  font-size: 11px;
  letter-spacing: 0.1em;
  text-transform: uppercase;
}

h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #1a1a1a;
  line-height: 1.2;
}

.nav {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin: auto 0;
}

.nav-link {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  text-decoration: none;
  background: transparent;
  border: 1px solid transparent;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.nav-link:hover {
  background: #f8fafc;
}

.nav-link.active {
  background: #e6f4ff;
  border-color: #e6f4ff;
}

.nav-copy {
  display: flex;
  align-items: center;
  gap: 12px;
}

.nav-icon {
  font-size: 16px;
  color: #8c8c8c;
  transition: color 0.2s;
}

.nav-link:hover .nav-icon {
  color: #595959;
}

.nav-link.active .nav-icon {
  color: #1677ff;
}

.nav-copy strong {
  font-size: 14px;
  font-weight: 500;
  color: #4b5563;
}

.nav-link:hover .nav-copy strong {
  color: #1f2937;
}

.nav-link.active .nav-copy strong {
  color: #1677ff;
  font-weight: 600;
}

.nav-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 28px;
  height: 28px;
  padding: 0 8px;
  border-radius: 14px;
  background: #f0f0f0;
  color: #595959;
  font-size: 13px;
  font-weight: 600;
}

.nav-link.active .nav-count {
  background: #1677ff;
  color: #fff;
}

.sidebar-footer {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding-top: 16px;
}

.user-profile-panel {
  padding: 16px;
  border-radius: 16px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  box-shadow:
    0 1px 3px rgba(0, 0, 0, 0.02),
    0 2px 4px -2px rgba(0, 0, 0, 0.01);
  transition: all 0.2s ease;
}

.user-profile-panel:hover {
  border-color: #cbd5e1;
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.03),
    0 2px 4px -2px rgba(0, 0, 0, 0.02);
}

.user-info-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #0f172a;
  color: #ffffff;
  font-weight: 700;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-details {
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-details strong {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #0f172a;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
}

.user-details p {
  margin: 0;
  font-size: 12px;
  color: #64748b;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
}

.user-actions-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #e2e8f0;
  gap: 8px;
}

.device-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 500;
  color: #4b5563;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  min-width: 0;
}

.device-tag .status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #10b981;
  box-shadow: 0 0 0 2px #d1fae5;
  flex-shrink: 0;
}

.device-name-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-cluster {
  display: flex;
  align-items: center;
  gap: 6px;
}

.footer-icon-btn {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 15px;
  color: #94a3b8;
  background: transparent;
  border: 1px solid transparent;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
}

.footer-icon-btn:hover {
  background: #f1f5f9;
  color: #1677ff;
  border-color: #e2e8f0;
}

.footer-icon-btn.router-link-active {
  background: #e6f4ff;
  color: #1677ff;
  border-color: #e6f4ff;
}

.footer-icon-btn--danger:hover {
  background: #fef2f2;
  color: #ef4444;
  border-color: #fee2e2;
}

.footer-bottom-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 4px;
}

.version-label {
  color: #94a3b8;
  font-size: 12px;
  font-weight: 500;
}

.version-value {
  color: #475569;
  font-size: 13px;
  font-weight: 600;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}

.error-text {
  margin: 0;
  color: #ef4444;
  font-size: 13px;
}

.content {
  flex: 1;
  min-width: 0;
  height: 100vh;
  padding: 24px 32px;
  overflow-y: auto;
  position: relative;
}

.content-dragbar {
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  height: 24px;
  margin: -24px -32px 0;
  -webkit-app-region: drag;
  z-index: 5;
}

@media (max-width: 1080px) {
  .sidebar {
    width: 260px;
  }
}
</style>
