var cur_language = "chinese";
var player = null;

function normalizePreviewDimension(value, fallback, max) {
    value = parseInt(value, 10);
    fallback = parseInt(fallback, 10);
    max = parseInt(max, 10);

    if (!(fallback > 0)) {
        fallback = 1;
    }
    if (!(value > 0)) {
        value = fallback;
    }
    if (max > 0) {
        value = Math.min(value, max);
    }

    return value;
}

function fitPreviewToViewport(w, h, options) {
    options = options || {};

    w = normalizePreviewDimension(w, options.fallbackWidth || 450, options.maxWidth || w);
    h = normalizePreviewDimension(h, options.fallbackHeight || 180, options.maxHeight || h);

    var viewportWidth = Math.max(window.innerWidth || 0, document.documentElement ? document.documentElement.clientWidth : 0);
    var viewportHeight = Math.max(window.innerHeight || 0, document.documentElement ? document.documentElement.clientHeight : 0);
    var horizontalChrome = options.horizontalChrome > 0 ? options.horizontalChrome : 48;
    var verticalChrome = options.verticalChrome > 0 ? options.verticalChrome : 96;
    var availableWidth = viewportWidth > 0 ? viewportWidth - horizontalChrome : w;
    var availableHeight = viewportHeight > 0 ? viewportHeight - verticalChrome : h;

    if (!(availableWidth > 0)) {
        availableWidth = w;
    }
    if (!(availableHeight > 0)) {
        availableHeight = h;
    }

    var scale = Math.min(1, availableWidth / w, availableHeight / h);
    if (!(scale > 0)) {
        scale = 1;
    }

    return {
        width: Math.max(1, Math.floor(w * scale)),
        height: Math.max(1, Math.floor(h * scale))
    };
}

function normalizeH265PreviewSize(w, h, venc_width, venc_height) {
    w = parseInt(w, 10);
    h = parseInt(h, 10);
    venc_width = parseInt(venc_width, 10);
    venc_height = parseInt(venc_height, 10);

    if (!(w > 0)) {
        w = 640;
    }
    if (!(h > 0)) {
        h = 360;
    }

    if (!(venc_width > 0) || !(venc_height > 0)) {
        return { width: w, height: h };
    }

    w = Math.min(w, venc_width);
    h = Math.round(w * venc_height / venc_width);

    if (!(h > 0)) {
        h = Math.min(h, venc_height);
    }
    if (!(h > 0)) {
        h = 360;
    }

    return { width: w, height: h };
}

function getPreviewText(key, fallback) {
    if (typeof i18n !== 'undefined' && typeof i18n.t === 'function') {
        var value = i18n.t(key);
        if (value && value !== key) {
            return value;
        }
    }
    return fallback;
}

/**
 * 简单的视频预览弹窗（Tabler 风格）
 * 替代旧的 artDialog 弹窗，确保与页面整体风格一致。
 */
function openVideoPreviewModal(title, contentHtml, onShow, onClose) {
    // 确保同一时间只存在一个预览弹窗
    var existing = document.getElementById('video-preview-backdrop');
    if (existing && existing.parentNode) {
        existing.parentNode.removeChild(existing);
    }

    var previousOverflow = document.body.style.overflow || '';
    document.body.style.overflow = 'hidden';

    var backdrop = document.createElement('div');
    backdrop.id = 'video-preview-backdrop';
    backdrop.className = 'video-preview-backdrop';

    var modal = document.createElement('div');
    modal.className = 'video-preview-modal';

    var header = document.createElement('div');
    header.className = 'video-preview-header';

    var titleEl = document.createElement('div');
    titleEl.className = 'video-preview-title';
    titleEl.textContent = title || '';

    var closeBtn = document.createElement('button');
    closeBtn.type = 'button';
    closeBtn.className = 'video-preview-close';
    closeBtn.setAttribute('aria-label', 'Close');
    closeBtn.innerHTML = '&times;';

    header.appendChild(titleEl);
    header.appendChild(closeBtn);

    var body = document.createElement('div');
    body.className = 'video-preview-body';
    body.innerHTML = contentHtml || '';

    modal.appendChild(header);
    modal.appendChild(body);
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    function cleanup() {
        document.removeEventListener('keydown', onKeyDown);
        backdrop.removeEventListener('click', onBackdropClick);
        if (backdrop.parentNode) {
            backdrop.parentNode.removeChild(backdrop);
        }
        document.body.style.overflow = previousOverflow;
        if (typeof onClose === 'function') {
            onClose();
        }
    }

    function onKeyDown(e) {
        if (e.key === 'Escape' || e.keyCode === 27) {
            cleanup();
        }
    }

    function onBackdropClick(e) {
        if (e.target === backdrop) {
            cleanup();
        }
    }

    closeBtn.addEventListener('click', cleanup);
    document.addEventListener('keydown', onKeyDown);
    backdrop.addEventListener('click', onBackdropClick);

    if (typeof onShow === 'function') {
        onShow();
    }
}

