export type PlacementFlowStepKey = 'research' | 'outreach' | 'matrix'

export type WorkflowKind = 'copy' | 'placement'

export type PlacementFlowStep = {
  key: PlacementFlowStepKey
  step: string
  label: string
  shortLabel: string
  desc: string
  path: string
}

/** 流程 B（產品獲客）子步驟 — 主題列表在 /placement/topics */
export const PLACEMENT_FLOW: PlacementFlowStep[] = [
  {
    key: 'research',
    step: '01',
    label: '置入研究',
    shortLabel: '研究',
    desc: '研究地圖、知識圖譜、置入海巡',
    path: '/research',
  },
  {
    key: 'outreach',
    step: '02',
    label: '找 TA 留言',
    shortLabel: '留言',
    desc: '置入海巡結果、獲客留言草稿',
    path: '/outreach',
  },
]

export function detectPlacementFlowStep(pathname: string): PlacementFlowStepKey | null {
  if (pathname === '/research' || pathname.startsWith('/research/')) return 'research'
  if (pathname === '/outreach' || pathname.startsWith('/outreach/')) return 'outreach'
  if (pathname === '/placement/topics' || pathname.startsWith('/placement/')) return 'research'
  return null
}

export function detectActiveWorkflow(pathname: string): WorkflowKind | null {
  if (pathname === '/matrix' || pathname.startsWith('/matrix/')) return 'copy'
  if (detectPlacementFlowStep(pathname)) return 'placement'
  return null
}

export function isPlacementFlowPath(pathname: string): boolean {
  return detectPlacementFlowStep(pathname) !== null
}

import { topicResearchMapPath } from './placementTopics'

/** 流程 B 子步驟用主題 id（新）；相容舊書籤 ?brand= */
export function topicIdFromSearch(search: string): string {
  const params = new URLSearchParams(search)
  return params.get('topic')?.trim() ?? params.get('brand')?.trim() ?? ''
}

/** 流程 A / 舊品牌研究頁仍用 ?brand= */
export function brandIdFromSearch(search: string): string {
  return new URLSearchParams(search).get('brand')?.trim() ?? ''
}

export type PlacementFlowScope = 'topic' | 'brand'

export function placementFlowPath(
  path: string,
  scopeId?: string,
  scope: PlacementFlowScope = 'topic',
): string {
  const id = scopeId?.trim()
  if (!id) return path
  if (scope === 'brand') {
    return `${path}?brand=${encodeURIComponent(id)}`
  }
  if (path === '/research' || path.startsWith('/research/')) {
    return topicResearchMapPath(id)
  }
  return `${path}?topic=${encodeURIComponent(id)}`
}
