<template>
  <TreeItem
    :label="connection.display_name"
    :load-children="loadChildren"
    :depth="depth"
    @select="navigateToRoot"
  >
    <template #icon>
      <svg class="w-4 h-4 shrink-0" :class="providerIconColor" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
          d="M3 15a4 4 0 004 4h9a5 5 0 10-.1-9.999 5.002 5.002 0 10-9.78 2.096A4.001 4.001 0 003 15z" />
      </svg>
    </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 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>
