window.GDPRVideoComponent = {
    props: ['url'],

    computed: {
        provider() {
            if (this.url.includes("youtu")) return "youtube";
            if (this.url.includes("vimeo")) return "vimeo";
            return null;
        },

        videoId() {
            if (this.provider === "youtube") {
                const m = this.url.match(/(?:v=|youtu\.be\/|embed\/)([A-Za-z0-9_-]{11})/);
                return m ? m[1] : null;
            }

            if (this.provider === "vimeo") {
                const m = this.url.match(/vimeo\.com\/(?:video\/)?([0-9]+)/);
                return m ? m[1] : null;
            }

            return null;
        },

        thumbnail() {
            if (this.provider === "youtube") {
                return `https://img.youtube.com/vi/${this.videoId}/hqdefault.jpg`;
            }

            if (this.provider === "vimeo") {
                return `https://vumbnail.com/${this.videoId}.jpg`;
            }

            return null;
        }
    },

    methods: {
        play() {
            const iframe = document.createElement('iframe');

            if (this.provider === "youtube") {
                iframe.src = `https://www.youtube-nocookie.com/embed/${this.videoId}?autoplay=1`;
            }

            if (this.provider === "vimeo") {
                iframe.src = `https://player.vimeo.com/video/${this.videoId}?autoplay=1`;
            }

            iframe.allow = "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture";
            iframe.allowFullscreen = true;
            iframe.className = "gdpr-video-iframe";

            this.$el.innerHTML = "";
            this.$el.appendChild(iframe);
        }
    },

    template: `
        <div v-if="videoId" class="gdpr-video">

            <div class="gdpr-video-thumb"
                 :style="thumbnail 
                     ? 'background-image:url(' + thumbnail + ')' 
                     : ''"
                 @click="play"></div>

            <div class="gdpr-video-play" @click="play">▶</div>

            <div class="gdpr-video-notice">
                En cliquant, vous acceptez de charger du contenu externe.
            </div>
        </div>
    `
};
