/** 云律小程序 web-view 内与原生壳通信（返回会议浮窗 / 挂断） */

export function getMiniProgram() {
  return typeof window !== 'undefined' && window.wx && window.wx.miniProgram ? window.wx.miniProgram : null
}

export function isCloudLawEmbed() {
  try {
    return typeof window !== 'undefined'
      && !!window.sessionStorage
      && window.sessionStorage.getItem('echo_cloud_law_meeting_embed') === '1'
  } catch (e) {
    return false
  }
}

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

/** 律师端返回上一页：会议仍在进行，通知小程序弹出「返回会议」浮窗 */
export function minimizeCloudLawMeeting(callId = '') {
  const mp = getMiniProgram()
  if (!isCloudLawEmbed() || !mp) return false
  try {
    if (typeof mp.postMessage === 'function') {
      mp.postMessage({
        data: {
          type: 'cloudLawMinimized',
          action: 'cloudLawMinimized',
          callId: String(callId || '')
        }
      })
    }
  } catch (e) {
    console.warn('[cloudLawMiniProgram] minimize postMessage failed', e)
  }
  try {
    if (typeof mp.navigateBack === 'function') {
      mp.navigateBack({ delta: 1 })
      return true
    }
  } catch (e) {
    console.warn('[cloudLawMiniProgram] minimize navigateBack failed', e)
  }
  return false
}

/** 会议真正结束：通知小程序释放占用 */
export function notifyCloudLawCallEnded(callId = '') {
  const mp = getMiniProgram()
  if (!mp) return false
  try {
    if (typeof mp.postMessage === 'function') {
      mp.postMessage({
        data: {
          type: 'cloudLawCallEnded',
          action: 'cloudLawCallEnded',
          callId: String(callId || '')
        }
      })
    }
  } catch (e) {
    console.warn('[cloudLawMiniProgram] ended postMessage failed', e)
  }
  try {
    if (typeof mp.navigateBack === 'function') {
      mp.navigateBack({ delta: 1 })
      return true
    }
  } catch (e) {
    console.warn('[cloudLawMiniProgram] ended navigateBack failed', e)
  }
  return false
}
