/**
 * iframe postMessage 通信�?
 * 封装 H5 与企业父页面的双向通信
 */
import config from './config'
// const VITE_CREATE_POST_MESSAGE_URL = import.meta.env.VITE_CREATE_POST_MESSAGE_URL;
const VITE_CREATE_POST_MESSAGE_URL = location.origin;
const SOURCE = 'leai-creation'
const VERSION = 1
const TIMEOUT = 30000

const pendingCallbacks = new Map()

export const isEmbedded = config.isEmbedded

// 目标 origin：配置了白名单用第一个，未配置用 '*'
const targetOrigin = config.parentOrigins.length > 0 ? config.parentOrigins[0] : '*'

export function send(type, payload = {}) {
  if (!isEmbedded) return
  window.parent.postMessage({ source: SOURCE, version: VERSION, type, payload }, VITE_CREATE_POST_MESSAGE_URL)
}
export function request(type, payload = {}) {
  if (!isEmbedded) return Promise.reject(new Error('Not in iframe'))
  const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8)
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      pendingCallbacks.delete(messageId)
      reject(new Error('TIMEOUT'))
    }, TIMEOUT)
    pendingCallbacks.set(messageId, { resolve, reject, timer })
    send(type, { ...payload, messageId })
  })
}

export function requestTokenRefresh() {
  return request('TOKEN_EXPIRED')
}

function onMessage(event) {
  if (event.origin !== VITE_CREATE_POST_MESSAGE_URL) {
    console.log('event.origin', event.origin);
    return
  }
  console.log('onMessage', event);
  if (config.parentOrigins.length > 0 && !config.parentOrigins.includes(event.origin)) {
    return
  }
  const msg = event.data
  if (!msg || msg.source !== SOURCE) return

  switch (msg.type) {
    case 'TOKEN_REFRESHED': {
      const messageId = msg.payload?.messageId
      const cb = pendingCallbacks.get(messageId)
      if (cb) {
        clearTimeout(cb.timer)
        pendingCallbacks.delete(messageId)
        cb.resolve(msg.payload)
      }
      break
    }
    case 'INIT': {
      if (msg.payload?.token && window.__LEAI_INIT_CALLBACK__) {
        window.__LEAI_INIT_CALLBACK__(msg.payload)
      }
      break
    }
  }
}

if (isEmbedded) {
  window.addEventListener('message', onMessage)
}

export default { isEmbedded, send, request, requestTokenRefresh }
