/** 云律视频咨询：iframe / web-view 内通知云律后端结束通话，并通知父页面（律师 PC 浮窗）释放状态 */

export function getCloudLawApiBase(explicitBase) {
  const base = String(explicitBase || '').trim().replace(/\/+$/, '')
  if (base) return base
  if (typeof window !== 'undefined' && window.location && window.location.origin) {
    return window.location.origin
  }
  return ''
}

export function resolveCloudLawApiUrl(path, apiBase) {
  const base = getCloudLawApiBase(apiBase)
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  return `${base}${normalizedPath}`
}

/**
 * 通知云律后端结束通话（律师端 /api/law/voiceCall，用户端 /api/applet/voiceConnection）
 */
export function notifyCloudLawBackendEnd(callId, role = 'law', apiBase = '', token = '') {
  if (!callId) return Promise.resolve(false)
  const endBase = String(role).toLowerCase() === 'law' ? '/api/law/voiceCall' : '/api/applet/voiceConnection'
  const url = resolveCloudLawApiUrl(`${endBase}/${encodeURIComponent(callId)}/end`, apiBase)
  const header = { 'Content-Type': 'application/json' }
  if (token) {
    header.token = token.startsWith('Bearer') ? token : `Bearer ${token}`
  }
  return new Promise(resolve => {
    uni.request({
      url,
      method: 'POST',
      data: {},
      header,
      timeout: 8000,
      complete: () => resolve(true)
    })
  })
}

/** PC 律师端 iframe 会议结束时，通知父页面（outbound 浮窗）清除「会议进行中」状态 */
export function notifyCloudLawParentCallEnded(callId = '') {
  if (typeof window === 'undefined') return false
  try {
    if (window.parent && window.parent !== window) {
      window.parent.postMessage({
        type: 'cloudLawCallEnded',
        action: 'cloudLawCallEnded',
        callId: String(callId || '')
      }, '*')
      return true
    }
  } catch (e) {
    console.warn('[cloudLawVoiceCall] parent postMessage failed', e)
  }
  return false
}

export function isCloudLawLawRoleInMeeting(role) {
  if (String(role || '').toLowerCase() === 'law') return true
  try {
    return typeof window !== 'undefined'
      && window.sessionStorage
      && window.sessionStorage.getItem('echo_cloud_law_meeting_role') === 'law'
  } catch (e) {
    return false
  }
}

export function isCloudLawPcIframe() {
  return typeof window !== 'undefined' && !!(window.parent && window.parent !== window)
}

/** 查询云律通话状态（律师端 /api/law/voiceCall，用户端 /api/applet/voiceConnection） */
export function queryCloudLawCallStatus(callId, role = 'law', apiBase = '', token = '') {
  if (!callId) return Promise.resolve(null)
  const endBase = String(role).toLowerCase() === 'law' ? '/api/law/voiceCall' : '/api/applet/voiceConnection'
  const url = resolveCloudLawApiUrl(`${endBase}/${encodeURIComponent(callId)}/status`, apiBase)
  const header = { 'Content-Type': 'application/json' }
  if (token) {
    header.token = token.startsWith('Bearer') ? token : `Bearer ${token}`
  }
  return new Promise(resolve => {
    uni.request({
      url,
      method: 'GET',
      header,
      timeout: 8000,
      success: (res) => {
        const body = res?.data || {}
        const payload = body.data !== undefined ? body.data : body
        resolve(payload && typeof payload === 'object' ? payload : null)
      },
      fail: () => resolve(null)
    })
  })
}

const CLOUD_LAW_HANGUP_QUERY = 'cloudLawHangup'

/** 小程序 web-view 内挂断：改 URL 触发原生页 @load，立即调 /end（不依赖 web-view 销毁） */
export function notifyNativeMiniProgramHangup() {
  // #ifdef H5
  if (typeof window === 'undefined') return false
  try {
    const mp = window.wx && window.wx.miniProgram
    if (!mp) return false
    const href = String(window.location.href || '')
    if (href.includes(`${CLOUD_LAW_HANGUP_QUERY}=1`)) return true
    const url = new URL(href)
    url.searchParams.set(CLOUD_LAW_HANGUP_QUERY, '1')
    window.location.replace(url.toString())
    return true
  } catch (e) {
    console.warn('[cloudLawVoiceCall] native hangup bridge failed', e)
  }
  // #endif
  return false
}

export function isCloudLawHangupBridgeUrl(url) {
  return String(url || '').includes(`${CLOUD_LAW_HANGUP_QUERY}=1`)
}
