<template>
  <!-- ═══ 对话侧边栏(抽自 AiChat.vue 第一批,零行为变更) ═══ -->
  <transition name="sidebar-slide">
    <div
      v-if="store.state.sidebarOpen"
      class="ai-conv-sidebar"
      :style="{ '--sidebar-width': store.state.sidebarWidth + 'px' }"
    >
      <!-- 侧栏右边缘拖拽条(UX-2025-16):col-resize,拖动 mousemove 改 sidebarWidth,mouseup 持久化 -->
      <div
        class="ai-sidebar-resize-handle"
        :title="t('aiChat.sidebarResizeHint')"
        @mousedown.prevent="onResizeStart"
      />
      <div class="ai-conv-sidebar-header">
        <span class="ai-conv-sidebar-title">{{ t('aiChat.sidebarTitle') }}</span>
        <button class="ai-btn-icon" @click="emit('confirm-new-conversation')" :title="t('aiChat.newConversation')">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        </button>
      </div>
      <!-- UX-06 §3.1: 对话搜索框(v-model 双绑 store.searchQuery;Ctrl+K 聚焦) -->
      <div class="ai-conv-search">
        <svg class="ai-conv-search-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
        <input
          ref="searchInputRef"
          v-model="store.state.searchQuery"
          class="ai-conv-search-input"
          :placeholder="t('aiChat.searchPlaceholder')"
          :title="t('aiChat.searchShortcutHint')"
          type="text"
        />
        <kbd class="ai-conv-search-kbd">{{ t('aiChat.searchShortcutHint') }}</kbd>
      </div>
      <div class="ai-conv-list">
        <!-- UX-06 §3.1: 搜索态(searchResults 非 null)→ 平铺,活跃+归档全量按 updated_at DESC -->
        <template v-if="searchResults">
          <div
            v-for="conv in searchResults"
            :key="'s-' + conv.id"
            class="ai-conv-item"
            :class="{
              'ai-conv-item--active': conv.id === store.state.activeConversationId,
              'ai-conv-item--archived': conv.archived,
              'ai-conv-item--pinned': conv.pinned,
            }"
            @click="onSelectSearchResult(conv.id)"
          >
            <div class="ai-conv-item-main">
              <span class="ai-conv-item-title" :title="conv.title || ''">
                {{ conv.title || t('aiChat.newConversation') }}
                <span v-if="store.isGenerating(conv.id)" class="ai-conv-gen-dot" :title="t('aiChat.generating')"></span>
              </span>
              <span class="ai-conv-item-time">{{ formatRelative(conv.updated_at) }}</span>
            </div>
            <div class="ai-conv-item-actions">
              <div class="ai-conv-item-more">
                <button class="ai-conv-item-act" @click.stop="toggleActionsMenu(conv.id)" :title="t('aiChat.moreActions')">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>
                </button>
                <div v-if="actionsOpenId === conv.id" class="ai-conv-actions-menu">
                  <button class="ai-conv-actions-opt" @click.stop="store.setPinnedConversation(conv.id, !conv.pinned); closeActionsMenu()">
                    <svg width="12" height="12" viewBox="0 0 24 24" :fill="conv.pinned ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5"/><path d="M9 10.76a2 2 0 01-1.11 1.79l-1.78.9A2 2 0 005 15.24V16a1 1 0 001 1h12a1 1 0 001-1v-.76a2 2 0 00-1.11-1.79l-1.78-.9A2 2 0 0115 10.76V7a1 1 0 011-1 2 2 0 002-2V3H6v1a2 2 0 002 2 1 1 0 011 1z"/></svg>
                    {{ conv.pinned ? t('aiChat.unpinConversation') : t('aiChat.pinConversation') }}
                  </button>
                  <button class="ai-conv-actions-opt" @click.stop="store.archiveConversation(conv.id, !conv.archived); closeActionsMenu()">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="5" rx="1"/><path d="M4 9v9a2 2 0 002 2h12a2 2 0 002-2V9"/><line x1="10" y1="13" x2="14" y2="13"/></svg>
                    {{ conv.archived ? t('aiChat.unarchive') : t('aiChat.archive') }}
                  </button>
                  <button class="ai-conv-actions-opt ai-conv-actions-opt--danger" @click.stop="emit('confirm-delete', conv.id); closeActionsMenu()">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    {{ t('common.delete') }}
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div v-if="searchResults.length === 0" class="ai-conv-empty">
            {{ t('aiChat.searchEmpty') }}
          </div>
        </template>

        <!-- 非搜索态:原时间分组(活跃) + 归档分组 -->
        <template v-else>
          <!-- 活跃对话:按 今天/昨天/更早 分组 -->
          <template v-for="group in groupedActive" :key="'g-' + group.key">
            <div
              class="ai-conv-group-title ai-conv-group-title--fold"
              @click="store.toggleGroupFold(group.key)"
            >
              <span class="ai-conv-group-arrow" :class="{ 'is-folded': store.state.foldedGroups[group.key] }">▸</span>
              {{ group.label }}
              <span class="ai-conv-group-count">({{ group.items.length }})</span>
            </div>
            <div
              v-if="group.key === 'today' && !group.items.length"
              v-show="!store.state.foldedGroups[group.key]"
              class="ai-conv-group-empty"
            >{{ t('aiChat.groupEmpty') }}</div>
            <div
              v-for="conv in group.items"
              v-show="!store.state.foldedGroups[group.key]"
              :key="conv.id"
              :ref="(el) => setItemEl(conv.id, el)"
              class="ai-conv-item"
              :class="{ 'ai-conv-item--active': conv.id === store.state.activeConversationId, 'ai-conv-item--pinned': conv.pinned }"
              @click="store.switchConversation(conv.id)"
            >
              <div class="ai-conv-item-main">
                <input
                  v-if="editingConvId === conv.id"
                  :ref="setEditEl"
                  v-model="editText"
                  class="ai-conv-item-edit"
                  @keyup.enter="commitRename(conv.id)"
                  @keyup.esc="cancelRename"
                  @blur="commitRename(conv.id)"
                  @click.stop
                />
                <span
                  v-else
                  class="ai-conv-item-title"
                  :class="{ 'ai-conv-item-title--flash': titleFlash && conv.id === store.state.activeConversationId }"
                  @dblclick.stop="startRename(conv)"
                  :title="conv.title || t('aiChat.doubleClickToRename')"
                >
                  {{ conv.title || t('aiChat.newConversation') }}
                  <!-- UX-2025-20 §7.4:AI 生成标题标识小图标(标题非空非占位时显示) -->
                  <svg
                    v-if="conv.title && titleFlash && conv.id === store.state.activeConversationId"
                    class="ai-conv-item-title-badge"
                    width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"
                  ><polyline points="20 6 9 17 4 12"/></svg>
                  <!-- F-09: 多会话并发生成指示器(后台/当前会话生成中均显脉冲点,多会话可同时显示) -->
                  <span v-if="store.isGenerating(conv.id)" class="ai-conv-gen-dot" :title="t('aiChat.generating')"></span>
                </span>
                <span class="ai-conv-item-time">{{ formatRelative(conv.updated_at) }}</span>
              </div>
              <div class="ai-conv-item-actions">
                <div class="ai-conv-item-more">
                  <button class="ai-conv-item-act" @click.stop="toggleActionsMenu(conv.id)" :title="t('aiChat.moreActions')">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>
                  </button>
                  <div v-if="actionsOpenId === conv.id" class="ai-conv-actions-menu">
                    <button class="ai-conv-actions-opt" @click.stop="store.setPinnedConversation(conv.id, !conv.pinned); closeActionsMenu()">
                      <svg width="12" height="12" viewBox="0 0 24 24" :fill="conv.pinned ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5"/><path d="M9 10.76a2 2 0 01-1.11 1.79l-1.78.9A2 2 0 005 15.24V16a1 1 0 001 1h12a1 1 0 001-1v-.76a2 2 0 00-1.11-1.79l-1.78-.9A2 2 0 0115 10.76V7a1 1 0 011-1 2 2 0 002-2V3H6v1a2 2 0 002 2 1 1 0 011 1z"/></svg>
                      {{ conv.pinned ? t('aiChat.unpinConversation') : t('aiChat.pinConversation') }}
                    </button>
                    <button class="ai-conv-actions-opt" @click.stop="store.archiveConversation(conv.id, true); closeActionsMenu()">
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="5" rx="1"/><path d="M4 9v9a2 2 0 002 2h12a2 2 0 002-2V9"/><line x1="10" y1="13" x2="14" y2="13"/></svg>
                      {{ t('aiChat.archive') }}
                    </button>
                    <button class="ai-conv-actions-opt ai-conv-actions-opt--danger" @click.stop="emit('confirm-delete', conv.id); closeActionsMenu()">
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                      {{ t('common.delete') }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <!-- 归档分组(可折叠) -->
          <template v-if="archivedConvs.length">
            <div class="ai-conv-group-title ai-conv-group-title--fold" @click="store.toggleArchivedFold()">
              <span class="ai-conv-group-arrow" :class="{ 'is-folded': store.state.archivedCollapsed }">▸</span>
              {{ t('aiChat.archivedCount', { n: archivedConvs.length }) }}
            </div>
            <div
              v-for="conv in archivedConvs"
              v-show="!store.state.archivedCollapsed"
              :key="'a-' + conv.id"
              :ref="(el) => setItemEl(conv.id, el)"
              class="ai-conv-item ai-conv-item--archived"
              :class="{ 'ai-conv-item--active': conv.id === store.state.activeConversationId, 'ai-conv-item--pinned': conv.pinned }"
              @click="store.switchConversation(conv.id)"
            >
              <div class="ai-conv-item-main">
                <span class="ai-conv-item-title" :title="conv.title || ''">
                  {{ conv.title || t('aiChat.newConversation') }}
                  <span v-if="store.isGenerating(conv.id)" class="ai-conv-gen-dot" :title="t('aiChat.generating')"></span>
                </span>
                <span class="ai-conv-item-time">{{ formatRelative(conv.updated_at) }}</span>
              </div>
              <div class="ai-conv-item-actions">
                <div class="ai-conv-item-more">
                  <button class="ai-conv-item-act" @click.stop="toggleActionsMenu(conv.id)" :title="t('aiChat.moreActions')">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>
                  </button>
                  <div v-if="actionsOpenId === conv.id" class="ai-conv-actions-menu">
                    <button class="ai-conv-actions-opt" @click.stop="store.setPinnedConversation(conv.id, !conv.pinned); closeActionsMenu()">
                      <svg width="12" height="12" viewBox="0 0 24 24" :fill="conv.pinned ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5"/><path d="M9 10.76a2 2 0 01-1.11 1.79l-1.78.9A2 2 0 005 15.24V16a1 1 0 001 1h12a1 1 0 001-1v-.76a2 2 0 00-1.11-1.79l-1.78-.9A2 2 0 0115 10.76V7a1 1 0 011-1 2 2 0 002-2V3H6v1a2 2 0 002 2 1 1 0 011 1z"/></svg>
                      {{ conv.pinned ? t('aiChat.unpinConversation') : t('aiChat.pinConversation') }}
                    </button>
                    <button class="ai-conv-actions-opt" @click.stop="store.archiveConversation(conv.id, false); closeActionsMenu()">
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="5" rx="1"/><path d="M4 9v9a2 2 0 002 2h12a2 2 0 002-2V9"/><line x1="12" y1="13" x2="12" y2="17"/><polyline points="10 15 12 13 14 15"/></svg>
                      {{ t('aiChat.unarchive') }}
                    </button>
                    <button class="ai-conv-actions-opt ai-conv-actions-opt--danger" @click.stop="emit('confirm-delete', conv.id); closeActionsMenu()">
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                      {{ t('common.delete') }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </template>

          <div v-if="store.state.conversations.length === 0" class="ai-conv-empty">
            {{ t('aiChat.emptyConversation') }}
          </div>
        </template>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
/**
 * 对话侧边栏 — 抽自 AiChat.vue 第一批重构(零行为变更)。
 *
 * 设计:
 * - store 共享(useAiStore 全局单例),子组件直接 useAiStore 读写 store.state/mutations,
 *   与父组件 AiChat 等价(策略:store 共享则两边都用 useXxxStore,不走 props 传 store)。
 * - 跨组件事件走 emit:
 *   - `confirm-delete`(id):删除需弹 ConfirmDialog,而 ConfirmDialog 由父渲染 +
 *     confirmDialog 实例归父所有(useConfirm 每次调用返回独立 ref,非全局单例),
 *     故删除确认交父处理。父调原 confirmDeleteConversation(id)。
 *   - `confirm-new-conversation`:新建对话(F-09 决策e 直接新建,旧后台继续不中断),交父 confirmNewConversation。
 * - 父 Ctrl+K 全局快捷键聚焦搜索框:经 defineExpose({ focusSearch }) 供父调,
 *   父侧 ref 替代原 searchInputRef(零行为变更)。
 *
 * 本组件自管的纯侧栏态:titleFlash/重命名/更多操作菜单/侧栏拖拽/搜索结果/时间分组。
 * 样式:零 scoped style(沿用 AiChat.vue 全局/父级样式,样式后续批下沉)。
 */
import { ref, computed, nextTick, watch, onMounted, onBeforeUnmount, type ComponentPublicInstance } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAiStore } from '../../stores/ai'
import { formatRelative } from '../../utils/time'
import type { AiConversationSummary } from '../../api/types'

const emit = defineEmits<{
  /** 删除对话(需二次确认),父调 confirmDeleteConversation(id) */
  (e: 'confirm-delete', id: string): void
  /** 新建对话(F-09 决策e 直接新建,旧后台继续不中断),父调 confirmNewConversation() */
  (e: 'confirm-new-conversation'): void
}>()

const { t } = useI18n()
const store = useAiStore()

// ── 标题生成淡入(UX-2025-20 §7.4):监听当前对话标题从空→非空触发 ──
const titleFlash = ref(false)
let _titleFlashTimer: ReturnType<typeof setTimeout> | null = null
const activeConv = computed(() =>
  store.state.conversations.find(c => c.id === store.state.activeConversationId) || null,
)
watch(
  () => activeConv.value?.title,
  (newTitle, oldTitle) => {
    if (!newTitle) return
    if (oldTitle && oldTitle === newTitle) return
    if (oldTitle) return
    titleFlash.value = true
    if (_titleFlashTimer) clearTimeout(_titleFlashTimer)
    _titleFlashTimer = setTimeout(() => { titleFlash.value = false }, 320)
  },
)

// ── 对话项 inline 重命名 ──
const editingConvId = ref<string | null>(null)
const editText = ref('')
let editEl: HTMLInputElement | null = null
function setEditEl(el: Element | { $el?: Element } | null): void {
  editEl = (el as HTMLInputElement) || null
}

// UX-06 §3.1: 对话搜索框引用(Ctrl+K 聚焦用)
const searchInputRef = ref<HTMLInputElement>()

/** 父 Ctrl+K 快捷键调用:聚焦搜索框(等价原 searchInputRef.value?.focus()) */
function focusSearch(): void {
  nextTick(() => searchInputRef.value?.focus())
}

function startRename(conv: { id: string; title: string | null }) {
  editingConvId.value = conv.id
  editText.value = conv.title || ''
  nextTick(() => {
    editEl?.focus()
    editEl?.select()
  })
}

async function commitRename(id: string) {
  const title = editText.value.trim()
  if (title && editingConvId.value === id) {
    await store.renameConversation(id, title)
  }
  editingConvId.value = null
}

function cancelRename() {
  editingConvId.value = null
}

// ── 会话项「更多」操作菜单(置顶/归档/删除)──
const actionsOpenId = ref<string | null>(null)

function toggleActionsMenu(id: string) {
  actionsOpenId.value = actionsOpenId.value === id ? null : id
}

function closeActionsMenu() {
  actionsOpenId.value = null
}

// 点击外部关闭更多操作菜单
function onActionsOutsideClick(e: MouseEvent) {
  if (!actionsOpenId.value) return
  const target = e.target as HTMLElement | null
  if (target?.closest('.ai-conv-item-more')) return
  actionsOpenId.value = null
}

/**
 * UX-260617-23:搜索结果点击切对话后清空 searchQuery,退出搜索模式回原时间分组视图。
 * M3:命中项可能在折叠的时间分组或折叠的归档分组内,选中态不可见。切回分组视图后展开所在分组
 * 并 scrollIntoView,确保选中项立即可见(原仅切 searchQuery,选中项落在折叠组里看不到高亮)。
 */
function onSelectSearchResult(id: string) {
  void store.switchConversation(id)
  store.state.searchQuery = ''
  // nextTick 后视图已切回分组态;ensureVisible 展开所在组 + 滚动定位
  void nextTick(() => ensureActiveVisible())
}

// ── M3:活跃会话项 DOM ref 收集(id → el),用于展开折叠组后 scrollIntoView ──
// Vue 3 函数 ref:每项 :ref="(el) => setItemEl(id, el)"。卸载时 el 为 null,删 key 防 Map 泄漏。
const itemEls = new Map<string, Element>()
function setItemEl(id: string, el: Element | ComponentPublicInstance | null): void {
  if (!el) {
    itemEls.delete(id)
    return
  }
  // 组件实例取 $el,但本项是普通 div(el 即 Element)
  itemEls.set(id, el as Element)
}

/**
 * M3:确保当前活跃会话在分组视图可见。若它落在折叠的时间分组(今天/昨天/更早)或折叠的归档分组,
 * 展开该组让 v-show 渲染出来,再 scrollIntoView。用于搜索点选、切对话后选中态不被折叠吞掉。
 */
function ensureActiveVisible(): void {
  const id = store.state.activeConversationId
  if (!id) return
  const conv = store.state.conversations.find(c => c.id === id)
  if (!conv) return
  // 先按归档态/时间桶决定应展开哪个组折叠态
  if (conv.archived) {
    if (store.state.archivedCollapsed) store.state.archivedCollapsed = false
  } else {
    const bucket = timeBucket(conv.updated_at)
    if (store.state.foldedGroups[bucket]) store.state.foldedGroups[bucket] = false
  }
  // 折叠态翻转后 v-show 需一帧才渲染,再 nextTick 取 el 滚动
  void nextTick(() => {
    const el = itemEls.get(id)
    if (el) {
      ;(el as HTMLElement).scrollIntoView({ block: 'nearest', behavior: 'smooth' })
    }
  })
}

// ── 对话分组:今天 / 昨天 / 更早 ──
const bucketLabels = computed<Record<string, string>>(() => ({
  today: t('aiChat.today'),
  yesterday: t('aiChat.yesterday'),
  earlier: t('aiChat.earlier'),
}))

function timeBucket(ts: string): 'today' | 'yesterday' | 'earlier' {
  const t = parseInt(ts, 10)
  if (!Number.isFinite(t)) return 'earlier'
  const d = new Date(t)
  const now = new Date()
  const sameDay = d.getFullYear() === now.getFullYear()
    && d.getMonth() === now.getMonth()
    && d.getDate() === now.getDate()
  if (sameDay) return 'today'
  const yest = new Date(now)
  yest.setDate(now.getDate() - 1)
  if (d.getFullYear() === yest.getFullYear()
    && d.getMonth() === yest.getMonth()
    && d.getDate() === yest.getDate()) return 'yesterday'
  return 'earlier'
}

const groupedActive = computed(() => {
  const map = new Map<string, AiConversationSummary[]>()
  for (const c of store.state.conversations) {
    if (c.archived) continue
    const b = timeBucket(c.updated_at)
    if (!map.has(b)) map.set(b, [])
    map.get(b)!.push(c)
  }
  for (const items of map.values()) {
    items.sort((a, b) => Number(b.pinned ? 1 : 0) - Number(a.pinned ? 1 : 0)
      || Number(b.updated_at) - Number(a.updated_at))
  }
  const groups: { key: string; label: string; items: AiConversationSummary[] }[] = []
  for (const key of ['today', 'yesterday', 'earlier']) {
    const items = map.get(key) || []
    if (key === 'today' || items.length) groups.push({ key, label: bucketLabels.value[key], items })
  }
  return groups
})

const archivedConvs = computed(() =>
  store.state.conversations
    .filter(c => c.archived)
    .sort((a, b) => Number(b.pinned ? 1 : 0) - Number(a.pinned ? 1 : 0)
      || Number(b.updated_at) - Number(a.updated_at)),
)

const searchResults = computed<AiConversationSummary[] | null>(
  () => store.filteredConversations.value,
)

// ── UX-2025-16: 侧栏宽度拖拽 ──
const resizeState = { startX: 0, startWidth: 0 }
function onResizeMove(e: MouseEvent) {
  store.setSidebarWidth(resizeState.startWidth + (e.clientX - resizeState.startX))
}
function onResizeEnd() {
  document.removeEventListener('mousemove', onResizeMove)
  document.removeEventListener('mouseup', onResizeEnd)
  document.body.classList.remove('ai-sidebar-resizing')
  store.persistUiState()
}
function onResizeStart(e: MouseEvent) {
  resizeState.startX = e.clientX
  resizeState.startWidth = store.state.sidebarWidth
  document.body.classList.add('ai-sidebar-resizing')
  document.addEventListener('mousemove', onResizeMove)
  document.addEventListener('mouseup', onResizeEnd)
}

onMounted(() => {
  // 点击外部关闭更多操作菜单
  document.addEventListener('click', onActionsOutsideClick)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', onActionsOutsideClick)
  // UX-2025-16:拖拽中途卸载兜底摘临时 document listener(原 AiChat 同段迁移)
  document.removeEventListener('mousemove', onResizeMove)
  document.removeEventListener('mouseup', onResizeEnd)
  document.body.classList.remove('ai-sidebar-resizing')
  // UX-2025-20:释放标题淡入计时器
  if (_titleFlashTimer) { clearTimeout(_titleFlashTimer); _titleFlashTimer = null }
})

defineExpose({
  /** 聚焦搜索框(父 Ctrl+K 快捷键调,等价原 searchInputRef.value?.focus()) */
  focusSearch,
})
</script>

<!-- ═══ ConversationSidebar scoped 样式(第一批抽离遗漏修复: 从 AiChat.vue <style scoped> 迁移,
     零视觉变更。原 AiChat scoped 不渗透子组件根,导致侧栏元素失配 → 本组件自持样式。
     CSS 变量(--df-*)由根级 global.css 提供,共享同一份。.ai-btn-icon 共享按钮抽 components.css 全局。) ═══ -->
<style scoped>
/* ═══ 对话侧边栏 ═══ */
/* 宽度由 CSS 变量驱动(UX-2025-16 拖拽)::style 绑 --sidebar-width,不直接绑 width,
   这样 sidebar-slide 过渡的 width:0(enter-from/leave-to)能正常覆盖,折叠/展开动画不破 */
.ai-conv-sidebar {
  position: relative;
  width: var(--sidebar-width, 200px);
  min-width: var(--sidebar-width, 200px);
  border-right: 0.5px solid var(--df-border);
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--df-bg);
}
/* UX-2025-16:右边缘 2px 拖拽条。hover/active 显高亮;拖拽中 body.ai-sidebar-resizing 全局锁 cursor 防抖 */
.ai-sidebar-resize-handle {
  position: absolute;
  top: 0;
  right: -1px; /* 跨过 0.5px border-right,确保命中区不被 border 遮挡 */
  width: 4px; /* 命中区 4px(视觉 2px 由 background 控制),易抓取 */
  height: 100%;
  cursor: col-resize;
  z-index: 5;
  background: transparent;
  transition: background 0.15s var(--df-ease);
}
.ai-sidebar-resize-handle:hover {
  background: var(--df-accent, #4f8cff);
  opacity: 0.5;
}
/* 拖拽中全局锁 cursor + 禁选中文本(挂在 body 上,跨元素生效) */
body.ai-sidebar-resizing,
body.ai-sidebar-resizing * {
  cursor: col-resize !important;
  user-select: none !important;
}
.ai-conv-sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 10px;
  border-bottom: 0.5px solid var(--df-border);
}
.ai-conv-sidebar-title {
  font-size: 12px;
  font-weight: 500;
  color: var(--df-text);
}

