<template>
  <TreeItem
    :label="folder.name"
    :expandable="folder.is_dir"
    :load-children="loadChildren"
    :depth="depth"
    :is-active="isActive"
    @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"
        :connection-id="connectionId"
        :depth="depth + 1"
      />
    </template>
  </TreeItem>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter, useRoute } 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 },
  connectionId: { type: String, required: true },
  depth: { type: Number, default: 2 },
})

const router = useRouter()
const route = useRoute()

/** Active when the current route points to this exact folder. */
const isActive = computed(() => {
  return route.path === `/cloud/${props.connectionId}/${props.folder.id}`
})

async function loadChildren() {
  // Browse by connection UUID + provider item/path reference — never provider slug
  const data = await api.getCloudFoldersByConnectionId(props.connectionId, props.folder.id)
  return (data.items ?? []).filter(i => i.is_dir)
}

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