window.vidplexYTQueue = window.vidplexYTQueue || [];
window.vidplexYTReady = window.vidplexYTReady || false;

window.YTPlayerManager = (() => {
    let apiReady = false;
    const players = {};
    const queue = [];

    window.onYouTubeIframeAPIReady = () => {
        apiReady = true;
        queue.forEach((fn) => fn());
        queue.length = 0;
    };

    function create({ id, el, videoId, options = {}, onReady, onStateChange }) {
        const init = () => {
            if (players[id]) return players[id];

            players[id] = new YT.Player(el, {
                height: "100%",
                width: "100%",
                videoId,
                playerVars: {
                    rel: 0,
                    modestbranding: 1,
                    ...options,
                },
                events: {
                    onReady,
                    onStateChange,
                },
            });

            return players[id];
        };

        if (apiReady) {
            return init();
        }

        queue.push(init);
    }

    function get(id) {
        return players[id];
    }

    function getAll() {
        return players;
    }

    function destroy(id) {
        if (players[id]) {
            players[id].destroy();
            delete players[id];
        }
    }

    // Replace videoId in an existing player
    function replace({ id, videoId, startTime }) {
        const player = players[id];
        if (player && typeof player.loadVideoById === "function") {
            player.loadVideoById({ videoId: videoId, startSeconds: startTime });
            return player;
        }
        console.warn(
            `Player with id "${id}" does not exist yet or is not ready.`,
        );
        return null;
    }

    return {
        create,
        get,
        getAll,
        destroy,
        replace,
    };
})();
