import { state } from './composables/useOverlayState'

function parseArg(data: any) {
  return typeof data === 'string' ? JSON.parse(data) : data
}

// JSON 去重：相同数据不触发 Vue 重渲染
const lastJSON = new Map<string, string>()
function shouldUpdate(key: string, data: any): boolean {
  const json = JSON.stringify(data)
  if (lastJSON.get(key) === json) return false
  lastJSON.set(key, json)
  return true
}

export function registerGoBridge() {
  const w = window as any

  w.updateHoroscopeFromGo = (data: any) => {
    const parsed = parseArg(data)
    if (shouldUpdate('horoscope', parsed)) state.horoscope = parsed
  }

  w.updateAINewsFromGo = (items: any) => {
    const parsed = parseArg(items)
    if (parsed?.length && shouldUpdate('ainews', parsed)) state.aiNews = parsed
  }

  w.updateKnowledgeFromGo = (data: any) => {
    const parsed = parseArg(data)
    if (shouldUpdate('knowledge', parsed)) state.knowledge = parsed
  }

  w.updateWeatherFromGo = (data: any) => {
    const parsed = parseArg(data)
    if (shouldUpdate('weather', parsed)) state.weather = parsed
  }

  w.updatePhotoFromGo = (data: any) => {
    const parsed = parseArg(data)
    if (parsed?.src && shouldUpdate('photo', parsed)) state.photo = parsed
  }

  w.setCardVisible = (card: string, visible: boolean) => {
    if (card in state.cardVisibility) {
      (state.cardVisibility as any)[card] = visible
    }
  }

  w.setWallpaperVisible = (visible: boolean) => {
    state.wallpaperVisible = visible
  }

  w.setPhotoFrameMode = (enabled: boolean) => {
    state.photoFrameMode = enabled
  }

  w.setShowSeconds = (v: boolean) => {
    state.showSeconds = v
  }

  Object.defineProperty(w, 'userZodiac', {
    set(v: string) { state.userZodiac = v },
    get() { return state.userZodiac },
  })

  w.__updateBackgroundHtml = (html: string) => {
    state.backgroundHtml = html
  }

  // 音频可视化：频率数据直接写入 window，不经过 Vue reactive
  w.updateAudioDataFromGo = (data: any) => {
    const parsed = parseArg(data)
    if (Array.isArray(parsed)) {
      ;(window as any).__audioBins = parsed
    }
  }
}
