<template>
  <aside class="rail" :class="{ 'rail-collapsed': collapsed }" aria-label="主导航">
    <div class="rail-brand">
      <div class="brand-mark" aria-hidden="true">
        <img v-if="companyLogo" :src="companyLogo" alt="System Logo" class="custom-logo" />
        <svg v-else viewBox="0 0 36 36">
          <path d="M19.8 4.5c5.7 1.1 9.9 5.7 10.5 11.6-2.8-.9-5.5-.7-7.9.6-2.8 1.5-4.5 4.3-5.2 8.2-4.4-2.8-6.5-6.5-6.3-11.1.2-4.2 3.5-7.8 8.9-9.3Z" />
          <path d="M9 7.6c-3 3.5-4 7.3-2.9 11.2 1.2 4.2 4.6 7 10.1 8.5-2 1.8-4.6 2.6-7.6 2.3C5.1 26.7 3.5 23.1 3.7 19 4 14.4 5.7 10.6 9 7.6Z" />
        </svg>
      </div>
      <strong class="brand-name">{{ displayCompanyName }}</strong>
      <ElTooltip
        :content="collapseTooltipContent"
        placement="right"
        effect="light"
        :show-after="180"
        :hide-after="0"
        :offset="12"
        popper-class="rail-tooltip-popper"
      >
        <button
          class="rail-collapse-btn"
          type="button"
          :aria-label="collapseTooltipContent"
          :aria-expanded="!collapsed"
          @click="emit('toggle-collapse')"
        >
          <i :class="collapsed ? 'mdi mdi-chevron-right' : 'mdi mdi-chevron-left'"></i>
        </button>
      </ElTooltip>
    </div>

    <nav class="rail-nav" aria-label="功能导航">
      <ElTooltip
        v-for="item in decoratedNavItems"
        :key="item.id"
        :content="item.displayLabel"
        placement="right"
        effect="light"
        :disabled="!collapsed"
        :show-after="180"
        :hide-after="0"
        :offset="12"
        popper-class="rail-tooltip-popper"
      >
        <button
          class="nav-btn"
          :class="{ active: activeView === item.id }"
          type="button"
          @click="emit('navigate', item.id)"
        >
          <span class="nav-icon" v-html="item.icon"></span>
          <span class="nav-label">{{ item.displayLabel }}</span>
          <span v-if="item.hasNewMessage" class="nav-unread-dot" aria-hidden="true"></span>
          <span v-if="item.badge" class="nav-badge">{{ item.badge }}</span>
        </button>
      </ElTooltip>
    </nav>

    <div
      class="rail-user"
      @mouseenter="openCollapsedUserMenu"
      @mouseleave="closeCollapsedUserMenu"
      @focusin="openCollapsedUserMenu"
      @focusout="handleUserFocusOut"
    >
      <div v-if="!collapsed" class="user-menu" role="menu" aria-label="用户菜单">
        <button class="user-menu-item" type="button" @click="emit('logout')">
          <i class="mdi mdi-logout-variant"></i>
          <span>退出系统</span>
        </button>
      </div>

      <Teleport to="body">
        <div
          v-if="collapsed && userMenuOpen"
          class="rail-user-menu-floating"
          :style="userMenuStyle"
          role="menu"
          aria-label="用户菜单"
          @mouseenter="clearUserMenuCloseTimer"
          @mouseleave="closeCollapsedUserMenu"
        >
          <button class="user-menu-item" type="button" @click="handleLogout">
            <i class="mdi mdi-logout-variant"></i>
            <span>退出系统</span>
          </button>
        </div>
      </Teleport>

      <ElTooltip
        :content="userTooltipContent"
        placement="top"
        effect="light"
        :disabled="!collapsed || userMenuOpen"
        :show-after="180"
        :hide-after="0"
        :offset="10"
        popper-class="rail-tooltip-popper"
      >
        <div class="user-summary" tabindex="0" :aria-label="userTooltipContent">
          <span class="user-avatar">{{ displayUser.avatar }}</span>
          <span class="user-copy">
            <strong>{{ displayUser.name }}</strong>
            <span>{{ displayUser.role }}</span>
          </span>
          <i class="mdi mdi-chevron-up"></i>
        </div>
      </ElTooltip>
    </div>
  </aside>
</template>

