const DEFAULT_TENCENT_MAP_LIBRARIES = 'visualization,geometry,vector,tools,service'

let mapScriptPromise: Promise<void> | null = null
let scriptLoading = false
const pendingResolvers: Array<() => void> = []

export const loadTencentMapScript = (apiKey: string, libraries = DEFAULT_TENCENT_MAP_LIBRARIES) => {
  const w = window as unknown as { TMap?: unknown } & Record<string, unknown>
  if (w.TMap) return Promise.resolve()
  if (mapScriptPromise) return mapScriptPromise
  mapScriptPromise = new Promise((resolve, reject) => {
    pendingResolvers.push(resolve)
    if (scriptLoading) return
    scriptLoading = true
    const callbackName = '__tencentMapInit'
    if (!w[callbackName]) {
      w[callbackName] = () => {
        scriptLoading = false
        const queue = pendingResolvers.splice(0, pendingResolvers.length)
        queue.forEach((fn) => fn())
      }
    }
    const script = document.createElement('script')
    const libParam = libraries?.trim()
    script.src = libParam
      ? `https://map.qq.com/api/gljs?v=1.exp&key=${apiKey}&libraries=${libParam}&callback=${callbackName}`
      : `https://map.qq.com/api/gljs?v=1.exp&key=${apiKey}&callback=${callbackName}`
    script.type = 'text/javascript'
    script.async = true
    script.defer = true
    script.onerror = () => {
      scriptLoading = false
      mapScriptPromise = null
      pendingResolvers.length = 0
      reject(new Error('Tencent map script load failed'))
    }
    document.body.appendChild(script)
  })
  return mapScriptPromise
}

export { DEFAULT_TENCENT_MAP_LIBRARIES }
