let eventSource = null
let translationCallback = null

/**
 * 连接 SSE 翻译推送流
 * @param {Function} onTranslation - 翻译结果回调
 */
export function connectSSE(onTranslation) {
  translationCallback = onTranslation

  // 关闭旧连接
  disconnectSSE()

  eventSource = new EventSource('/api/translations/stream')

  eventSource.addEventListener('translation', (event) => {
    try {
      const data = JSON.parse(event.data)
      if (translationCallback) {
        translationCallback(data)
      }
    } catch (_e) {
      // 解析失败静默忽略
    }
  })

  eventSource.onerror = () => {
    // EventSource 会自动重连
  }
}

/**
 * 断开 SSE
 */
export function disconnectSSE() {
  if (eventSource) {
    eventSource.close()
    eventSource = null
  }
}
