<script setup>
import { ref, h } from 'vue'
import { NIcon, NInput, useDialog } from 'naive-ui'
import {
  FolderOutline, FolderOpenOutline, DocumentOutline,
  CreateOutline, AddOutline, TrashOutline
} from '@vicons/ionicons5'

const props = defineProps({
  files: { type: Array, default: () => [] },
  currentFile: { type: String, default: '' }
})

const emit = defineEmits(['select', 'create-file', 'create-dir', 'delete'])

const dialog = useDialog()
const expandedDirs = ref(new Set())

function toggleDir(path) {
  const s = new Set(expandedDirs.value)
  if (s.has(path)) s.delete(path)
  else s.add(path)
  expandedDirs.value = s
}

function isExpanded(path) {
  return expandedDirs.value.has(path)
}

function handleNodeClick(node) {
  if (node.type === 'directory') {
    toggleDir(node.path)
  } else {
    emit('select', node.path)
  }
}

// ==================== 弹窗式创建/删除 ====================

function showCreateDialog(title, placeholder, onConfirm) {
  let inputValue = ''
  dialog.create({
    title,
    content: () => h(NInput, {
      placeholder,
      autofocus: true,
      'onUpdate:value': (val) => { inputValue = val }
    }),
    maskClosable: false,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      const name = inputValue.trim()
      if (!name) return false
      onConfirm(name)
    }
  })
}

function handleCreateInDir(node, type) {
  const prefix = node.path + '/'
  if (type === 'file') {
    showCreateDialog('新建文件', '输入文件名（如 main.py）', (name) => {
      emit('create-file', prefix + name)
    })
  } else {
    showCreateDialog('新建目录', '输入目录名', (name) => {
      emit('create-dir', prefix + name)
    })
  }
}

function handleCreateAtRoot(type) {
  if (type === 'file') {
    showCreateDialog('新建文件', '输入文件名（如 main.py）', (name) => {
      emit('create-file', name)
    })
  } else {
    showCreateDialog('新建目录', '输入目录名', (name) => {
      emit('create-dir', name)
    })
  }
}

function handleDelete(node) {
  if (node.path === 'SKILL.md') return
  dialog.warning({
    title: '确认删除',
    content: `确定要删除「${node.name}」吗？${node.type === 'directory' ? '目录下的所有文件也会被删除。' : ''}`,
    maskClosable: false,
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: () => {
      emit('delete', node.path)
    }
  })
}

function getIconColor(node) {
  if (node.type === 'directory') return '#e0a526'
  const ext = node.name.split('.').pop().toLowerCase()
  const colors = {
    md: '#519aba', js: '#cbcb41', ts: '#3178c6', json: '#cbcb41',
    py: '#3572a5', java: '#b07219', css: '#563d7c', html: '#e34c26',
    sh: '#89e051', yaml: '#cb171e', yml: '#cb171e'
  }
  return colors[ext] || '#8b8b8b'
}
</script>

