<script setup lang="ts">
  import { computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  const route = useRoute()
  const router = useRouter()

  interface BreadcrumbItem {
    title: string
    path?: string
    isCurrent?: boolean
  }

  const breadcrumbs = computed<BreadcrumbItem[]>(() => {
    const matched = route.matched.filter((item) => item.meta?.title)
    const items: BreadcrumbItem[] = []

    matched.forEach((item, index) => {
      // 如果有父路由信息，先添加父路由
      if (item.meta?.parentPath && item.meta?.parentTitle) {
        // 检查是否已经添加过父路由
        const parentExists = items.some((b) => b.path === item.meta?.parentPath)
        if (!parentExists) {
          items.push({
            title: item.meta.parentTitle as string,
            path: item.meta.parentPath as string,
            isCurrent: false,
          })
        }
      }

      // 添加当前路由
      items.push({
        title: item.meta?.title as string,
        path: item.path,
        isCurrent: index === matched.length - 1,
      })
    })

    return items
  })

  function handleClick(item: BreadcrumbItem) {
    if (item.isCurrent || !item.path) return
    router.push(item.path)
  }
</script>

<template>
  <div class="breadcrumb-wrapper">
    <!-- <el-button v-if="canGoBack" class="back-btn" :icon="ArrowLeft" circle size="small" @click="goBack" /> -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-for="item in breadcrumbs"
        :key="item.path"
        :class="{ 'is-clickable': !item.isCurrent && item.path }"
        @click="handleClick(item)"
      >
        <span :class="{ 'current-title': item.isCurrent }">
          {{ item.title }}
        </span>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<style scoped lang="scss">
  .breadcrumb-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;
  }

  .back-btn {
    border: none;
    background: transparent;
    color: var(--admin-text-secondary);

    &:hover {
      background: rgba(255, 255, 255, 0.1);
      color: var(--admin-text-primary);
    }
  }

  :deep(.el-breadcrumb) {
    font-size: 14px;

    .el-breadcrumb__item {
      .el-breadcrumb__inner {
        color: var(--admin-text-secondary);
      }

      &.is-clickable {
        .el-breadcrumb__inner {
          cursor: pointer;
          transition: color 0.2s;

          &:hover {
            color: var(--el-color-primary);
          }
        }
      }

      &:last-child {
        .el-breadcrumb__inner {
          color: var(--admin-text-primary);
        }
      }
    }

    .el-breadcrumb__separator {
      color: var(--admin-text-secondary);
    }
  }

  .current-title {
    font-weight: 500;
  }
</style>
