<template>
  <TreeItem
    :label="connectionName"
    :load-children="loadChildren"
    :depth="depth"
    :is-active="isActive"
    @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"
        :connection-id="connection.id"
        :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'
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 route = useRoute()

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

const connectionName = computed(
  () => props.connection.display_name || props.connection.provider
)

/** Active when the current route is this connection's root or any subfolder. */
const isActive = computed(() => {
  const path = route.path
  return (
    path === `/cloud/${props.connection.id}/root` ||
    path.startsWith(`/cloud/${props.connection.id}/`)
  )
})

async function loadChildren() {
  // Use connection UUID, never provider slug (UAT gap: 422 from UUID endpoint if slug passed)
  const data = await api.getCloudFoldersByConnectionId(props.connection.id, '')
  return (data.items ?? []).filter(i => i.is_dir)
}

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