import { hasResearchMap, type PlacementTopicData } from '../types/placementTopic'

export function sortPlacementTopics(items: PlacementTopicData[]): PlacementTopicData[] {
  return [...items].sort((a, b) => (b.update_at ?? 0) - (a.update_at ?? 0))
}

export function topicTitle(item: PlacementTopicData): string {
  const name = item.topic_name?.trim()
  if (name) return name
  const seed = item.seed_query?.trim()
  if (seed) return seed
  const brief = item.brief?.trim()
  if (brief) return brief.length > 48 ? `${brief.slice(0, 48)}…` : brief
  return item.brand_display_name?.trim() || '未命名主題'
}

export function topicSeedLabel(item: PlacementTopicData): string {
  return item.seed_query?.trim() || ''
}

export function topicOptionLabel(item: PlacementTopicData): string {
  const title = topicTitle(item)
  const seed = topicSeedLabel(item)
  if (!seed || seed === title) return title
  return `${title}｜種子：${seed}`
}

export function topicSearchText(item: PlacementTopicData): string {
  return [
    item.topic_name,
    item.seed_query,
    item.brief,
    item.brand_display_name,
    topicTitle(item),
  ]
    .map((value) => value?.trim())
    .filter(Boolean)
    .join(' ')
    .toLowerCase()
}

export function topicSettingsPath(topicId: string): string {
  return `/placement/topics/${encodeURIComponent(topicId)}`
}

export function topicResearchMapPath(topicId: string): string {
  return `/placement/topics/${encodeURIComponent(topicId)}/research-map`
}

export { hasResearchMap }
