export type ExtensionSyncResult = {
  success?: boolean
  valid?: boolean
  synced?: boolean
  message?: string
  username?: string
  account_id?: string
}

export function isExtensionBridgePresent() {
  return document.documentElement.dataset.haixunExtension === '1'
}

export function normalizeExtensionSyncResult(raw: ExtensionSyncResult): ExtensionSyncResult {
  const nested =
    raw && typeof (raw as { data?: ExtensionSyncResult }).data === 'object'
      ? ((raw as { data?: ExtensionSyncResult }).data as ExtensionSyncResult)
      : null

  const payload = nested ?? raw
  return {
    success: payload.success !== false,
    valid: payload.valid !== false,
    synced: payload.synced ?? true,
    message: payload.message,
    username: payload.username,
    account_id: payload.account_id,
  }
}

export function pingExtensionBridge() {
  window.postMessage({ type: 'HAIXUN_PING_EXTENSION' }, '*')
}

export function waitForExtensionBridge(timeoutMs = 8000): Promise<boolean> {
  if (isExtensionBridgePresent()) return Promise.resolve(true)

  return new Promise((resolve) => {
    const started = Date.now()

    const onMessage = (event: MessageEvent) => {
      if (event.source !== window) return
      if (event.data?.type !== 'HAIXUN_EXTENSION_READY') return
      cleanup()
      resolve(true)
    }

    const timer = window.setInterval(() => {
      pingExtensionBridge()
      if (isExtensionBridgePresent()) {
        cleanup()
        resolve(true)
        return
      }
      if (Date.now() - started >= timeoutMs) {
        cleanup()
        resolve(false)
      }
    }, 500)

    function cleanup() {
      window.removeEventListener('message', onMessage)
      window.clearInterval(timer)
    }

    window.addEventListener('message', onMessage)
    pingExtensionBridge()
  })
}

export function requestExtensionSync(input: {
  accountId: string
  accessToken: string
  serverUrl: string
}): Promise<ExtensionSyncResult> {
  return new Promise((resolve, reject) => {
    const timeout = window.setTimeout(() => {
      window.removeEventListener('message', onMessage)
      reject(
        new Error(
          '等待 Chrome 擴充回應逾時。請確認已載入 extension/haixun-threads-sync 並重新整理此頁',
        ),
      )
    }, 30000)

    function onMessage(event: MessageEvent) {
      if (event.source !== window) return
      if (event.data?.type !== 'HAIXUN_THREADS_SYNC_RESULT') return
      window.clearTimeout(timeout)
      window.removeEventListener('message', onMessage)
      resolve(normalizeExtensionSyncResult(event.data as ExtensionSyncResult))
    }

    window.addEventListener('message', onMessage)
    window.postMessage(
      {
        type: 'HAIXUN_REQUEST_THREADS_SYNC',
        serverUrl: input.serverUrl,
        accountId: input.accountId,
        accessToken: input.accessToken,
        apiVersion: 'go-v1',
      },
      '*',
    )
  })
}