import { computed } from 'vue'

// Global slug -> PageType mapping (same as legacy jingrow.router.routes)
// Built from user's can_read list at startup
const slugToPageTypeMap: Record<string, string> = {}

/**
 * Initialize the slug -> PageType mapping from user's can_read list
 * This should be called once at app startup, same as legacy jingrow.router.setup()
 */
export function initSlugMapping(canReadList: string[]): void {
  // Clear existing mapping
  Object.keys(slugToPageTypeMap).forEach(key => delete slugToPageTypeMap[key])
  
  // Build mapping: slug -> PageType
  // slug conversion: lowercase + replace spaces with dashes
  for (const pagetype of canReadList) {
    const slug = pagetype.toLowerCase().replace(/ /g, '-')
    slugToPageTypeMap[slug] = pagetype
  }
}

/**
 * Add a single PageType to the mapping
 * Useful for dynamically loaded PageTypes
 */
export function registerPageTypeSlug(pagetype: string): void {
  if (!pagetype) return
  const slug = pagetype.toLowerCase().replace(/ /g, '-')
  slugToPageTypeMap[slug] = pagetype
}

/**
 * Convert URL slug to PageType name
 * Uses lookup table first (accurate), falls back to algorithm (best effort)
 */
export function slugToPageType(slug: string): string {
  if (!slug) return ''
  
  // Lookup from mapping table (accurate)
  if (slugToPageTypeMap[slug]) {
    return slugToPageTypeMap[slug]
  }
  
  // Fallback: algorithm conversion (best effort for unknown PageTypes)
  return slug
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
}

/**
 * Convert PageType name to URL slug
 */
export function pageTypeToSlug(pageType: string): string {
  if (!pageType) return ''
  return pageType.toLowerCase().replace(/ /g, '-')
}

// URL参数处理组合式函数
export function usePageTypeSlug(route: any) {
  const pagetypeSlug = computed(() => (route.params.entity as string) || '')
  const entity = computed(() => slugToPageType(pagetypeSlug.value))
  
  return {
    pagetypeSlug,
    entity
  }
}
