<template>
  <div class="app-header">
    <div class="header-left">
      <n-button
        quaternary
        circle
        @click="$emit('toggle-sidebar')"
        class="sidebar-toggle"
      >
        <template #icon>
          <Icon icon="tabler:menu-2" />
        </template>
      </n-button>
      
      <n-breadcrumb class="breadcrumb">
        <n-breadcrumb-item>
          <router-link to="/">{{ appName }}</router-link>
        </n-breadcrumb-item>
        <template v-for="(item, index) in breadcrumbItems" :key="index">
          <n-breadcrumb-item v-if="item.href">
            <router-link :to="item.href">{{ item.label }}</router-link>
          </n-breadcrumb-item>
          <n-breadcrumb-item v-else>
            {{ item.label }}
          </n-breadcrumb-item>
        </template>
      </n-breadcrumb>
    </div>

    <div class="header-right">
      <n-space>
        <!-- 搜索框 - 使用Naive UI的响应式属性，仅System User显示 -->
        <n-input
          v-if="isSystemUser"
          v-model:value="searchQuery"
          :placeholder="t('Search...')"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
          @clear="handleSearchClear"
        >
          <template #prefix>
            <Icon icon="tabler:search" />
          </template>
        </n-input>

        <!-- 通知 -->
        <n-button quaternary circle>
          <template #icon>
            <Icon icon="tabler:bell" />
          </template>
        </n-button>

        <!-- 用户菜单 -->
        <UserMenu />
      </n-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { NButton, NBreadcrumb, NBreadcrumbItem, NSpace, NInput } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { useAuthStore } from '../../shared/stores/auth'
import { t } from '../../shared/i18n'
import UserMenu from '../../shared/components/UserMenu.vue'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 搜索相关状态
const searchQuery = ref('')

// 从 localStorage 读取应用名称
const appName = computed(() => localStorage.getItem('appName') || 'Jingrow')

const isSystemUser = computed(() => authStore.user?.user_type === 'System User')

// 将路径段转换为可读标签
function pathSegmentToLabel(segment: string): string {
  // 将 kebab-case 或 snake_case 转换为标题格式
  return segment
    .split(/[-_]/)
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(' ')
}

// 从路由路径自动生成面包屑
function generateBreadcrumbFromPath(path: string): Array<{ label: string; href?: string }> {
  const items: Array<{ label: string; href?: string }> = []
  const segments = path.split('/').filter(Boolean)
  
  // 构建路径前缀，用于生成 href
  let currentPath = ''
  
  segments.forEach((segment, index) => {
    currentPath += `/${segment}`
    const isLast = index === segments.length - 1
    
    // 特殊处理：tools 路径
    if (segment === 'tools') {
      items.push({
        label: t('Tools'),
        href: isLast ? undefined : currentPath
      })
    } else {
      // 对于最后一项，不添加链接
      items.push({
        label: pathSegmentToLabel(segment),
        href: isLast ? undefined : currentPath
      })
    }
  })
  
  return items
}

