const YouTubePlayerUtils = {
    player: null,
    isAPIReady: false,
    pendingVideoId: null,

    init(containerId = 'player') {
        if (this.isAPIReady) return;

        const tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        const firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        window.onYouTubeIframeAPIReady = () => {
            this.isAPIReady = true;
            this.createPlayer(containerId);
        };
    },

    createPlayer(containerId, videoId = null) {
        if (!this.isAPIReady) {
            this.pendingVideoId = videoId;
            return;
        }

        const config = {
            height: '100%',
            width: '100%',
            playerVars: {
                autoplay: 1,
                controls: 0,
                mute: 1,
                loop: 1,
                showinfo: 0,
                modestbranding: 1,
                disablekb: 1
            },
            events: {
                onReady: (event) => {
                    event.target.mute();
                    if (this.pendingVideoId) {
                        this.loadVideo(this.pendingVideoId);
                        this.pendingVideoId = null;
                    } else {
                        event.target.playVideo();
                    }
                }
            }
        };

        if (videoId) {
            config.videoId = videoId;
            config.playerVars.playlist = videoId;
        }

        this.player = new YT.Player(containerId, config);
    },

    loadVideo(videoId) {
        if (!this.player || !this.player.loadVideoById) {
            this.pendingVideoId = videoId;
            return;
        }

        this.player.loadVideoById(videoId);
        this.player.mute();
    },

    playTrailer(trailerData, containerId = 'player', fallbackImage = null) {
        if (!trailerData || trailerData.site !== 'youtube' || !trailerData.id) {

            if (fallbackImage) {
                this.showFallbackImage(containerId, fallbackImage);
            }
            return false;
        }

        if (!this.isAPIReady) {
            this.init(containerId);
            this.pendingVideoId = trailerData.id;
        } else if (this.player) {
            this.loadVideo(trailerData.id);
        } else {
            this.createPlayer(containerId, trailerData.id);
        }

        return true;
    },

    showFallbackImage(containerId, imageUrl) {
        const container = document.querySelector(`#${containerId}`)?.parentElement;
        if (!container) return;

        container.innerHTML = `<img src="${imageUrl}" style="width:100%; height:100%; object-fit:cover;">`;
    },

    stop() {
        if (this.player && this.player.stopVideo) {
            this.player.stopVideo();
        }
    },

    destroy() {
        if (this.player && this.player.destroy) {
            this.player.destroy();
            this.player = null;
        }
    }
};

window.YouTubePlayerUtils = YouTubePlayerUtils;