let widgetNode = document.getElementById('widget');
let predictionNode = document.getElementById('prediction');
let titleNode = document.getElementById('title');
let pointsNode = document.getElementById('points');
let timeNode = document.getElementById('time');
let outcomesNode = document.getElementById('outcomes');
let templateNode = document.getElementById('outcome');

let willEndAt = new Date();
let locksAt = null;
let endedAt = null;

window.addEventListener('message', function (event) {
    let message = event.detail;
    widgetNode.classList.add('active');

    switch (message.type) {
        case 'prediction.end':
            if (message.status == "canceled") {
                predictionNode.classList.remove('active');
                predictionNode.classList.remove('ended');
            } else {
                predictionNode.classList.remove('locked');
                predictionNode.classList.add('ended');
                endedAt = new Date(message.ended_at);

                let winnerNode = document.querySelector(`[outcomeId="${message.winning_outcome_id}"]`);
                winnerNode.classList.add('winner');
            };
            break;
        case 'prediction.lock':
            predictionNode.classList.add('active');
            locksAt = new Date();
            endedAt = null;
            break;
        case 'prediction.begin':
        case 'prediction.progress':
            var totalPoints = message.outcomes.reduce((sum, outcome) => sum + (outcome.channel_points ?? 0), 0);
            endedAt = null;

            if (message.id != predictionNode.getAttribute('predictionId')) {
                outcomesNode.innerHTML = '';
                locksAt = new Date(message.ends_at);

                predictionNode.setAttribute('predictionId', message.id);
                titleNode.innerText = message.title;
                pointsNode.innerHTML = `Поинтов: ${totalPoints}`;

                predictionNode.classList.add('active');
                predictionNode.classList.remove('locked');
                predictionNode.classList.remove('ended');

                message.outcomes.forEach(outcome => {
                    let root = templateNode.content.cloneNode(true);
                    let outcomeNode = root.querySelector('.outcome');
                    let title = root.querySelector('.title');
                    let points = root.querySelector('.points');

                    let outcomePoints = outcome.channel_points ?? 0;
                    let percent = (outcomePoints / (totalPoints || 1) * 100).toFixed(2);

                    outcomeNode.setAttribute('outcomeId', outcome.id);
                    outcomeNode.style.setProperty('--progress', `${percent}%`);

                    title.innerText = outcome.title;
                    points.innerText = `${percent}%`;

                    outcomesNode.appendChild(root);
                });
            } else {
                pointsNode.innerHTML = `Поинтов: ${totalPoints}`;
                message.outcomes.forEach(outcome => {
                    let outcomeNode = document.querySelector(`[outcomeId="${outcome.id}"]`);
                    let title = outcomeNode.querySelector('.title');
                    let points = outcomeNode.querySelector('.points');

                    let outcomePoints = outcome.channel_points ?? 0;
                    let percent = (outcomePoints / (totalPoints || 1) * 100).toFixed(2);

                    outcomeNode.style.setProperty('--progress', `${percent}%`);

                    title.innerText = outcome.title;
                    points.innerText = `${percent}%`;
                });
            };

            locksAt = new Date(message.locks_at);

            break;

        default: break;
    };
});

function convertSecondsToMMSS(seconds) {
    seconds = Math.round(seconds);
    if (seconds <= 0) {
        seconds = 0;
    };
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(secs).padStart(2, '0');
    return `${formattedMinutes}м:${formattedSeconds}с`;
};

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};

async function updateTimer() {
    let now = new Date().getTime();
    let left = (locksAt - now) / 1000;

    timeNode.innerHTML = `Осталось: ${convertSecondsToMMSS(left)}`;

    if (!endedAt && left <= 0) {
        timeNode.innerHTML = `Ожидание результата`;
        predictionNode.classList.add('locked');
    };

    left = (now - endedAt) / 1000;

    if (endedAt) {
        timeNode.innerHTML = `Закончилось`;
        predictionNode.classList.remove('locked');

        if (left > 5) {
            predictionNode.classList.remove('active');
            predictionNode.classList.remove('ended');
        };
    };

    await delay(100);
    updateTimer();
};

updateTimer();
