/**
 * assistant.html — 广播发布弹层
 * 业务对齐 live-web-operator src/common/component/_broadcast/index.vue：
 * - 历史列表：DWLive.getBroadcastList({ success, fail })
 * - 发布：hdChat.releaseBroadcast(content)；成功清空输入并关闭弹层（与运营端一致）
 * - 删除：hdChat.removeBroadcast(id)
 * - IM 推送：hdChat.on('broadcastRelease'|'broadcastRemove')；观看端 DWLive.onBroadcastMsg / removeBroadcastMsg 与 live.js 链式合并
 */
;(function ($) {
  var state = {
    list: [],
    tipMsg: '暂无直播历史广播记录',
    hdchat: null,
    limit: 100
  }

  function escapeHtml(s) {
    if (s == null) return ''
    return String(s)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
  }

  function getLimit() {
    var h = state.hdchat
    if (h && h.options && h.options.account && h.options.account.broadcastCharNum) {
      return Number(h.options.account.broadcastCharNum) || 100
    }
    return 100
  }

  function isMaskOpen() {
    var m = document.getElementById('broadcast-modal-mask')
    return !!(m && m.classList.contains('is-open'))
  }

  function normalizeRow(d) {
    if (!d) return null
    return {
      id: d.id,
      createTime: d.createTime || d.time || '',
      publisherName: d.publisherName || d.username || '—',
      content: d.content != null ? String(d.content) : ''
    }
  }

  function renderHistory() {
    var ul = document.getElementById('broadcast-history-list')
    var empty = document.getElementById('broadcast-history-empty')
    if (!ul || !empty) return
    if (!state.list.length) {
      empty.textContent = state.tipMsg
      empty.style.display = 'block'
      ul.style.display = 'none'
      ul.innerHTML = ''
      return
    }
    empty.style.display = 'none'
    ul.style.display = 'block'
    var html = ''
    for (var i = 0; i < state.list.length; i++) {
      var it = state.list[i]
      if (!it || it.id == null) continue
      html +=
        '<li data-broadcast-id="' +
        escapeHtml(String(it.id)) +
        '"><span class="radio-time">' +
        escapeHtml(it.createTime) +
        '</span><span class="radio-name">发布者：' +
        escapeHtml(it.publisherName) +
        '</span><span class="radio-delete" role="button" tabindex="0">删除</span>' +
        '<p class="radio-content">' +
        escapeHtml(it.content) +
        '</p></li>'
    }
    ul.innerHTML = html
  }

  function fetchList() {
    state.tipMsg = '暂无直播历史广播记录'
    state.limit = getLimit()
    if (typeof DWLive === 'undefined' || typeof DWLive.getBroadcastList !== 'function') {
      state.list = []
      state.tipMsg = '当前 SDK 无 getBroadcastList'
      renderHistory()
      return
    }
    DWLive.getBroadcastList({
      success: function (rows) {
        state.list = Array.isArray(rows) ? rows.slice() : []
        renderHistory()
      },
      fail: function () {
        state.list = []
        state.tipMsg = '加载失败，请重新打开'
        renderHistory()
      }
    })
  }

  function openModal() {
    var mask = document.getElementById('broadcast-modal-mask')
    if (!mask) return
    mask.classList.add('is-open')
    mask.setAttribute('aria-hidden', 'false')
    var ta = document.getElementById('broadcast-textarea')
    if (ta) ta.value = ''
    updateCount()
    fetchList()
    if (ta) {
      try {
        ta.focus()
      } catch (e) {}
    }
  }

  function closeModal() {
    var mask = document.getElementById('broadcast-modal-mask')
    if (!mask) return
    mask.classList.remove('is-open')
    mask.setAttribute('aria-hidden', 'true')
  }

  function updateCount() {
    state.limit = getLimit()
    var ta = document.getElementById('broadcast-textarea')
    var c = document.getElementById('broadcast-char-count')
    if (ta) ta.setAttribute('maxlength', String(state.limit))
    if (c && ta) {
      c.textContent = String((ta.value || '').length) + '/' + state.limit
    }
  }

  function runAsync(p, ok, fail) {
    if (!p) {
      if (fail) fail('无返回')
      return
    }
    if (typeof p.then === 'function') {
      p.then(ok).catch(function (e) {
        if (fail) fail(e)
      })
      return
    }
    if (typeof p.done === 'function') {
      p.done(ok).fail(function (e) {
        if (fail) fail(e)
      })
    }
  }

  function publish() {
    var ta = document.getElementById('broadcast-textarea')
    var text = $.trim((ta && ta.value) || '')
    if (!text) {
      window.alert('内容不能为空')
      return
    }
    if (!state.hdchat) {
      window.alert('请先登录并初始化 hdChat')
      return
    }
    var ret = state.hdchat.releaseBroadcast(text)
    if (ret === false) {
      window.alert('发布失败：内容为空或超过字数限制（最多 ' + state.limit + ' 字）')
      return
    }
    runAsync(
      ret,
      function () {
        if (ta) ta.value = ''
        updateCount()
        closeModal()
      },
      function (err) {
        window.alert((err && (err.message || err.msg || String(err))) || '发布失败，请重试')
      }
    )
  }

  function deleteById(id) {
    if (!state.hdchat) return
    if (!window.confirm('确定删除该广播？')) return
    var ret = state.hdchat.removeBroadcast(id)
    runAsync(
      ret,
      function () {
        state.list = state.list.filter(function (x) {
          return String(x.id) !== String(id)
        })
        if (!state.list.length) state.tipMsg = '暂无直播历史广播记录'
        renderHistory()
      },
      function (err) {
        window.alert((err && (err.message || err.msg || String(err))) || '删除失败，请重试')
      }
    )
  }

  function onImBroadcastRelease(d) {
    var row = normalizeRow(d)
    if (!row || row.id == null) return
    for (var i = 0; i < state.list.length; i++) {
      if (String(state.list[i].id) === String(row.id)) return
    }
    state.list.unshift(row)
    if (isMaskOpen()) renderHistory()
  }

  function onImBroadcastRemove(d) {
    var id = d && d.id
    if (id == null) return
    state.list = state.list.filter(function (x) {
      return String(x.id) !== String(id)
    })
    if (!state.list.length) state.tipMsg = '暂无直播历史广播记录'
    if (isMaskOpen()) renderHistory()
  }

  function onSdkBroadcastMsg(data) {
    var row = normalizeRow(data)
    if (!row || row.id == null) return
    for (var j = 0; j < state.list.length; j++) {
      if (String(state.list[j].id) === String(row.id)) return
    }
    state.list.unshift(row)
    if (isMaskOpen()) renderHistory()
  }

  function onSdkRemoveBroadcastMsg(data) {
    var id = data && data.id
    if (id == null) return
    state.list = state.list.filter(function (x) {
      return String(x.id) !== String(id)
    })
    if (!state.list.length) state.tipMsg = '暂无直播历史广播记录'
    if (isMaskOpen()) renderHistory()
  }

  function chainDwLive(name, handler) {
    if (typeof DWLive === 'undefined') return
    var prev = DWLive[name]
    DWLive[name] = function () {
      var args = arguments
      if (typeof prev === 'function') {
        try {
          prev.apply(DWLive, args)
        } catch (e1) {}
      }
      try {
        handler.apply(null, args)
      } catch (e2) {
        console.warn('DemoBroadcast.' + name, e2)
      }
    }
  }

  function bindUi() {
    document.addEventListener('click', function (e) {
      var t = e.target
      if (!t || !t.closest) return
      var openBtn = t.closest('[data-interact-tool="broadcast"]')
      if (openBtn) {
        e.preventDefault()
        openModal()
      }
    })

    var mask = document.getElementById('broadcast-modal-mask')
    var dlg = document.getElementById('broadcast-modal-dialog')
    if (mask) {
      mask.addEventListener('click', function (e) {
        if (e.target === mask) closeModal()
      })
    }
    if (dlg) {
      dlg.addEventListener('click', function (e) {
        e.stopPropagation()
      })
    }

    var closeBtn = document.getElementById('broadcast-modal-close')
    if (closeBtn) closeBtn.addEventListener('click', closeModal)

    var pub = document.getElementById('broadcast-publish')
    if (pub) pub.addEventListener('click', publish)

    var ta = document.getElementById('broadcast-textarea')
    if (ta) {
      ta.addEventListener('input', updateCount)
    }

    var ul = document.getElementById('broadcast-history-list')
    if (ul) {
      ul.addEventListener('click', function (e) {
        var del = e.target && e.target.closest && e.target.closest('.radio-delete')
        if (!del) return
        var li = del.closest('li[data-broadcast-id]')
        if (!li) return
        var id = li.getAttribute('data-broadcast-id')
        if (id) deleteById(id)
      })
    }

    document.addEventListener('keydown', function (e) {
      if (e.keyCode !== 27) return
      if (isMaskOpen()) closeModal()
    })
  }

  window.DemoBroadcastPanel_attachHdchat = function (hdchat) {
    if (!hdchat) return
    state.hdchat = hdchat
    state.limit = getLimit()
    if (!hdchat._demoBroadcastPanelBound) {
      hdchat._demoBroadcastPanelBound = true
      hdchat.on('broadcastRelease', onImBroadcastRelease)
      hdchat.on('broadcastRemove', onImBroadcastRemove)
    }
  }

  function install() {
    if (!document.getElementById('broadcast-modal-mask')) return
    bindUi()
    chainDwLive('onBroadcastMsg', onSdkBroadcastMsg)
    chainDwLive('removeBroadcastMsg', onSdkRemoveBroadcastMsg)
  }

  $(install)
})(window.jQuery)
