<template>
  <StorageBrowser
    mode="cloud"
    :folders="connectionRoots"
    :files="[]"
    :breadcrumb="[]"
    :upload-queue="[]"
    :loading="loading"
    :empty-message="'No cloud storage connected'"
    :empty-hint="'Connect Google Drive, OneDrive, Nextcloud, or a WebDAV server in Settings.'"
    @folder-navigate="openConnection"
  />
</template>

<script setup>
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCloudConnectionsStore } from '../stores/cloudConnections.js'
import { providerLabel } from '../utils/formatters.js'
import StorageBrowser from '../components/storage/StorageBrowser.vue'

const router = useRouter()
const cloudStore = useCloudConnectionsStore()

const loading = computed(() => cloudStore.loading)

/**
 * Map each connection to a folder-like item for StorageBrowser.
 * name uses defaultDisplayName so duplicate providers get a 4-char UUID suffix.
 */
const connectionRoots = computed(() =>
  cloudStore.connections.map(conn => ({
    id: conn.id,
    name: conn.display_name || cloudStore.defaultDisplayName(conn),
    _connectionId: conn.id,
    _provider: conn.provider,
    created_at: conn.connected_at ?? null,
  }))
)

function openConnection(item) {
  router.push(`/cloud/${item._connectionId}/root`)
}

onMounted(() => {
  if (cloudStore.connections.length === 0) {
    cloudStore.fetchConnections()
  }
})
</script>
