<script setup lang="ts">
import { useApp } from '@/composables/useApp'
import { useRouter } from 'vue-router'
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/components/ui/breadcrumb'
import { ChevronRight } from 'lucide-vue-next'

const app = useApp()
const router = useRouter()

function buildBreadcrumbs() {
  const conn = app.activeConnection.value
  if (!conn) return []
  const path = conn.currentPath.value
  const parts = path.split('/').filter(Boolean)
  const crumbs = [{ name: 'Home', path: '/' }]
  let current = ''
  for (const part of parts) {
    current += `/${part}`
    crumbs.push({ name: part, path: current })
  }
  return crumbs
}

function navigate(path: string) {
  router.push({ query: path === '/' ? {} : { path } })
}
</script>

<template>
  <div class="px-3 py-2 overflow-x-auto">
    <Breadcrumb>
      <BreadcrumbList class="flex-nowrap text-sm">
        <template v-for="(crumb, index) in buildBreadcrumbs()" :key="crumb.path">
          <BreadcrumbItem class="shrink-0">
            <BreadcrumbLink
              v-if="index < buildBreadcrumbs().length - 1"
              as="button"
              @click="navigate(crumb.path)"
              class="text-muted-foreground hover:text-foreground transition-colors whitespace-nowrap"
            >
              {{ crumb.name }}
            </BreadcrumbLink>
            <BreadcrumbPage v-else class="whitespace-nowrap">
              {{ crumb.name }}
            </BreadcrumbPage>
          </BreadcrumbItem>
          <BreadcrumbSeparator v-if="index < buildBreadcrumbs().length - 1" class="shrink-0">
            <ChevronRight class="size-3" />
          </BreadcrumbSeparator>
        </template>
      </BreadcrumbList>
    </Breadcrumb>
  </div>
</template>
