<template>
  <el-tree
    class="structure-tree"
    :data="data"
    :props="{ label: 'label', children: 'children' }"
    node-key="id"
    default-expand-all
    highlight-current
    @node-click="handleNodeClick"
  >
    <template #default="{ node, data: nodeData }">
      <span class="tree-node">
        <el-icon>
          <Document v-if="isFile(nodeData)" />
          <Folder v-else />
        </el-icon>
        <span>{{ node.label }}</span>
      </span>
    </template>
  </el-tree>
</template>

<script setup>
import { Document, Folder } from '@element-plus/icons-vue'

defineProps({
  data: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['file-select'])

function isFile(node) {
  if (node?.type === 'folder' || node?.type === 'directory') return false
  if (node?.type === 'file' || node?.isFile) return true
  return !node?.children?.length
}

function handleNodeClick(node) {
  if (isFile(node)) {
    emit('file-select', node)
  }
}
</script>

<style scoped lang="scss">
.structure-tree {
  min-width: 220px;
}

.tree-node {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}
</style>
