<template>
  <TreeItem
    :label="folder.name"
    :expandable="folder.is_dir"
    :load-children="loadChildren"
    :depth="depth"
    @select="navigate"
  >
    <template #icon>
      <AppIcon v-if="folder.is_dir" name="folder" class="w-4 h-4 shrink-0 text-gray-400" />
      <AppIcon v-else name="fileDoc" class="w-4 h-4 shrink-0 text-gray-400" />
    </template>
    <template #children="{ children }">
      <CloudFolderTreeItem
        v-for="child in children"
        :key="child.id"
        :folder="child"
        :provider="provider"
        :depth="depth + 1"
      />
    </template>
  </TreeItem>
</template>

<script setup>
import { useRouter } from 'vue-router'
import * as api from '../../api/client.js'
import AppIcon from '../ui/AppIcon.vue'
import TreeItem from '../ui/TreeItem.vue'

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

const router = useRouter()

async function loadChildren() {
  const data = await api.getCloudFolders(props.provider, props.folder.id)
  return (data.items ?? []).filter(i => i.is_dir)
}

function navigate() {
  router.push(`/cloud/${props.provider}/${props.folder.id}`)
}
</script>
