<script setup lang="ts">
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'

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 && !item.meta?.hidden)

  return matched.map((item, index) => ({
    title: item.meta?.title as string,
    path: item.path,
    isCurrent: index === matched.length - 1
  }))
})

const canGoBack = computed(() => {
  return window.history.length > 1
})

function goBack() {
  router.back()
}

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>
