export type PlacementHandoff = {
  flow: string
  brand_id?: string
  /** @deprecated use brand_id */
  persona_id?: string
  pain_tag_count?: number
  summary?: string
  next_route?: string
  needs_supplemental_expand?: boolean
  search_source_mode?: string
  dev_mode?: boolean
  job_id?: string
  template_type?: string
  received_at: number
}

const STORAGE_KEY = 'haixun.islander.handoff'
const MAX_AGE_MS = 30 * 60 * 1000

let memoryHandoff: PlacementHandoff | null = readStored()

function readStored(): PlacementHandoff | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return null
    const parsed = JSON.parse(raw) as PlacementHandoff
    if (!parsed?.received_at || Date.now() - parsed.received_at > MAX_AGE_MS) {
      localStorage.removeItem(STORAGE_KEY)
      return null
    }
    return parsed
  } catch {
    return null
  }
}

function persist(handoff: PlacementHandoff | null) {
  memoryHandoff = handoff
  try {
    if (!handoff) {
      localStorage.removeItem(STORAGE_KEY)
      return
    }
    localStorage.setItem(STORAGE_KEY, JSON.stringify(handoff))
  } catch {
    // ignore quota / private mode
  }
}

export function setPlacementHandoff(input: Omit<PlacementHandoff, 'received_at'>) {
  persist({
    ...input,
    received_at: Date.now(),
  })
}

export function getPlacementHandoff(): PlacementHandoff | null {
  if (memoryHandoff && Date.now() - memoryHandoff.received_at <= MAX_AGE_MS) {
    return memoryHandoff
  }
  const stored = readStored()
  memoryHandoff = stored
  return stored
}

export function clearPlacementHandoff() {
  persist(null)
}

export function formatPlacementHandoffContext(handoff: PlacementHandoff | null): string {
  if (!handoff) return ''
  if (handoff.flow === 'copy') {
    const lines = [
      '【近期爆款海巡交接】',
      handoff.summary ? `- 摘要：${handoff.summary}` : '',
      handoff.next_route ? `- 建議前往：${handoff.next_route}` : '',
    ].filter(Boolean)
    return lines.length > 1 ? lines.join('\n') : ''
  }
  if (handoff.flow !== 'placement') return ''
  const lines = [
    '【近期海巡交接】',
    handoff.summary ? `- 摘要：${handoff.summary}` : '',
    handoff.pain_tag_count !== undefined ? `- 痛點 tag 候選：${handoff.pain_tag_count}` : '',
    handoff.needs_supplemental_expand
      ? '- 痛點 tag 仍不足，可建議使用者執行 supplemental 擴展'
      : '',
    handoff.next_route ? `- 建議前往：${handoff.next_route}` : '',
    handoff.search_source_mode ? `- 海巡來源模式：${handoff.search_source_mode}` : '',
  ].filter(Boolean)
  return lines.join('\n')
}