<template>
  <div class="toolbar">
    <div class="toolbar-left">
      <!-- 路径输入 -->
      <div class="path-input-wrapper">
        <!-- ZIP 浏览模式：显示 ZIP 路径和面包屑 -->
        <div v-if="config.isBrowsingZip" class="zip-breadcrumb">
          <a-tag size="small" class="zip-file-tag" @click="handleNavigateToZipRoot">
            📦 {{ config.zipFileName }}
          </a-tag>
          <template v-if="config.zipBreadcrumbs && config.zipBreadcrumbs.length > 0">
            <icon-right class="breadcrumb-sep" />
            <a-tag
              v-for="(crumb, index) in config.zipBreadcrumbs"
              :key="index"
              size="small"
              class="breadcrumb-tag"
              @click="handleNavigateToZipDirectory(crumb.path)"
            >
              {{ crumb.name }}
            </a-tag>
          </template>
          <a-button size="small" type="outline" @click="handleExitZip">
            <template #icon><icon-close /></template>
            退出 ZIP
          </a-button>
        </div>
        <!-- 正常模式：连接指示器 + 面包屑导航（融合布局） -->
        <div v-else class="path-breadcrumb-wrapper">
          <!-- 连接指示器（紧凑标签样式，作为面包屑首段） -->
          <ConnectionIndicator @add="showConnectionDialog = true" @select="onConnectionChanged" @edit="onEditProfile" />
          <span class="breadcrumb-sep">›</span>
          <!-- 路径面包屑 -->
          <PathBreadcrumb
            :path="config.filePath"
            @navigate="handleGoToPath"
            @openFile="handleOpenFile"
          />
          <!-- 右侧操作：快捷路径 + 复制 -->
          <div class="breadcrumb-right-actions">
            <a-tooltip content="快捷路径" position="bottom">
              <a-dropdown>
                <a-button size="mini" type="text" class="shortcut-btn">
                  <template #icon><icon-forward /></template>
                </a-button>
                <template #content>
                  <a-doption
                    v-for="shortcut in config.commonPaths"
                    :key="shortcut.path"
                    @click="handleGoToPath(shortcut.path)"
                  >
                    <template #icon>{{ (shortcut.name || '').split(' ')[0] }}</template>
                    {{ (shortcut.name || '').substring(2) }}
                  </a-doption>
                </template>
              </a-dropdown>
            </a-tooltip>
            <a-tooltip :content="copied ? '已复制' : '复制路径'" position="top">
              <a-button
                size="mini"
                type="text"
                :status="copied ? 'success' : 'normal'"
                class="toolbar-copy-btn"
                @click="handleCopyPath"
              >
                <icon-copy v-if="!copied" />
                <icon-check v-else />
              </a-button>
            </a-tooltip>
          </div>
        </div>
      </div>
    </div>

    <div class="toolbar-right">
      <!-- 搜索框 -->
      <a-input-search
        :model-value="config.searchKeyword"
        placeholder="搜索文件..."
        size="small"
        class="toolbar-search"
        allow-clear
        @search="handleSearch"
        @update:model-value="handleSearch"
        @keyup.escape="handleClearSearch"
      />

      <!-- 刷新按钮 -->
      <a-button
        size="small"
        :loading="config.fileLoading"
        @click="handleRefresh"
      >
        <template #icon>
          <icon-refresh />
        </template>
        刷新
      </a-button>

      <!-- 历史记录下拉（仅图标，Ctrl+H） -->
      <a-dropdown
        v-model:popup-visible="historyPopupVisible"
      >
        <a-tooltip content="历史记录 (Ctrl+H)" position="left">
          <a-button size="small">
            <template #icon><icon-history /></template>
          </a-button>
        </a-tooltip>
        <template #content>
          <div class="history-dropdown-content">
            <a-doption
              v-for="path in config.pathHistory.slice(0, 10)"
              :key="path"
              @click="handleGoToPath(path)"
            >
              <span class="history-path-text">{{ path }}</span>
            </a-doption>
            <a-doption v-if="config.pathHistory.length === 0" disabled>暂无历史</a-doption>
          </div>
        </template>
      </a-dropdown>

      <!-- 切换侧边栏 -->
      <a-button
        size="small"
        :type="config.showSidebar ? 'primary' : 'text'"
        @click="handleToggleSidebar"
      >
        <template #icon>
          <icon-menu />
        </template>
      </a-button>
    </div>
  </div>

  <ConnectionDialog ref="connectionDialogRef" v-model:visible="showConnectionDialog" />
</template>

