/*
 * 一起看公共播放器工具：统一处理普通视频链接和 m3u8 链接。
 * 作者: @ccfork
 */
(function() {
    function isHlsUrl(url) {
        return /\.m3u8(\?|#|$)/i.test(url || '');
    }

    function destroyHls(video) {
        if (video.__watchHls) {
            video.__watchHls.destroy();
            video.__watchHls = null;
        }
    }

    async function setVideoSource(video, url) {
        if (!video || !url) return { ok: false, error: '缺少播放地址' };
        destroyHls(video);
        video.pause();
        video.removeAttribute('src');
        video.load();

        if (isHlsUrl(url) && window.Hls && window.Hls.isSupported()) {
            const hls = new window.Hls({ lowLatencyMode: true });
            video.__watchHls = hls;
            hls.loadSource(url);
            hls.attachMedia(video);
            return { ok: true, mode: 'hls.js' };
        }

        if (isHlsUrl(url) && video.canPlayType('application/vnd.apple.mpegurl')) {
            video.src = url;
            video.load();
            return { ok: true, mode: 'native-hls' };
        }

        if (!isHlsUrl(url)) {
            video.src = url;
            video.load();
            return { ok: true, mode: 'native' };
        }

        return { ok: false, error: '当前浏览器缺少 m3u8 播放支持' };
    }

    window.WatchPlayer = { isHlsUrl, setVideoSource, destroyHls };
})();
