<template>
  <nav aria-label="Breadcrumb" class="bg-base-200/50 border-b border-base-300/50 px-4 py-2 shrink-0">
    <ol class="flex flex-wrap items-center gap-1.5 text-sm">
      <li v-for="(item, i) in items" :key="item.path" class="flex items-center gap-1.5">
        <template v-if="i > 0">
          <span class="text-base-content/40" aria-hidden="true">/</span>
        </template>
        <NuxtLink
          v-if="i < items.length - 1"
          :to="item.path"
          class="link link-hover text-base-content/80 hover:text-primary"
        >
          {{ item.label }}
        </NuxtLink>
        <span v-else class="font-medium text-base-content" aria-current="page">{{ item.label }}</span>
      </li>
    </ol>
  </nav>
</template>

<script setup lang="ts">
const route = useRoute()
const adminMapName = useState<string | null>('admin-breadcrumb-map-name', () => null)

interface BreadcrumbItem {
  path: string
  label: string
}

const items = computed<BreadcrumbItem[]>(() => {
  const path = route.path
  if (!path.startsWith('/admin')) return []
  const segments = path.replace(/^\/admin\/?/, '').split('/').filter(Boolean)
  const result: BreadcrumbItem[] = [{ path: '/admin', label: 'Admin' }]
  if (segments[0] === 'users') {
    result.push({ path: '/admin', label: 'Users' })
    if (segments[1]) {
      result.push({
        path: `/admin/users/${segments[1]}`,
        label: segments[1] === 'new' ? 'New user' : segments[1],
      })
    }
  } else if (segments[0] === 'maps') {
    result.push({ path: '/admin', label: 'Maps' })
    if (segments[1]) {
      const id = segments[1]
      result.push({
        path: `/admin/maps/${id}`,
        label: adminMapName.value ?? `Map ${id}`,
      })
    }
  }
  return result
})
</script>
