<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>
      <svg
        class="w-4 h-4 shrink-0"
        :class="isActive ? 'text-indigo-500' : 'text-gray-400'"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
          d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" />
      </svg>
    </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 { 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>
