<script setup lang="ts">
import type { TreeItem } from './type'
import Leaf from './leaf.vue'
import TreeNode from './tree-node.vue'

const props = defineProps<{
  data: TreeItem[]
  selectedValue?: string
  onFetchChildren: (parentId: string) => Promise<void>
}>()

const emit = defineEmits(['select'])

function handleSelect(value: string) {
  emit('select', value)
}

// Computed untuk mendeteksi apakah ada node dengan children dalam level ini
const hasAnyChildrenInLevel = computed(() => {
  return props.data.some(item => item.hasChildren)
})
</script>

<template>
  <div class="tree-view min-w-max">
    <template v-for="item in data" :key="item.value">
      <!-- Jika item memiliki children, gunakan TreeNode -->
      <TreeNode
        v-if="item.hasChildren"
        :item="item"
        :selected-value="selectedValue"
        :on-fetch-children="onFetchChildren"
        @select="handleSelect"
      />
      <!-- Jika item tidak memiliki children, gunakan Leaf -->
      <Leaf
        v-else
        :item="item"
        :selected-value="selectedValue"
        :should-align="hasAnyChildrenInLevel"
        @select="handleSelect"
      />
    </template>
  </div>
</template>