/* UX-06 §3.1: 对话搜索框(紧贴 header 下,样式跟随周围输入控件) */
.ai-conv-search {
  position: relative;
  display: flex;
  align-items: center;
  padding: 6px 10px;
  border-bottom: 0.5px solid var(--df-border);
}
.ai-conv-search-icon {
  flex: none;
  color: var(--df-text-dim);
  margin-right: 6px;
}
.ai-conv-search-input {
  flex: 1;
  min-width: 0;
  border: none;
  outline: none;
  background: transparent;
  font-size: 12px;
  color: var(--df-text);
}
.ai-conv-search-input::placeholder {
  color: var(--df-text-dim);
}
.ai-conv-search-kbd {
  flex: none;
  font-family: inherit;
  font-size: 10px;
  color: var(--df-text-dim);
  border: 0.5px solid var(--df-border);
  border-radius: 3px;
  padding: 0 4px;
  user-select: none;
}

.ai-conv-list {
  flex: 1;
  overflow-y: auto;
  padding: 4px;
}
.ai-conv-group-title {
  padding: 8px 8px 3px;
  font-size: 10px;
  font-weight: 600;
  color: var(--df-text-dim);
  user-select: none;
}
.ai-conv-group-title--fold {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 3px;
}
.ai-conv-group-title--fold:hover {
  color: var(--df-text);
}
.ai-conv-group-arrow {
  display: inline-block;
  transition: transform 0.15s;
  font-size: 9px;
}
.ai-conv-group-arrow.is-folded {
  transform: rotate(0deg);
}
.ai-conv-group-arrow:not(.is-folded) {
  transform: rotate(90deg);
}
.ai-conv-group-count {
  margin-left: 2px;
  font-weight: 400;
  opacity: 0.7;
}
.ai-conv-group-empty {
  padding: 2px 8px 4px 20px;
  font-size: 10px;
  color: var(--df-text-dim);
  font-style: italic;
}
.ai-conv-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 8px;
  border-radius: var(--df-radius);
  cursor: pointer;
  transition: background 0.15s;
  gap: 4px;
}
.ai-conv-item:hover {
  background: var(--df-sidebar-hover);
}
.ai-conv-item--active {
  background: var(--df-sidebar-active);
}
.ai-conv-item--archived .ai-conv-item-title {
  opacity: 0.6;
}
.ai-conv-item-main {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.ai-conv-item-title {
  font-size: 11px;
  color: var(--df-text);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 3px;
  min-width: 0;
}
/* UX-2025-20 §7.4: AI 生成标题淡入(0.3s opacity + transform 过渡) */
.ai-conv-item-title--flash {
  animation: ai-title-flash 0.3s var(--df-ease);
}
.ai-conv-item-title-badge {
  flex-shrink: 0;
  color: var(--df-success);
}
@keyframes ai-title-flash {
  from { opacity: 0; transform: translateX(-3px); }
  to { opacity: 1; transform: translateX(0); }
}
.ai-conv-item-edit {
  font-size: 11px;
  color: var(--df-text);
  width: 100%;
  height: 18px;
  padding: 0 4px;
  border: 1px solid var(--df-primary, #4f8cff);
  border-radius: var(--df-radius-sm);
  background: var(--df-bg, #fff);
  outline: none;
  box-sizing: border-box;
}
.ai-conv-item-time {
  font-size: 9px;
  color: var(--df-text-dim);
}
/* F-09: 多会话并发生成指示器(会话项标题行内脉冲点,多会话可同时显示) */
.ai-conv-gen-dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--df-primary, #4f8cff);
  flex-shrink: 0;
  animation: ai-conv-gen-pulse 1.4s ease-in-out infinite;
}
@keyframes ai-conv-gen-pulse {
  0%, 100% { opacity: 0.35; transform: scale(0.85); }
  50% { opacity: 1; transform: scale(1.15); }
}
.ai-conv-item-actions {
  display: none;
  align-items: center;
  gap: 2px;
  flex-shrink: 0;
}
.ai-conv-item:hover .ai-conv-item-actions {
  display: flex;
}
/* 菜单展开时强制 actions 可见(鼠标移到菜单上 item 不再 hover,防菜单消失) */
.ai-conv-item:has(.ai-conv-actions-menu) .ai-conv-item-actions {
  display: flex;
}
.ai-conv-item-act {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  border: none;
  border-radius: var(--df-radius-sm);
  background: transparent;
  color: var(--df-text-dim);
  cursor: pointer;
  flex-shrink: 0;
}
.ai-conv-item-act:hover {
  background: var(--df-sidebar-hover);
  color: var(--df-text);
}
/* CR-22-1: 已置顶对话视觉强调(左边线,不依赖菜单展开,一眼识别)。
   pinned 类挂在 .ai-conv-item 上(操作收进更多菜单后,按钮不再常驻,改 item 级类)。 */
.ai-conv-item--pinned {
  box-shadow: inset 2px 0 0 var(--df-accent, var(--df-text));
}
/* ── 「更多」操作菜单(置顶/归档/删除)──
   「...」按钮 hover 时随 actions 浮出(同原 4 按钮交互),点击展开下拉。
   菜单绝对定位浮于 item 下方右侧,窄侧栏避免溢出。 */
.ai-conv-item-more {
  position: relative;
  display: flex;
  align-items: center;
  flex-shrink: 0;
}
.ai-conv-actions-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 2px;
  z-index: 20;
  min-width: 104px;
  padding: 2px;
  display: flex;
  flex-direction: column;
  gap: 1px;
  background: var(--df-bg, #fff);
  border: 1px solid var(--df-border, #e2e2e2);
  border-radius: var(--df-radius-sm);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}
.ai-conv-actions-opt {
  display: flex;
  align-items: center;
  gap: 6px;
  border: none;
  background: transparent;
  text-align: left;
  padding: 5px 8px;
  font-size: 11px;
  color: var(--df-text);
  cursor: pointer;
  border-radius: var(--df-radius-sm);
  white-space: nowrap;
}
.ai-conv-actions-opt:hover {
  background: var(--df-sidebar-hover);
}
.ai-conv-actions-opt--danger:hover {
  background: var(--df-danger-bg);
  color: var(--df-danger);
}
.ai-conv-empty {
  padding: 16px 8px;
  text-align: center;
  font-size: 11px;
  color: var(--df-text-dim);
}

/* 侧边栏滑入动画 */
.sidebar-slide-enter-active { transition: width 0.2s var(--df-ease), opacity 0.15s; }
.sidebar-slide-leave-active { transition: width 0.15s var(--df-ease), opacity 0.1s; }
.sidebar-slide-enter-from, .sidebar-slide-leave-to {
  width: 0;
  min-width: 0;
  opacity: 0;
  overflow: hidden;
}
</style>
