<template>
  <!-- 无远程配置：极简入口按钮 -->
  <div v-if="!hasRemote" class="connection-indicator mini" @click="$emit('add')">
    <icon-cloud />
  </div>

  <!-- 有远程配置：完整标签 + 下拉菜单 -->
  <div v-else class="connection-indicator" @click.stop="showMenu = !showMenu">
    <span class="label">{{ label }}</span>

    <div v-if="showMenu" class="menu" @click.stop>
      <div class="menu-header">远程连接</div>
      <div
        v-for="p in profiles"
        :key="p.id"
        :class="['menu-item', { active: p.id === activeId }]"
        @click="handleSelect(p)"
      >
        <span :class="['dot', dotClass(p)]"></span>
        <span class="menu-name">{{ p.name }}</span>
        <span
          v-if="p.type !== 'local'"
          class="more-btn"
          title="更多操作"
          @click.stop="toggleMore(p)"
        >···</span>
        <!-- 更多操作子菜单 -->
        <div v-if="moreOpenId === p.id" class="more-menu" @click.stop>
          <div class="more-item" @click="handleEdit(p)">编辑</div>
          <div class="more-item danger" @click="handleDelete(p)">删除</div>
        </div>
      </div>
      <div class="menu-divider" />
      <button class="menu-item add-btn" @click="$emit('add')">
        + 添加服务器
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, shallowRef, onMounted, onUnmounted } from 'vue'
import { IconCloud } from '@arco-design/web-vue/es/icon'
import { Message } from '@arco-design/web-vue'
import { connectionManager } from '@/api/connection-manager'

const emit = defineEmits<{ (e: 'add'): void; (e: 'select', id: string): void; (e: 'edit', id: string): void }>()

const showMenu = ref(false)
const moreOpenId = ref<string | null>(null)
const profiles = shallowRef(connectionManager.profiles)
const activeId = shallowRef(connectionManager.activeProfile?.id ?? '')

// 是否有远程/SFTP profile（决定显示模式）
const hasRemote = computed(() => profiles.value.some(p => p.type !== 'local'))

// 防抖：避免 connecting→connected 快速切换导致闪烁
const displayState = ref(connectionManager.state)
let _stateTimer: ReturnType<typeof setTimeout> | null = null

const state = computed(() => displayState.value)
const label = computed(() => {
  const p = profiles.value.find(p => p.id === activeId.value)
  if (!p || p.type === 'local') return '本地'
  return p.name
})

// 监听连接变化，主动触发更新（带防抖）
connectionManager.onStateChange((newState) => {
  profiles.value = connectionManager.profiles
  activeId.value = connectionManager.activeProfile?.id ?? ''
  if (_stateTimer) clearTimeout(_stateTimer)
  if (newState === 'connecting') {
    _stateTimer = setTimeout(() => { displayState.value = newState }, 300)
  } else {
    displayState.value = newState
  }
})

// 点击外部关闭菜单
function handleClickOutside(e: MouseEvent) {
  const el = e.target as HTMLElement
  if (!el.closest('.connection-indicator')) {
    showMenu.value = false
    moreOpenId.value = null
  }
}
onMounted(() => document.addEventListener('click', handleClickOutside))
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  if (_stateTimer) clearTimeout(_stateTimer)
})

async function handleSelect(p: { id: string }) {
  showMenu.value = false
  try {
    await connectionManager.connect(p.id)
    emit('select', p.id)
  } catch (err) {
    Message.error(`连接失败: ${err instanceof Error ? err.message : String(err)}`)
  }
}

function toggleMore(p: { id: string }) {
  moreOpenId.value = moreOpenId.value === p.id ? null : p.id
}

function handleEdit(p: { id: string }) {
  moreOpenId.value = null
  showMenu.value = false
  emit('edit', p.id)
}

function handleDelete(p: { id: string; name: string }) {
  if (!window.confirm(`确定删除「${p.name}」？`)) return
  connectionManager.removeProfile(p.id)
  moreOpenId.value = null
}

function dotClass(p: { type: string }): string {
  if (p.type === 'sftp') return 'sftp'
  if (p.type === 'remote') return 'remote'
  if (p.type === 'qiniu' || p.type === 'aliyun') return 'oss'
  return 'local'
}
</script>

<style scoped>
.connection-indicator {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 2px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  color: var(--color-text-2);
  transition: background 0.15s, border-color 0.15s;
  border: 1px solid transparent;
  white-space: nowrap;
  flex-shrink: 0;
}

.connection-indicator:hover {
  background: var(--color-fill-2);
  border-color: var(--color-border-2);
}

/* 极简模式：仅图标 */
.connection-indicator.mini {
  padding: 3px 6px;
  border: none;
  gap: 0;
}
.connection-indicator.mini:hover {
  background: var(--color-fill-2);
  border-color: transparent;
}
.connection-indicator.mini :deep(.arco-icon) {
  font-size: 14px;
  color: var(--color-text-3);
}

.dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  flex-shrink: 0;
}

.dot.connected { background: var(--color-success-6); }
.dot.connecting { background: var(--color-warning-6); animation: pulse 1.5s infinite; }
.dot.disconnected { background: var(--color-danger-6); }
.dot.error { background: var(--color-danger-6); }
.dot.local { background: var(--color-text-3); }
.dot.remote { background: var(--color-primary-6); }
.dot.sftp { background: #7c3aed; }
.dot.oss { background: #ff7d00; }

.label {
  max-width: 70px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  min-width: 180px;
  background: var(--color-bg-popup);
  border: 1px solid var(--color-border);
  border-radius: 6px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  z-index: 1000;
  padding: 4px 0;
}

.menu-header {
  padding: 8px 12px;
  font-size: 12px;
  color: var(--color-text-3);
  border-bottom: 1px solid var(--color-fill-1);
}

.menu-item {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  cursor: pointer;
  font-size: 13px;
  transition: background 0.15s;
}
.menu-item:hover { background: var(--color-fill-1); }
.menu-item.active { background: var(--color-primary-light-1); color: var(--color-primary-6); }

.menu-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.more-btn {
  margin-left: auto;
  opacity: 0;
  font-size: 14px;
  color: var(--color-text-3);
  cursor: pointer;
  padding: 0 4px;
  line-height: 1;
  letter-spacing: 1px;
  transition: opacity 0.15s;
  user-select: none;
}
.menu-item:hover .more-btn { opacity: 1; }

/* 更多操作子菜单 */
.more-menu {
  position: absolute;
  right: 0;
  top: 0;
  transform: translateX(100%);
  min-width: 90px;
  background: var(--color-bg-popup);
  border: 1px solid var(--color-border);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  padding: 2px 0;
}

.more-item {
  padding: 6px 14px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.15s;
}
.more-item:hover { background: var(--color-fill-1); }
.more-item.danger { color: var(--color-danger-6); }

.menu-divider {
  height: 1px;
  background: var(--color-fill-1);
  margin: 4px 8px;
}

.add-btn {
  width: 100%;
  border: none;
  background: transparent;
  text-align: left;
  color: var(--color-primary-6);
  font-size: 13px;
  padding: 8px 12px;
}
.add-btn:hover { background: var(--color-primary-light-1); }

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}
</style>
