<template>
  <v-col
    v-if="features.showBreadcrumb && breadcrumbBarVisible && !isMobile"
    class="d-flex align-center justify-space-between pr-2 pl-3 bg-surface"
  >
    <v-breadcrumbs class="ma-2 pa-0" density="compact" :items="breadcrumbItems">
      <template #prepend>
        <v-btn
          v-if="features.showFavorites && !showFavoritesBar"
          class="mr-2"
          color="primary"
          size="small"
          variant="outlined"
          @click="emit('toggle-favorites-bar', true)"
        >
          常用
        </v-btn>
      </template>
      <template #item="{ item }">
        <li class="d-flex align-center ga-1">
          <v-icon
            v-if="getBreadcrumbIcon(item)"
            class="mr-1"
            size="14"
            :icon="getBreadcrumbIcon(item)"
          />
          <span class="text-caption text-no-wrap">{{ getBreadcrumbTitle(item) }}</span>
        </li>
      </template>
      <template #divider>
        <v-icon color="primary-variant" size="12" :icon="mdiChevronRight" />
      </template>
    </v-breadcrumbs>
    <div class="page-actions">
      <slot name="breadcrumb-actions"></slot>
    </div>
  </v-col>
</template>

<script setup lang="ts">
import type { AdminLayoutBreadcrumbItem, AdminLayoutFeatures } from './types'
import { mdiChevronRight } from '@mdi/js'

interface Props {
  features?: AdminLayoutFeatures
  breadcrumbBarVisible?: boolean
  isMobile?: boolean
  breadcrumbItems?: AdminLayoutBreadcrumbItem[]
  showFavoritesBar?: boolean
}

withDefaults(defineProps<Props>(), {
  features: () => ({
    showThemeToggle: false,
    showFavorites: true,
    showBreadcrumb: true,
    showSearch: true,
    showToolbarActions: true,
    showUserInfo: true,
  }),
  breadcrumbBarVisible: true,
  isMobile: false,
  breadcrumbItems: () => [],
  showFavoritesBar: true,
})

const emit = defineEmits<{
  'toggle-favorites-bar': [value: boolean]
}>()

function getBreadcrumbItem(item: unknown): AdminLayoutBreadcrumbItem | null {
  if (typeof item !== 'object' || item === null) return null

  if ('title' in item) {
    return item as AdminLayoutBreadcrumbItem
  }

  const raw = (item as { raw?: unknown }).raw
  if (typeof raw !== 'object' || raw === null || !('title' in raw)) return null

  return raw as AdminLayoutBreadcrumbItem
}

function getBreadcrumbIcon(item: unknown) {
  return getBreadcrumbItem(item)?.icon
}

function getBreadcrumbTitle(item: unknown) {
  return getBreadcrumbItem(item)?.title ?? ''
}
</script>