function destroyPlayer() {
    if (!player) {
        return;
    }
    try {
        if (typeof player.stop === 'function') {
            player.stop();
        }
    } catch (e) {}
    try {
        if (typeof player.unload === 'function') {
            player.unload();
        }
    } catch (e) {}
    try {
        if (typeof player.detachMediaElement === 'function') {
            player.detachMediaElement();
        }
    } catch (e) {}
    try {
        if (typeof player.destroy === 'function') {
            player.destroy();
        }
    } catch (e) {}
    player = null;
}

// H.265 预览（中文）
function videoPlayerH265(url, m3u8, image, w, h, venc_width, venc_height) {
    if (!url) {
        alert(getPreviewText('preview.flvRequired', 'Please enable the FLV stream.'));
        return;
    }
    if (url) {
        tt = 'FLV';
    }

    cur_language = "chinese";

    var isH265 = true;

    var previewSize = normalizeH265PreviewSize(w, h, venc_width, venc_height);
    previewSize = fitPreviewToViewport(previewSize.width, previewSize.height, {
        fallbackWidth: 640,
        fallbackHeight: 360,
        maxWidth: previewSize.width,
        maxHeight: previewSize.height
    });
    w = previewSize.width;
    h = previewSize.height;

    var ct = '<div class="video-preview-content" style="width:' + w + 'px;height:' + h + 'px;">' +
        '<img id="player_loading_logo" class="video-preview-loading" src="player/icons/loading.gif" />' +
        '<canvas id="canvas" class="video-preview-canvas" width="' + w + '" height="' + h + '"></canvas>' +
        '</div>';

    openVideoPreviewModal(
        tt + ' Preview',
        ct,
        function () {
            if (typeof WXInlinePlayer === 'undefined' || !WXInlinePlayer.isSupport()) {
                return;
            }

            var canvas = document.getElementById("canvas");
            var params = {
                asmUrl: "./player/wx/prod." + (isH265 ? "h265" : "all") + ".asm.combine.js",
                wasmUrl: "./player/wx/prod." + (isH265 ? "h265" : "all") + ".wasm.combine.js",
                url: url,
                $container: canvas,
                volume: 1.0,
                muted: false,
                autoplay: true,
                loop: true,
                isLive: true,
                chunkSize: 128 * 1024,
                preloadTime: 2000,
                bufferingTime: 2000,
                cacheSegmentCount: 256,
                customLoader: null
            };

            $("#canvas").hide();

            WXInlinePlayer.ready(params).then(function (obj) {
                player = obj;

                player.on("buffering", function () {
                    $("#player_loading_logo").show();
                });
                player.on("playing", function () {
                    $("#player_loading_logo").hide();
                    $("#canvas").show();
                });
            });

            // 双击全屏
            canvas.ondblclick = function () {
                if (canvas.requestFullscreen) {
                    canvas.requestFullscreen();
                }
            };

            // 单击预留（当前不做暂停切换）
            canvas.onclick = function () {};
        },
        function () {
            destroyPlayer();
        }
    );
}

