<template>
  <TreeItem
    :label="folder.name"
    :expandable="folder.is_dir"
    :load-children="loadChildren"
    :depth="depth"
    @select="navigate"
  >
    <template #icon>
      <svg
        v-if="folder.is_dir"
        class="w-4 h-4 shrink-0 text-gray-400"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
          d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" />
      </svg>
      <svg
        v-else
        class="w-4 h-4 shrink-0 text-gray-400"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
          d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
      </svg>
    </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 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>
