<template>
  <div class="module-node" :class="{ active: selected }">
    <div class="module-node__header">
      <span class="module-node__icon">📦</span>
      <span class="module-node__name">{{ data.name }}</span>
    </div>
    <div class="module-node__path">{{ truncatedPath }}</div>
    <div v-if="stackList.length" class="module-node__tags">
      <span v-for="s in stackList" :key="s" class="module-node__tag">{{ s }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { parseJsonArray } from '@/utils/json'

const props = defineProps<{
  data: {
    name: string
    path: string
    stack: string | null
    gitUrl: string | null
  }
  selected?: boolean
}>()

// 路径截断:保留首段根目录(盘符/家目录锚点)+末尾目录,丢中间段。
// 旧实现 '...' + slice(-29) 仅留末尾,丢失前缀致同末不同源目录难辨(如 C:/a 与 D:/b 同名)。
// 现:根段(/第一段分隔符前)+ … + 末尾(容纳 32 字符上限内)。短路径直返。
const truncatedPath = computed(() => {
  const p = props.data?.path || ''
  if (p.length <= 32) return p
  // 拆根段:取首个路径分隔符(/ 或 \,跨平台)前部分作锚点(盘符 C: 或家目录片段)
  const sepMatch = p.match(/[\\/]/)
  if (!sepMatch) {
    // 无分隔符的单段长名,退化为末尾
    return '...' + p.slice(-29)
  }
  const sepIdx = sepMatch.index! + 1
  const head = p.slice(0, sepIdx)
  const tailBudget = 32 - head.length - 1 // -1 留给 …(此处用 …)
  if (tailBudget < 4) {
    // 根段本身就长,退化为末尾(保留原行为)
    return '...' + p.slice(-29)
  }
  const tail = p.slice(-tailBudget)
  return head + '…' + tail
})

const stackList = computed(() => parseJsonArray(props.data?.stack).slice(0, 3))
</script>

<style scoped>
.module-node {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 8px 12px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: #16213e;
  border: 1px solid #0f3460;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.15s;
}
.module-node.active {
  border-color: #5378e8;
  box-shadow: 0 0 0 2px rgba(83, 120, 232, 0.3);
}
.module-node__header {
  display: flex;
  align-items: center;
  gap: 6px;
}
.module-node__icon {
  font-size: 14px;
}
.module-node__name {
  font-size: 13px;
  font-weight: 600;
  color: #e0e0e0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.module-node__path {
  font-size: 10px;
  color: #888;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.module-node__tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}
.module-node__tag {
  font-size: 9px;
  padding: 1px 6px;
  border-radius: 3px;
  background: rgba(83, 120, 232, 0.15);
  color: #7c9aff;
}
</style>
