<template>
  <TreeItem
    :label="connection.display_name"
    :load-children="loadChildren"
    :depth="depth"
    @select="navigateToRoot"
  >
    <template #icon>
      <AppIcon name="cloud" class="w-4 h-4 shrink-0" :class="providerIconColor" />
    </template>
    <template #children="{ children }">
      <CloudFolderTreeItem
        v-for="folder in children"
        :key="folder.id"
        :folder="folder"
        :provider="connection.provider"
        :depth="depth + 1"
      />
    </template>
  </TreeItem>
</template>

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

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

const router = useRouter()

const providerIconColor = computed(() => providerColor(props.connection.provider))

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

function navigateToRoot() {
  router.push(`/cloud/${props.connection.provider}/root`)
}
</script>
