<template>
  <aside class="ai-rail" :class="{ 'rail-collapsed': collapsed }" aria-label="AI模式导航">
    <section class="ai-rail-brand" aria-label="当前产品标识">
      <span class="ai-brand-logo" aria-hidden="true">
        <img v-if="brandLogo" :src="brandLogo" alt="" />
        <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>
      </span>
      <span class="ai-brand-copy">
        <strong>{{ displayBrandName }}</strong>
        <small>AI 财务工作台</small>
      </span>
    </section>

    <section class="ai-rail-section ai-rail-quick" aria-label="对话操作">
      <template v-for="action in quickActions" :key="action.event">
        <label
          v-if="action.event === 'search' && conversationSearchOpen"
          class="ai-conversation-search"
        >
          <i class="mdi mdi-magnify" aria-hidden="true"></i>
          <input
            ref="conversationSearchInputRef"
            v-model="conversationSearchQuery"
            type="search"
            placeholder="搜索对话标题"
            @keydown.esc.prevent="closeConversationSearch"
          />
          <button
            type="button"
            :aria-label="conversationSearchQuery ? '清空对话搜索' : '关闭对话搜索'"
            @click="handleConversationSearchAuxAction"
          >
            <i class="mdi mdi-close" aria-hidden="true"></i>
          </button>
        </label>
        <button
          v-else
          type="button"
          class="ai-quick-btn"
          :class="{ primary: action.primary }"
          @click="handleQuickAction(action.event)"
        >
          <span class="ai-quick-icon" aria-hidden="true">
            <svg
              class="ai-sidebar-tabler-icon"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path
                v-for="(path, pathIndex) in action.iconPaths"
                :key="`${action.event}-${pathIndex}`"
                :d="path"
              />
            </svg>
          </span>
          <span>{{ action.label }}</span>
        </button>
      </template>
    </section>

    <div class="ai-rail-divider"></div>

    <nav class="ai-rail-section ai-rail-nav" aria-label="业务导航">
      <div class="ai-nav-list">
        <button
          v-for="item in businessNavItems"
          :key="item.id"
          type="button"
          class="ai-nav-btn"
          :class="{ active: activeView === item.id }"
          :aria-current="activeView === item.id ? 'page' : undefined"
          @mouseenter="emit('prefetch-view', item.id)"
          @focus="emit('prefetch-view', item.id)"
          @click="emit('navigate', item.id)"
        >
          <span class="ai-nav-icon" aria-hidden="true">
            <svg
              class="ai-sidebar-tabler-icon"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <path
                v-for="(path, pathIndex) in item.aiIconPaths"
                :key="`${item.id}-${pathIndex}`"
                :d="path"
              />
            </svg>
          </span>
          <span class="ai-nav-copy">
            <strong>{{ item.displayLabel }}</strong>
          </span>
        </button>
      </div>
    </nav>

    <div class="ai-rail-divider"></div>

    <section class="ai-rail-section ai-rail-recents" aria-label="最近对话">
      <h2 class="ai-section-heading">最近对话</h2>
      <div class="ai-recents-list">
        <div
          v-for="recent in filteredConversationHistory"
          :key="recent.id"
          role="button"
          tabindex="0"
          class="ai-recent-item"
          :class="{ active: activeConversationId === recent.id }"
          :aria-current="activeConversationId === recent.id ? 'true' : undefined"
          @click="handleRecentClick(recent)"
          @dblclick.stop="startEditingRecentTitle(recent)"
          @keydown.enter.prevent="emit('open-recent', recent)"
          @keydown.space.prevent="emit('open-recent', recent)"
        >
          <span class="ai-recent-main">
            <input
              v-if="editingConversationId === recent.id"
              ref="editingTitleInputRef"
              v-model="editingConversationTitle"
              class="ai-recent-title-input"
              type="text"
              aria-label="编辑对话标题"
              @click.stop
              @dblclick.stop
              @keydown.enter.prevent="commitRecentTitleEdit(recent)"
              @keydown.esc.prevent="cancelRecentTitleEdit"
              @blur="commitRecentTitleEdit(recent)"
            />
            <span v-else class="ai-recent-title">{{ recent.title }}</span>
            <span class="ai-recent-desc">{{ recent.desc }}</span>
          </span>
          <span class="ai-recent-time">{{ recent.time }}</span>
        </div>
        <p v-if="!normalizedConversationHistory.length" class="ai-recents-empty">暂无历史对话</p>
        <p v-else-if="!filteredConversationHistory.length" class="ai-recents-empty">没有匹配的对话</p>
      </div>
    </section>

    <section class="ai-rail-user" aria-label="当前用户">
      <div class="ai-user-avatar" aria-hidden="true">{{ displayUser.avatar }}</div>
      <div class="ai-user-copy">
        <strong>{{ displayUser.name }}</strong>
        <span>{{ displayUser.subtitle }}</span>
      </div>
      <div class="ai-user-actions" aria-label="用户操作">
        <button type="button" class="ai-user-action ai-user-logout" aria-label="退出系统" @click="emit('logout')">
          <i class="mdi mdi-logout-variant" aria-hidden="true"></i>
        </button>
      </div>
    </section>
  </aside>
