/**
 * Jessibuca视频播放器插件
 * 用于初始化Jessibuca所需的脚本和依赖
 */

function loadJessibucaScript() {
  return new Promise((resolve, reject) => {
    if (typeof window === 'undefined') {
      return reject(new Error('非浏览器环境，无法加载Jessibuca'))
    }

    if (window.Jessibuca) {
      return resolve(window.Jessibuca)
    }

    const script = document.createElement('script')
    script.src = './static/js/jessibuca/jessibuca.js' // 修改路径为相对路径
    script.async = true

    script.onload = () => {
      console.log('Jessibuca脚本加载成功')
      resolve(window.Jessibuca)
    }

    script.onerror = (error) => {
      console.error('Jessibuca脚本加载失败:', error)
      // 尝试使用备用路径
      const backupScript = document.createElement('script')
      backupScript.src = '/static/js/jessibuca/jessibuca.js' 
      backupScript.async = true
      
      backupScript.onload = () => {
        console.log('Jessibuca备用脚本加载成功')
        resolve(window.Jessibuca)
      }
      
      backupScript.onerror = (backupError) => {
        console.error('Jessibuca备用脚本加载失败:', backupError)
        reject(backupError)
      }
      
      document.head.appendChild(backupScript)
    }

    document.head.appendChild(script)
  })
}

// 判断是否支持 Jessibuca（H5环境）
function isSupported() {
  return typeof window !== 'undefined' && typeof document !== 'undefined'
}

export default {
  install(Vue) {
    Vue.prototype.$jessibuca = {
      loadScript: loadJessibucaScript,
      createPlayer(options) {
        return loadJessibucaScript().then((Jessibuca) => {
          if (!Jessibuca) {
            console.log('Jessibuca 加载失败，无法创建播放器')
            return null
          }
          
          // 确保设置了decoder和wasm路径
          options = options || {};
          options.decoder = options.decoder || './static/js/jessibuca/decoder.js';
          options.wasmUrl = options.wasmUrl || './static/js/jessibuca/decoder.wasm';
          
          return new Jessibuca(options)
        })
      },
      isSupported
    }

    // 预加载脚本（H5环境下执行）
    if (isSupported()) {
      setTimeout(() => {
        loadJessibucaScript().catch(err => {
          console.error('预加载 Jessibuca 失败:', err)
        })
      }, 1000)
    }
  }
}