<script setup lang="ts">
import { nextTick } from 'vue'
import { IconForward, IconHistory, IconRefresh, IconMenu, IconClose, IconRight, IconCopy, IconCheck } from '@arco-design/web-vue/es/icon'
import type { ToolbarConfig } from '@/types/file-system'
import PathBreadcrumb from './PathBreadcrumb.vue'
import { useClipboardCopy } from '../composables/useClipboardCopy'
import ConnectionIndicator from './ConnectionIndicator.vue'
import ConnectionDialog from './ConnectionDialog.vue'

// Props
interface Props {
  config: ToolbarConfig
  openConnectionDialog?: boolean
  editProfileId?: string | null
}

const props = defineProps<Props>()

// Emits
interface Emits {
  (e: 'update:filePath', path: string): void
  (e: 'update:showSidebar', show: boolean): void
  (e: 'update:searchKeyword', keyword: string): void
  (e: 'refresh'): void
  (e: 'exitZip'): void
  (e: 'goToPath', path: string): void
  (e: 'openFile', path: string): void
  (e: 'navigateToZipDirectory', path: string): void
  (e: 'connectionChanged'): void
}

const emit = defineEmits<Emits>()

// 连接对话框
const showConnectionDialog = ref(false)
const connectionDialogRef = ref<InstanceType<typeof ConnectionDialog>>()

watch(() => props.openConnectionDialog, (v) => {
  if (v > 0) {
    showConnectionDialog.value = true
    if (props.editProfileId) {
      nextTick(() => connectionDialogRef.value?.editProfile(props.editProfileId))
    }
  }
})

const onConnectionChanged = async (_id: string) => {
  emit('connectionChanged')
}

const onEditProfile = (id: string) => {
  showConnectionDialog.value = true
  // 等待 DOM 更新后调用 editProfile 填充表单
  nextTick(() => connectionDialogRef.value?.editProfile(id))
}

// 历史记录下拉显隐（供父组件 Ctrl+H 调用）
const historyPopupVisible = ref(false)

// 事件处理
const handleGoToPath = (path: string) => {
  emit('goToPath', path)
}

const handleOpenFile = (path: string) => {
  emit('openFile', path)
}

const handleRefresh = () => {
  emit('refresh')
}

const handleExitZip = () => {
  emit('exitZip')
}

const handleNavigateToZipRoot = () => {
  emit('navigateToZipDirectory', '')
}

const handleToggleSidebar = () => {
  emit('update:showSidebar', !props.config.showSidebar)
}

const handleSearch = (keyword: string) => {
  emit('update:searchKeyword', keyword)
}

const handleClearSearch = () => {
  emit('update:searchKeyword', '')
}

// 切换历史记录下拉面板（供父组件 Ctrl+H 调用）
const toggleHistoryDropdown = () => {
  historyPopupVisible.value = !historyPopupVisible.value
}

const { copied, copy: copyPath } = useClipboardCopy()

// 暴露方法给父组件
defineExpose({ toggleHistoryDropdown })

const handleCopyPath = async () => {
  await copyPath(props.config.filePath)
}
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
  gap: 12px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.toolbar-right :deep(.arco-btn-size-small),
.toolbar-right :deep(.arco-input-wrapper) {
  height: 34px;
}

.toolbar-search {
  width: 180px;
  flex-shrink: 0;
}

.path-input-wrapper {
  flex: 1;
  min-width: 200px;
}

.path-breadcrumb-wrapper {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 200px;
  gap: 4px;
  padding: 4px 8px;
  background: var(--color-fill-1);
  border-radius: 4px;
  border: 1px solid var(--color-border);
  transition: border-color 0.2s;
  overflow: visible;
}

.path-breadcrumb-wrapper:hover {
  border-color: var(--color-border-2);
}

.breadcrumb-sep {
  color: var(--color-text-3);
  font-size: 12px;
  flex-shrink: 0;
  line-height: 1;
  margin: 0 1px;
}

.breadcrumb-right-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-left: auto;
  flex-shrink: 0;
}

.shortcut-btn {
  padding: 1px 3px;
}

.toolbar-copy-btn {
  padding: 2px 4px;
}

.zip-breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.zip-file-tag {
  cursor: pointer;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
  background: var(--color-fill-2);
  border-color: var(--color-border-2);
  transition: all 0.2s;
}

.zip-file-tag:hover {
  background: var(--color-fill-3);
  border-color: rgb(var(--primary-6));
}

.breadcrumb-tag {
  cursor: pointer;
  font-size: 12px;
  background: var(--color-fill-1);
  border-color: var(--color-border-2);
  transition: all 0.2s;
}

.breadcrumb-tag:hover {
  background: var(--color-fill-2);
  border-color: rgb(var(--primary-6));
}

/* 历史记录下拉 */
.history-dropdown-content {
  max-width: 420px;
  max-height: 300px;
  overflow-y: auto;
}

.history-path-text {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 380px;
}
</style>