<template>
  <div class="file-tree">
    <!-- 顶部操作栏 -->
    <div class="tree-toolbar">
      <span class="tree-title">文件浏览器</span>
      <div class="tree-actions">
        <button class="tree-action-btn" title="新建文件" @click="handleCreateAtRoot('file')">
          <n-icon size="14"><CreateOutline /></n-icon>
        </button>
        <button class="tree-action-btn" title="新建目录" @click="handleCreateAtRoot('directory')">
          <n-icon size="14"><AddOutline /></n-icon>
        </button>
      </div>
    </div>

    <!-- 文件树 -->
    <div class="tree-content">
      <template v-for="node in files" :key="node.path">
        <div
          class="tree-node"
          :class="{ active: currentFile === node.path }"
          :style="{ paddingLeft: '12px' }"
          @click="handleNodeClick(node)"
        >
          <span v-if="node.type === 'directory'" class="tree-arrow" :class="{ expanded: isExpanded(node.path) }">
            ›
          </span>
          <span v-else class="tree-arrow-spacer" />

          <n-icon size="15" :color="getIconColor(node)" class="tree-icon">
            <FolderOpenOutline v-if="node.type === 'directory' && isExpanded(node.path)" />
            <FolderOutline v-else-if="node.type === 'directory'" />
            <DocumentOutline v-else />
          </n-icon>

          <span class="tree-name">{{ node.name }}</span>

          <div v-if="node.type === 'directory'" class="node-actions">
            <button class="node-action" title="新建文件" @click.stop="handleCreateInDir(node, 'file')">
              <n-icon size="12"><CreateOutline /></n-icon>
            </button>
            <button class="node-action" title="删除" @click.stop="handleDelete(node)">
              <n-icon size="12"><TrashOutline /></n-icon>
            </button>
          </div>
          <div v-else class="node-actions">
            <button v-if="node.path !== 'SKILL.md'" class="node-action" title="删除" @click.stop="handleDelete(node)">
              <n-icon size="12"><TrashOutline /></n-icon>
            </button>
          </div>
        </div>

        <!-- 子节点：紧跟父节点渲染 -->
        <template v-if="node.type === 'directory' && isExpanded(node.path) && node.children">
          <template v-for="child in node.children" :key="child.path">
            <div
              class="tree-node"
              :class="{ active: currentFile === child.path }"
              :style="{ paddingLeft: '28px' }"
              @click="handleNodeClick(child)"
            >
              <span v-if="child.type === 'directory'" class="tree-arrow" :class="{ expanded: isExpanded(child.path) }">›</span>
              <span v-else class="tree-arrow-spacer" />

              <n-icon size="15" :color="getIconColor(child)" class="tree-icon">
                <FolderOpenOutline v-if="child.type === 'directory' && isExpanded(child.path)" />
                <FolderOutline v-else-if="child.type === 'directory'" />
                <DocumentOutline v-else />
              </n-icon>

              <span class="tree-name">{{ child.name }}</span>

              <div v-if="child.type === 'directory'" class="node-actions">
                <button class="node-action" title="新建文件" @click.stop="handleCreateInDir(child, 'file')">
                  <n-icon size="12"><CreateOutline /></n-icon>
                </button>
                <button class="node-action" title="删除" @click.stop="handleDelete(child)">
                  <n-icon size="12"><TrashOutline /></n-icon>
                </button>
              </div>
              <div v-else class="node-actions">
                <button v-if="child.path !== 'SKILL.md'" class="node-action" title="删除" @click.stop="handleDelete(child)">
                  <n-icon size="12"><TrashOutline /></n-icon>
                </button>
              </div>
            </div>

            <!-- 第三层：紧跟第二层父节点渲染 -->
            <template v-if="child.type === 'directory' && isExpanded(child.path) && child.children">
              <div
                v-for="grandchild in child.children"
                :key="grandchild.path"
                class="tree-node"
                :class="{ active: currentFile === grandchild.path }"
                :style="{ paddingLeft: '44px' }"
                @click="handleNodeClick(grandchild)"
              >
                <span v-if="grandchild.type === 'directory'" class="tree-arrow" :class="{ expanded: isExpanded(grandchild.path) }">›</span>
                <span v-else class="tree-arrow-spacer" />

                <n-icon size="15" :color="getIconColor(grandchild)" class="tree-icon">
                  <FolderOpenOutline v-if="grandchild.type === 'directory' && isExpanded(grandchild.path)" />
                  <FolderOutline v-else-if="grandchild.type === 'directory'" />
                  <DocumentOutline v-else />
                </n-icon>

                <span class="tree-name">{{ grandchild.name }}</span>

                <div class="node-actions">
                  <button v-if="grandchild.path !== 'SKILL.md'" class="node-action" title="删除" @click.stop="handleDelete(grandchild)">
                    <n-icon size="12"><TrashOutline /></n-icon>
                  </button>
                </div>
              </div>
            </template>
          </template>
        </template>
      </template>
    </div>
  </div>
</template>

<style scoped>
.file-tree {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tree-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  border-bottom: 1px solid var(--border-color);
}

.tree-title {
  font-size: 12px;
  font-weight: 600;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.tree-actions {
  display: flex;
  gap: 4px;
}

.tree-action-btn {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  border-radius: 4px;
  color: var(--text-tertiary);
  cursor: pointer;
  transition: all 0.15s;
}

.tree-action-btn:hover {
  background: rgba(255, 255, 255, 0.06);
  color: var(--text-primary);
}

.tree-content {
  flex: 1;
  overflow-y: auto;
  padding: 4px 0;
}

.tree-node {
  display: flex;
  align-items: center;
  height: 28px;
  cursor: pointer;
  transition: background 0.1s;
  position: relative;
}

.tree-node:hover {
  background: rgba(255, 255, 255, 0.04);
}

.tree-node.active {
  background: rgba(37, 99, 235, 0.12);
}

.tree-arrow {
  width: 16px;
  font-size: 13px;
  color: var(--text-tertiary);
  transition: transform 0.15s;
  flex-shrink: 0;
  text-align: center;
}

.tree-arrow.expanded {
  transform: rotate(90deg);
}

.tree-arrow-spacer {
  width: 16px;
  flex-shrink: 0;
}

.tree-icon {
  flex-shrink: 0;
  margin-right: 6px;
}

.tree-name {
  flex: 1;
  font-size: 13px;
  color: var(--text-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tree-node.active .tree-name {
  color: var(--text-primary);
}

.node-actions {
  display: none;
  align-items: center;
  gap: 2px;
  margin-right: 8px;
}

.tree-node:hover .node-actions {
  display: flex;
}

.node-action {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  border-radius: 3px;
  color: var(--text-muted);
  cursor: pointer;
}

.node-action:hover {
  background: rgba(255, 255, 255, 0.08);
  color: var(--text-primary);
}
</style>