const breadcrumbItems = computed(() => {
  const items: Array<{ label: string; href?: string }> = []
  
  // 优先检查路由 meta 中的 toolName（工具路由）
  if (route.meta?.toolName) {
    // 工具路由：显示 Tools / 工具名称
    // 自动解析 Tools 路由的路径（用于面包屑链接）
    let toolsPath = '/tools'
    try {
      const resolved = router.resolve({ name: 'Tools' })
      if (resolved.matched.length > 0) {
        toolsPath = resolved.path
      }
    } catch {
      // 解析失败，使用默认值
    }
    items.push({
      label: t('Tools'),
      href: toolsPath
    })
    // 使用 meta.toolName（工具的显示名称）
    const toolLabel = route.meta.toolName as string
    if (toolLabel) {
      items.push({
        label: toolLabel
      })
    }
    return items
  }
  
  // 根据路由名称和参数生成面包屑
  if (route.name === 'PageTypeList') {
    const entity = route.params.entity as string
    if (entity) {
      items.push({
        label: entity,
        href: `/app/${entity}`
      })
    }
  } else if (route.name === 'PageTypeDetail') {
    const entity = route.params.entity as string
    const id = route.params.id as string
    if (entity) {
      items.push({
        label: entity,
        href: `/app/${entity}`
      })
    }
    if (id && id !== 'new') {
      items.push({
        label: id === 'new' ? t('Create') : id
      })
    }
  } else if (route.name === 'WorkspacePage') {
    const name = route.params.name as string
    if (name) {
      items.push({
        label: pathSegmentToLabel(name)
      })
    }
  } else {
    // 其他页面的标题映射（保留向后兼容）
    const map: Record<string, string> = {
      Dashboard: t('Dashboard'),
      AgentList: t('Agents'),
      AgentDetail: t('Agent Detail'),
      NodeList: t('Node Management'),
      NodeDetail: t('Node Detail'),
      LocalJobList: t('Local Jobs'),
      LocalJobDetail: t('Local Job Detail'),
      FlowBuilder: t('Flow Builder'),
      ScheduledJobList: t('Scheduled Jobs'),
      ScheduledJobDetail: t('Scheduled Job Detail'),
      MenuManager: t('Menu Manager'),
      Settings: t('Settings'),
      SearchResults: t('Search Results')
    }
    const title = map[route.name as string]
    
    if (title) {
      items.push({ label: title })
    } else {
      // 如果没有匹配的标题，尝试从路径自动生成
      // 排除根路径和已知的特殊路径
      if (route.path !== '/' && !route.path.startsWith('/app/') && !route.path.startsWith('/page/')) {
        const pathItems = generateBreadcrumbFromPath(route.path)
        if (pathItems.length > 0) {
          items.push(...pathItems)
        } else {
          // 最后的后备方案：使用路由名称
          const routeName = route.name as string
          if (routeName) {
            items.push({ label: pathSegmentToLabel(routeName) })
          }
        }
      }
    }
  }
  
  return items
})


// 搜索处理函数
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    router.push({
      name: 'SearchResults',
      query: { q: searchQuery.value.trim() }
    })
  }
}

const handleSearchClear = () => {
  searchQuery.value = ''
}
</script>

<style scoped>
.app-header {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  background: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  min-width: 0; /* 允许flex子项收缩 */
}

.header-right {
  display: flex;
  align-items: center;
  min-width: 0; /* 允许flex子项收缩 */
}


/* 搜索框响应式样式 */
.search-input {
  width: 280px;
}

/* 面包屑响应式样式 */
.breadcrumb {
  min-width: 0; /* 允许收缩 */
}

/* 平板端样式 (768px - 1024px) */
@media (max-width: 1024px) {
  .app-header {
    padding: 0 16px;
  }
  
  .search-input {
    width: 200px;
  }
  
  .header-left {
    gap: 12px;
  }
}

/* 移动端样式 (最大768px) */
@media (max-width: 768px) {
  .app-header {
    padding: 0 12px;
  }
  
  .header-left {
    gap: 8px;
  }
  
  /* 移动端隐藏面包屑 */
  .breadcrumb {
    display: none;
  }
  
  /* 移动端隐藏搜索框 */
  .search-input {
    display: none;
  }
  
  /* 移动端隐藏用户名文字 */
  .username {
    display: none;
  }
  
  /* 移动端调整按钮间距 */
  .header-right :deep(.n-space) {
    gap: 4px;
  }
}

/* 小屏移动端样式 (最大480px) */
@media (max-width: 480px) {
  .app-header {
    padding: 0 8px;
  }
  
  .header-left {
    gap: 4px;
  }
  
  /* 小屏移动端进一步压缩间距 */
  .header-right :deep(.n-space) {
    gap: 2px;
  }
}
</style>