</template>

<script setup>
import { computed, nextTick, onBeforeUnmount, ref } from 'vue'

import { resolveAiSidebarBusinessViewIds } from '../../utils/aiSidebarBusinessAccess.js'

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

const emit = defineEmits(['navigate', 'new-chat', 'open-recent', 'rename-conversation', 'logout', 'prefetch-view'])
const conversationSearchOpen = ref(false)
const conversationSearchQuery = ref('')
const conversationSearchInputRef = ref(null)
const editingConversationId = ref('')
const editingConversationTitle = ref('')
const editingTitleInputRef = ref(null)
let recentClickTimer = null

const tablerIconPaths = {
  plus: [
    'M12 5l0 14',
    'M5 12l14 0'
  ],
  search: [
    'M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0',
    'M21 21l-6 -6'
  ],
  fileText: [
    'M14 3v4a1 1 0 0 0 1 1h4',
    'M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2',
    'M9 9l1 0',
    'M9 13l6 0',
    'M9 17l6 0'
  ],
  folder: [
    'M5 4h4l3 3h7a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-11a2 2 0 0 1 2 -2'
  ],
  book2: [
    'M19 4v16h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12',
    'M19 16h-12a2 2 0 0 0 -2 2',
    'M9 8h6'
  ],
  chartLine: [
    'M4 19l16 0',
    'M4 15l4 -6l4 2l4 -5l4 4'
  ],
  chartDonut: [
    'M10 3.2a9 9 0 1 0 10.8 10.8a1 1 0 0 0 -1 -1h-6.8a2 2 0 0 1 -2 -2v-6.8a1 1 0 0 0 -1 -1',
    'M15 3.5a9 9 0 0 1 5.5 5.5h-4.5a1 1 0 0 1 -1 -1v-4.5'
  ],
  shieldCheck: [
    'M11.46 20.846a12 12 0 0 1 -7.46 -10.846v-4l8 -3l8 3v4c0 1.122 -.154 2.203 -.441 3.226',
    'M15 19l2 2l4 -4'
  ],
  robot: [
    'M7 7h10a2 2 0 0 1 2 2v7a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-7a2 2 0 0 1 2 -2',
    'M9 11l.01 0',
    'M15 11l.01 0',
    'M9 15h6',
    'M12 7v-4'
  ],
  users: [
    'M9 7m-4 0a4 4 0 1 0 8 0a4 4 0 1 0 -8 0',
    'M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2',
    'M16 3.13a4 4 0 0 1 0 7.75',
    'M21 21v-2a4 4 0 0 0 -3 -3.85'
  ],
  sliders: [
    'M4 6h16',
    'M4 12h10',
    'M4 18h14',
    'M8 6v.01',
    'M14 12v.01',
    'M18 18v.01'
  ],
  circle: [
    'M12 12m-8 0a8 8 0 1 0 16 0a8 8 0 1 0 -16 0'
  ]
}

const quickActions = [
  {
    label: '新建对话',
    iconPaths: tablerIconPaths.plus,
    event: 'new-chat',
    primary: true
  },
  {
    label: '查询对话',
    iconPaths: tablerIconPaths.search,
    event: 'search'
  }
]

const displayBrandName = computed(() => String(props.brandName || '易财费控').trim() || '易财费控')

