// script.js
var flvPlayer = null;
var videoElement = document.getElementById('overlay_video_player'); // 改为悬浮窗口内的视频元素

var stopPlayers = function () {
    if (flvPlayer) {
        flvPlayer.destroy();
        flvPlayer = null;
    }
};

var hide_for_error = function () {
    document.getElementById('main_flash_alert').style.display = 'block';
    document.getElementById('overlay').style.display = 'none';
    stopPlayers();
};

var show_for_ok = function () {
    document.getElementById('main_flash_alert').style.display = 'none';
    document.getElementById('overlay').style.display = 'flex';
};

var apply_url_change = function(url) {
    console.log('Applying URL change to:', url);  // 调试信息
    if (!mpegts.getFeatureList().mseLivePlayback) {
        hide_for_error();
        return;
    }

    show_for_ok();

    flvPlayer = mpegts.createPlayer({type: 'flv', url: url, isLive: true, enableStashBuffer: false});
    flvPlayer.attachMediaElement(videoElement);
    flvPlayer.load();

    videoElement.muted = true; // 确保视频静音

    videoElement.onloadedmetadata = function() {
        videoElement.style.width = `${videoElement.videoWidth}px`;
        videoElement.style.height = `${videoElement.videoHeight}px`;

        enterFullScreen(videoElement).then(() => {
            flvPlayer.play().then(() => {
                console.log('Autoplay started');
            }).catch(error => {
                console.error('Autoplay was prevented:', error);
            });
        }).catch(error => {
            console.error('Fullscreen was prevented:', error);
            flvPlayer.play().then(() => {
                console.log('Autoplay started');
            }).catch(error => {
                console.error('Autoplay was prevented:', error);
            });
        });
    };
};

var closeOverlay = function() {
    exitFullScreen();
    document.getElementById('overlay').style.display = 'none';
    stopPlayers();
};

var enterFullScreen = function(element) {
    return new Promise((resolve, reject) => {
        if (element.requestFullscreen) {
            element.requestFullscreen().then(resolve).catch(reject);
        } else if (element.mozRequestFullScreen) { // Firefox
            element.mozRequestFullScreen().then(resolve).catch(reject);
        } else if (element.webkitRequestFullscreen) { // Chrome, Safari and Opera
            element.webkitRequestFullscreen().then(resolve).catch(reject);
        } else if (element.msRequestFullscreen) { // IE/Edge
            element.msRequestFullscreen().then(resolve).catch(reject);
        } else {
            reject(new Error('Fullscreen API is not supported'));
        }
    });
};

var exitFullScreen = function() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.mozCancelFullScreen) { // Firefox
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
        document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) { // IE/Edge
        document.msExitFullscreen();
    }
};

videoElement.addEventListener('webkitfullscreenchange', onFullScreenChange);
videoElement.addEventListener('mozfullscreenchange', onFullScreenChange);
videoElement.addEventListener('fullscreenchange', onFullScreenChange);
videoElement.addEventListener('MSFullscreenChange', onFullScreenChange);

function onFullScreenChange() {
    var isFullScreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
    if (isFullScreen) {
        console.log('Entered full screen');
    } else {
        console.log('Exited full screen');
        // 恢复视频元素的默认尺寸
        videoElement.style.width = `${videoElement.videoWidth}px`;
        videoElement.style.height = `${videoElement.videoHeight}px`;
    }
}

async function loadPlatforms() {
    const response = await fetch('/api/platforms');
    if (response.ok) {
        const platforms = await response.json();
        const container = document.getElementById('platforms');
        container.innerHTML = '';
        platforms.forEach(platform => {
            console.log('Platform data:', platform);  // 调试信息
            const div = document.createElement('div');
            div.className = 'platform';
            div.innerHTML = `
                <img src="${platform.image}" alt="${platform.name}">
                <h2>${platform.name}</h2>
                <p>${platform.description}</p>
                <a href="javascript:void(0);" onclick="apply_url_change('${platform.link}')" class="watch-link">观看直播</a>
            `;
            container.appendChild(div);
        });

        // Update language on dynamically loaded content
        setLanguage();
    } else {
        console.error('Failed to fetch platforms:', response.statusText);
    }
}

loadPlatforms();
