<template>
  <TreeItem
    :label="folder.name"
    :to="`/folders/${folder.id}`"
    :expandable="folder.has_children !== false && (!childrenLoaded || subfolders.length > 0)"
    :load-children="loadChildren"
    :depth="depth"
    :is-active="isActive"
    ref="treeRef"
  >
    <template #icon>
      <AppIcon
        name="folder"
        class="w-4 h-4 shrink-0"
        :class="isActive ? 'text-indigo-500' : 'text-gray-400'"
      />
    </template>
    <template #children="{ children }">
      <FolderTreeItem
        v-for="child in children"
        :key="child.id"
        :folder="child"
        :depth="depth + 1"
      />
    </template>
  </TreeItem>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import AppIcon from '../ui/AppIcon.vue'
import { useFoldersStore } from '../../stores/folders.js'
import * as api from '../../api/client.js'
import TreeItem from '../ui/TreeItem.vue'

const props = defineProps({
  folder: { type: Object, required: true },
  depth: { type: Number, default: 0 },
})

const route = useRoute()
const foldersStore = useFoldersStore()
const treeRef = ref(null)
const subfolders = ref([])
const childrenLoaded = ref(false)

const isActive = computed(() =>
  route.params.folderId != null &&
  (route.params.folderId === String(props.folder.id) || route.params.folderId === props.folder.id)
)

async function loadChildren() {
  const data = await api.listFolders(props.folder.id)
  subfolders.value = data.items ?? data
  childrenLoaded.value = true
  return subfolders.value
}

watch(() => foldersStore.treeVersion, () => {
  treeRef.value?.refresh()
})
</script>
