const ACTIVE_BRAND_KEY = 'haixun.activeBrandId'
const ACTIVE_TOPIC_KEY = 'haixun.activeTopicId'
const REPLY_PERSONA_KEY = 'haixun.replyPersonaId'
export const BRAND_CHANGED_EVENT = 'haixun.brand-changed'
export const TOPIC_CHANGED_EVENT = 'haixun.topic-changed'
export const REPLY_PERSONA_CHANGED_EVENT = 'haixun.reply-persona-changed'

export function rememberBrandId(brandId: string) {
  const id = brandId.trim()
  if (!id) return
  try {
    sessionStorage.setItem(ACTIVE_BRAND_KEY, id)
    window.dispatchEvent(new CustomEvent(BRAND_CHANGED_EVENT, { detail: { id } }))
  } catch {
    // ignore
  }
}

export function getActiveBrandId(): string {
  try {
    return sessionStorage.getItem(ACTIVE_BRAND_KEY)?.trim() ?? ''
  } catch {
    return ''
  }
}

export function rememberTopicId(topicId: string) {
  const id = topicId.trim()
  if (!id) return
  try {
    sessionStorage.setItem(ACTIVE_TOPIC_KEY, id)
    window.dispatchEvent(new CustomEvent(TOPIC_CHANGED_EVENT, { detail: { id } }))
  } catch {
    // ignore
  }
}

export function getActiveTopicId(): string {
  try {
    return sessionStorage.getItem(ACTIVE_TOPIC_KEY)?.trim() ?? ''
  } catch {
    return ''
  }
}

export function rememberReplyPersonaId(personaId: string) {
  const id = personaId.trim()
  if (!id) return
  try {
    sessionStorage.setItem(REPLY_PERSONA_KEY, id)
    window.dispatchEvent(new CustomEvent(REPLY_PERSONA_CHANGED_EVENT, { detail: { id } }))
  } catch {
    // ignore
  }
}

export function getReplyPersonaId(): string {
  try {
    return sessionStorage.getItem(REPLY_PERSONA_KEY)?.trim() ?? ''
  } catch {
    return ''
  }
}