const scriptPromises = new Map()

function normalizeBaseUrl(value) {
  return String(value || '').replace(/\/$/, '')
}

export function buildOnlyOfficeScriptUrl(documentServerUrl) {
  return `${normalizeBaseUrl(documentServerUrl)}/web-apps/apps/api/documents/api.js`
}

export function loadOnlyOfficeApi(documentServerUrl) {
  const scriptUrl = buildOnlyOfficeScriptUrl(documentServerUrl)
  if (typeof window === 'undefined') {
    return Promise.reject(new Error('ONLYOFFICE 只能在浏览器环境中加载。'))
  }

  if (window.DocsAPI?.DocEditor) {
    return Promise.resolve(window.DocsAPI)
  }

  if (scriptPromises.has(scriptUrl)) {
    return scriptPromises.get(scriptUrl)
  }

  const promise = new Promise((resolve, reject) => {
    const existing = document.querySelector(`script[src="${scriptUrl}"]`)
    if (existing) {
      existing.addEventListener('load', () => resolve(window.DocsAPI), { once: true })
      existing.addEventListener('error', () => reject(new Error('ONLYOFFICE 脚本加载失败。')), { once: true })
      return
    }

    const script = document.createElement('script')
    script.src = scriptUrl
    script.async = true
    script.onload = () => resolve(window.DocsAPI)
    script.onerror = () => reject(new Error('ONLYOFFICE 脚本加载失败。'))
    document.head.appendChild(script)
  })

  scriptPromises.set(scriptUrl, promise)
  return promise
}