// H.265 预览（英文）
function videoPlayerH265E(url, m3u8, image, w, h, venc_width, venc_height) {
    if (!url) {
        alert("Please open FLV stream.");
        return;
    }
    if (url) {
        tt = 'FLV';
    }

    cur_language = "english";

    var isH265 = true;

    var previewSize = normalizeH265PreviewSize(w, h, venc_width, venc_height);
    previewSize = fitPreviewToViewport(previewSize.width, previewSize.height, {
        fallbackWidth: 640,
        fallbackHeight: 360,
        maxWidth: previewSize.width,
        maxHeight: previewSize.height
    });
    w = previewSize.width;
    h = previewSize.height;

    var ct = '<div class="video-preview-content" style="width:' + w + 'px;height:' + h + 'px;">' +
        '<img id="player_loading_logo" class="video-preview-loading" src="player/icons/loading.gif" />' +
        '<canvas id="canvas" class="video-preview-canvas" width="' + w + '" height="' + h + '"></canvas>' +
        '</div>';

    openVideoPreviewModal(
        tt + ' Preview',
        ct,
        function () {
            if (typeof WXInlinePlayer === 'undefined' || !WXInlinePlayer.isSupport()) {
                return;
            }

            var canvas = document.getElementById("canvas");
            var params = {
                asmUrl: "./player/wx/prod." + (isH265 ? "h265" : "all") + ".asm.combine.js",
                wasmUrl: "./player/wx/prod." + (isH265 ? "h265" : "all") + ".wasm.combine.js",
                url: url,
                $container: canvas,
                volume: 1.0,
                muted: false,
                autoplay: true,
                loop: true,
                isLive: true,
                chunkSize: 128 * 1024,
                preloadTime: 500,
                bufferingTime: 500,
                cacheSegmentCount: 64,
                customLoader: null
            };

            $("#canvas").hide();

            WXInlinePlayer.ready(params).then(function (obj) {
                player = obj;

                player.on("buffering", function () {
                    $("#player_loading_logo").show();
                });
                player.on("playing", function () {
                    $("#player_loading_logo").hide();
                    $("#canvas").show();
                });
            });

            canvas.onclick = function () {};
        },
        function () {
            destroyPlayer();
        }
    );
}

// flv.js / hls.js HTML5 播放器（中文）
function videoPlayerHTML5(url, m3u8, m3u8_fmp4, image, w, h) {
    if (typeof h === 'undefined' && typeof w !== 'undefined') {
        h = w;
        w = image;
        image = m3u8_fmp4;
        m3u8_fmp4 = '';
    }
    if (!url && !m3u8 && !m3u8_fmp4) {
        alert(getPreviewText('preview.flvOrHlsRequired', 'Please enable at least one live stream: FLV or HLS.'));
        return;
    }
    var hlsSource = '';
    if (!url) {
        hlsSource = m3u8 ? m3u8 : m3u8_fmp4;
    }
    var useHls = (!url && hlsSource);
    tt = useHls ? 'HLS' : 'FLV';

    cur_language = "chinese";

    var previewSize = fitPreviewToViewport(w, h, {
        fallbackWidth: 450,
        fallbackHeight: 180,
        maxWidth: 650,
        maxHeight: 420
    });
    w = previewSize.width;
    h = previewSize.height;

    var ct = '<div class="video-preview-content" style="width:' + w + 'px;height:' + h + 'px;">' +
        '<video id="videoElement" name="videoElement" class="video-preview-video" controls autoplay width="' + w + '" height="' + h + '"></video>' +
        '</div>';

    openVideoPreviewModal(
        tt + ' Preview',
        ct,
        function () {
            var element = document.getElementById('videoElement');
            destroyPlayer();

            if (useHls) {
                var hlsUrl = curl(hlsSource);
                if (element && element.canPlayType('application/vnd.apple.mpegurl')) {
                    element.src = hlsUrl;
                    element.play();
                    return;
                }
                if (typeof Hls === 'undefined' || !Hls.isSupported()) {
                    alert(getPreviewText('preview.hlsUnsupportedEnableFlv', 'HLS preview is not supported in this browser. Please enable FLV.'));
                    return;
                }
                player = new Hls();
                player.loadSource(hlsUrl);
                player.attachMedia(element);
                player.on(Hls.Events.MANIFEST_PARSED, function () {
                    element.play();
                });
                return;
            }

            if (typeof flvjs === 'undefined' || !flvjs.isSupported()) {
                return;
            }

            var mediaDataSource = {
                url: curl(url),
                type: 'flv',
                isLive: true,
                withCredentials: false
            };

            player = flvjs.createPlayer(mediaDataSource, {
                enableWorker: false,
                lazyLoadMaxDuration: 3 * 60,
                seekType: 'range'
            });
            player.attachMediaElement(element);
            player.load();
            player.play();
        },
        function () {
            destroyPlayer();
        }
    );
}