<script setup>
import { ElTooltip } from 'element-plus'
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'

import { useDocumentCenterInbox } from '../../composables/useDocumentCenterInbox.js'

const props = defineProps({
  navItems: { type: Array, required: true },
  activeView: { type: String, required: true },
  companyName: {
    type: String,
    default: ''
  },
  companyLogo: {
    type: String,
    default: ''
  },
  currentUser: {
    type: Object,
    default: () => ({
      name: '系统管理员',
      role: '管理员',
      avatar: '管'
    })
  },
  collapsed: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['navigate', 'openChat', 'logout', 'toggle-collapse'])

const {
  hasUnread: documentInboxHasUnread,
  refreshDocumentInbox,
  startDocumentInboxPolling,
  stopDocumentInboxPolling
} = useDocumentCenterInbox()

const sidebarMeta = {
  overview: { label: '分析看板' },
  workbench: { label: '个人工作台' },
  documents: { label: '单据中心' },
  budget: { label: '预算中心' },
  policies: { label: '知识管理' },
  audit: { label: '规则中心' },
  digitalEmployees: { label: '数字员工' },
  logs: { label: '系统日志' },
  employees: { label: '员工管理' },
  settings: { label: '系统设置' }
}

const decoratedNavItems = computed(() =>
  props.navItems.map((item) => ({
    ...item,
    displayLabel: sidebarMeta[item.id]?.label ?? item.label,
    hasNewMessage: item.id === 'documents' ? documentInboxHasUnread.value : false,
    badge: sidebarMeta[item.id]?.badge
  }))
)

onMounted(() => {
  void refreshDocumentInbox()
  startDocumentInboxPolling()
})


const displayUser = computed(() => ({
  name: props.currentUser?.name || '系统管理员',
  role: props.currentUser?.role || '管理员',
  avatar: props.currentUser?.avatar || '管'
}))

const displayCompanyName = computed(() => props.companyName || '易财费控')
const collapseTooltipContent = computed(() => (props.collapsed ? '展开侧边栏' : '折叠侧边栏'))
const userTooltipContent = computed(() => [displayUser.value.name, displayUser.value.role].filter(Boolean).join(' · '))

const userMenuOpen = ref(false)
let userMenuCloseTimer = null
const userMenuPosition = reactive({
  top: 0,
  left: 0
})

const userMenuStyle = computed(() => ({
  top: `${userMenuPosition.top}px`,
  left: `${userMenuPosition.left}px`
}))

function resolveUserMenuAnchor(element) {
  return element?.querySelector?.('.user-summary') || element
}

function clearUserMenuCloseTimer() {
  if (userMenuCloseTimer) {
    clearTimeout(userMenuCloseTimer)
    userMenuCloseTimer = null
  }
}

function openCollapsedUserMenu(event) {
  if (!props.collapsed) {
    return
  }

  clearUserMenuCloseTimer()

  const anchor = resolveUserMenuAnchor(event?.currentTarget)
  if (!anchor?.getBoundingClientRect) {
    return
  }

  const rect = anchor.getBoundingClientRect()
  userMenuPosition.top = rect.top + rect.height / 2
  userMenuPosition.left = rect.right + 12
  userMenuOpen.value = true
}

function closeCollapsedUserMenu() {
  clearUserMenuCloseTimer()
  userMenuCloseTimer = setTimeout(() => {
    userMenuOpen.value = false
    userMenuCloseTimer = null
  }, 120)
}

function closeCollapsedUserMenuNow() {
  clearUserMenuCloseTimer()
  userMenuOpen.value = false
}

function handleUserFocusOut(event) {
  if (!props.collapsed) {
    return
  }

  const container = event.currentTarget
  const nextTarget = event.relatedTarget
  if (nextTarget && container?.contains(nextTarget)) {
    return
  }

  closeCollapsedUserMenuNow()
}

function handleLogout() {
  closeCollapsedUserMenuNow()
  emit('logout')
}

watch(
  () => props.collapsed,
  (isCollapsed) => {
    if (!isCollapsed) {
      closeCollapsedUserMenuNow()
    }
  }
)

onBeforeUnmount(() => {
  stopDocumentInboxPolling()
  closeCollapsedUserMenuNow()
})
</script>


<style scoped src="../../assets/styles/components/sidebar-rail.css"></style>
