<template>
  <ul class="tree-list">
    <li v-for="item in items" :key="item.path">
      <div class="tree-item-row" @click="toggle(item)">
        <span class="tree-icon">
          <svg v-if="item.type === 'folder'" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/>
          </svg>
          <svg v-else width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
            <polyline points="14,2 14,8 20,8"/>
          </svg>
        </span>
        <span class="tree-name" :title="item.path">{{ item.name }}</span>
      </div>
      <TreeItem v-if="item.type === 'folder' && expandedPaths.has(item.path)" :key="item.path" v-model:expanded="expandedPaths" :items="item.children || []" />
    </li>
  </ul>
</template>

<script setup lang="ts">
import { onMounted, watch } from 'vue'

const props = defineProps<{
  items: any[]
  expanded?: Set<string>
}>()

const emit = defineEmits<{ 'update:expanded': [value: Set<string>] }>()

const expandedPaths = ref(new Set<string>())

defineExpose({ expandedPaths })

function toggle(item: any) {
  if (item.type !== 'folder') return
  const next = new Set(expandedPaths.value)
  if (next.has(item.path)) {
    next.delete(item.path)
  } else {
    next.add(item.path)
  }
  expandedPaths.value = next
  emit('update:expanded', next)
}

function syncExpanded() {
  if (props.expanded) {
    expandedPaths.value = new Set(props.expanded)
  }
}

watch(() => props.expanded, () => syncExpanded(), { immediate: true })

onMounted(() => syncExpanded())
</script>

<style scoped>
.tree-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.tree-item-row {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 3px 8px;
  cursor: pointer;
  border-radius: 4px;
  user-select: none;
  color: var(--text-secondary);
}

.tree-item-row:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.tree-icon {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  opacity: 0.6;
}

.tree-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tree-list .tree-list {
  padding-left: 16px;
}
</style>
