// 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();

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

        videoElement.muted = true;
        
        flvPlayer.play().then(() => {
            console.log('Autoplay started');
        }).catch(error => {
            console.error('Autoplay was prevented initially:', error);
            retryPlay();
        });
    }).catch(error => {
        console.error('Fullscreen was prevented:', error);
        hide_for_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) {
            element.mozRequestFullScreen().then(resolve).catch(reject);
        } else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen().then(resolve).catch(reject);
        } else if (element.msRequestFullscreen) {
            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) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }
};

var retryPlay = function(attempts = 3) {
    if (attempts > 0) {
        setTimeout(() => {
            flvPlayer.play().then(() => {
                console.log('Autoplay started after retry');
            }).catch(error => {
                console.error(`Autoplay retry failed (${3 - attempts + 1}):`, error);
                retryPlay(attempts - 1);
            });
        }, 1000);
    } else {
        console.error('Autoplay failed after multiple attempts');
    }
};

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

videoElement.addEventListener('enterpictureinpicture', () => {
    console.log('Entered Picture-in-Picture');
    minimizeWindow();
});

videoElement.addEventListener('leavepictureinpicture', () => {
    console.log('Exited Picture-in-Picture');
    restoreWindow();
});

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`;
    }
}

function minimizeWindow() {
    if (window.outerWidth > 200 && window.outerHeight > 200) {
        window.resizeTo(200, 200);
    }
}

function restoreWindow() {
    window.resizeTo(1024, 768);
}

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);
        });

        setLanguage();
    } else {
        console.error('Failed to fetch platforms:', response.statusText);
    }
}

loadPlatforms();
