/**
 * assistant.html — 设置观看端显示的在线人数基数弹层
 * 业务对齐 live-web-operator src/pc/Index.vue（message-box setnumbox + setBaseNum / numChange / setNum）：
 * - 打开：互动工具「设置用户基数」data-interact-tool="user-base"
 * - 输入：仅数字，maxlength 8（与运营端 input 一致）
 * - 确定：非空校验后 DWLive.roomBaseUserCount(Number(n))（assistantsdk 经 Pusher 下发）
 * - 当前基数：随 DWLive.onRoomContext 的 roomSettings.room_base_user_count 更新（由 demo-boot 转发）
 */
;(function ($) {
  var state = {
    baseStr: '0'
  }

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

  function openModal() {
    var mask = document.getElementById('room-base-modal-mask')
    var inp = document.getElementById('room-base-input')
    if (!mask) return
    mask.classList.add('is-open')
    mask.setAttribute('aria-hidden', 'false')
    if (inp) {
      inp.value = state.baseStr
      try {
        inp.focus()
        inp.select()
      } catch (e) {}
    }
  }

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

  function sanitizeInput() {
    var inp = document.getElementById('room-base-input')
    if (!inp) return
    inp.value = String(inp.value || '').replace(/\D/g, '').slice(0, 8)
  }

  function confirm() {
    var inp = document.getElementById('room-base-input')
    var raw = $.trim((inp && inp.value) || '')
    if (raw === '') {
      window.alert('输入不能为空')
      return
    }
    if (typeof DWLive === 'undefined' || typeof DWLive.roomBaseUserCount !== 'function') {
      window.alert('当前环境不支持 DWLive.roomBaseUserCount')
      return
    }
    var n = Number(raw)
    DWLive.roomBaseUserCount(n)
    state.baseStr = String(n)
    closeModal()
  }

  window.DemoRoomBaseUserPanel_onRoomContext = function (res) {
    try {
      var rs = res && res.roomSettings
      if (!rs) return
      var v = rs.room_base_user_count
      if (v !== undefined && v !== null && v !== '') {
        state.baseStr = String(v).replace(/\D/g, '').slice(0, 8) || '0'
      }
      if (isOpen()) {
        var inp = document.getElementById('room-base-input')
        if (inp) inp.value = state.baseStr
      }
    } catch (e) {}
  }

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

    var mask = document.getElementById('room-base-modal-mask')
    var dlg = document.getElementById('room-base-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('room-base-modal-close')
    if (closeBtn) closeBtn.addEventListener('click', closeModal)

    var cancel = document.getElementById('room-base-cancel')
    if (cancel) cancel.addEventListener('click', closeModal)

    var ok = document.getElementById('room-base-ok')
    if (ok) ok.addEventListener('click', confirm)

    var inp = document.getElementById('room-base-input')
    if (inp) {
      inp.addEventListener('input', sanitizeInput)
    }

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

  function install() {
    if (!document.getElementById('room-base-modal-mask')) return
    bindUi()
  }

  $(install)
})(window.jQuery)