const sidebarMeta = {
  overview: { label: '分析看板', iconPaths: tablerIconPaths.chartLine },
  documents: { label: '单据中心', iconPaths: tablerIconPaths.fileText },
  receiptFolder: { label: '票据夹', iconPaths: tablerIconPaths.folder },
  budget: { label: '预算管理', iconPaths: tablerIconPaths.chartDonut },
  policies: { label: '财务政策', iconPaths: tablerIconPaths.book2 },
  audit: { label: '规则管理', iconPaths: tablerIconPaths.shieldCheck },
  digitalEmployees: { label: '数字员工', iconPaths: tablerIconPaths.robot },
  employees: { label: '员工管理', iconPaths: tablerIconPaths.users },
  settings: { label: '系统设置', iconPaths: tablerIconPaths.sliders }
}

const aiBusinessViewIds = computed(() => new Set(resolveAiSidebarBusinessViewIds(props.currentUser)))

const businessNavItems = computed(() =>
  props.navItems
    .filter((item) => aiBusinessViewIds.value.has(item.id))
    .map((item) => ({
      ...item,
      displayLabel: sidebarMeta[item.id]?.label ?? item.label,
      aiIconPaths: sidebarMeta[item.id]?.iconPaths ?? tablerIconPaths.circle
    }))
)

const normalizedConversationHistory = computed(() => (
  Array.isArray(props.conversationHistory) ? props.conversationHistory : []
))

const filteredConversationHistory = computed(() => {
  const query = conversationSearchQuery.value.trim().toLowerCase()
  if (!query) {
    return normalizedConversationHistory.value
  }

  return normalizedConversationHistory.value.filter((recent) => (
    String(recent.title || '').toLowerCase().includes(query)
  ))
})

const displayUser = computed(() => ({
  name: props.currentUser?.name || '系统管理员',
  subtitle:
    props.currentUser?.email ||
    (props.currentUser?.username && props.currentUser?.username !== props.currentUser?.name ? props.currentUser.username : '') ||
    props.currentUser?.role ||
    '审批负责人',
  avatar: props.currentUser?.avatar || String(props.currentUser?.name || '管').trim().slice(0, 1) || '管'
}))

function handleQuickAction(event) {
  if (event === 'new-chat') {
    emit('new-chat')
    return
  }
  if (event === 'search') {
    openConversationSearch()
  }
}

function openConversationSearch() {
  conversationSearchOpen.value = true
  void nextTick(() => {
    resolveInputElement(conversationSearchInputRef.value)?.focus()
  })
}

function closeConversationSearch() {
  conversationSearchOpen.value = false
  conversationSearchQuery.value = ''
}

function handleConversationSearchAuxAction() {
  if (conversationSearchQuery.value) {
    conversationSearchQuery.value = ''
    return
  }

  closeConversationSearch()
}

function startEditingRecentTitle(recent = {}) {
  clearRecentClickTimer()
  editingConversationId.value = String(recent.id || '').trim()
  editingConversationTitle.value = String(recent.title || '').trim()
  void nextTick(() => {
    const input = resolveInputElement(editingTitleInputRef.value)
    input?.focus()
    input?.select()
  })
}

function handleRecentClick(recent = {}) {
  clearRecentClickTimer()
  recentClickTimer = window.setTimeout(() => {
    emit('open-recent', recent)
    recentClickTimer = null
  }, 180)
}

function clearRecentClickTimer() {
  if (recentClickTimer) {
    window.clearTimeout(recentClickTimer)
    recentClickTimer = null
  }
}

function cancelRecentTitleEdit() {
  editingConversationId.value = ''
  editingConversationTitle.value = ''
}

function commitRecentTitleEdit(recent = {}) {
  if (editingConversationId.value !== String(recent.id || '').trim()) {
    return
  }

  const title = editingConversationTitle.value.trim()
  cancelRecentTitleEdit()
  if (!title || title === String(recent.title || '').trim()) {
    return
  }

  emit('rename-conversation', {
    id: recent.id,
    title
  })
}

function resolveInputElement(value) {
  return Array.isArray(value) ? value[0] : value
}

onBeforeUnmount(() => {
  clearRecentClickTimer()
})

</script>

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