// flv.js / hls.js HTML5 播放器（英文）
function videoPlayerHTML5E(url, m3u8, m3u8_fmp4, image, w, h) {
    if (typeof h === 'undefined' && typeof w !== 'undefined') {
        h = w;
        w = image;
        image = m3u8_fmp4;
        m3u8_fmp4 = '';
    }
    if (!url && !m3u8 && !m3u8_fmp4) {
        alert("Please open FLV or HLS stream.");
        return;
    }
    var hlsSource = '';
    if (!url) {
        hlsSource = m3u8 ? m3u8 : m3u8_fmp4;
    }
    var useHls = (!url && hlsSource);
    tt = useHls ? 'HLS' : 'FLV';

    cur_language = "english";

    var previewSize = fitPreviewToViewport(w, h, {
        fallbackWidth: 450,
        fallbackHeight: 180,
        maxWidth: 650,
        maxHeight: 420
    });
    w = previewSize.width;
    h = previewSize.height;

    var ct = '<div class="video-preview-content" style="width:' + w + 'px;height:' + h + 'px;">' +
        '<video id="videoElement" name="videoElement" class="video-preview-video" controls autoplay width="' + w + '" height="' + h + '"></video>' +
        '</div>';

    openVideoPreviewModal(
        tt + ' Preview',
        ct,
        function () {
            var element = document.getElementById('videoElement');
            destroyPlayer();

            if (useHls) {
                var hlsUrl = curl(hlsSource);
                if (element && element.canPlayType('application/vnd.apple.mpegurl')) {
                    element.src = hlsUrl;
                    element.play();
                    return;
                }
                if (typeof Hls === 'undefined' || !Hls.isSupported()) {
                    alert("HLS preview is not supported in this browser. Please enable FLV.");
                    return;
                }
                player = new Hls();
                player.loadSource(hlsUrl);
                player.attachMedia(element);
                player.on(Hls.Events.MANIFEST_PARSED, function () {
                    element.play();
                });
                return;
            }

            if (typeof flvjs === 'undefined' || !flvjs.isSupported()) {
                return;
            }

            var mediaDataSource = {
                url: curl(url),
                type: 'flv',
                isLive: true,
                withCredentials: false
            };

            player = flvjs.createPlayer(mediaDataSource, {
                enableWorker: false,
                lazyLoadMaxDuration: 3 * 60,
                seekType: 'range'
            });
            player.attachMediaElement(element);
            player.load();
            player.play();
        },
        function () {
            destroyPlayer();
        }
    );
}

// 保留旧接口名，统一走 HTML5
function videoPlayer(url, m3u8, image, w, h) {
    videoPlayerHTML5(url, m3u8, image, w, h);
}

function videoPlayerE(url, m3u8, image, w, h) {
    videoPlayerHTML5E(url, m3u8, image, w, h);
}

function curl(str) {
    var parts = str.split("/");
    if (parts.length > 2) {
        str = str.replace(parts[2], window.location.host);
    }
    return str;
}
