<template lang="pug">
.hero.f-col(v-if="showHero")
    .hero--video(v-if="heroType === 'video'")
        iframe(
            v-if="isPlaying"
            :src="`https://www.youtube.com/embed/${heroIdFromUrl}?autoplay=1`"
            frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope"
            allowfullscreen
        ).embedded
        .blank.f-col(v-else)
            h3(v-if="heroText") {{ heroText }}
            img(:src="getThumbnailFromYt(showHero)" alt="hero alt image")
            button(v-if="showPlaybutton" @click="isPlaying = true") play
    .hero--image(v-else-if="heroType === 'image'")
        .hero--image--overlay.f-col
            div(v-html="heroText")
        img(:src="showHero" alt="hero alt image")
    .hero--image(v-else)
        .hero--image--overlay.f-col
            div(v-html="heroText")

</template>

<script>
import { ytThumbnail } from '@/utils/helpers'
import { mapState } from 'vuex'

export default {
    data() {
        return {
            heroHeight: 0,
            isPlaying: false
        }
    },
    computed: {
        ...mapState({
            showHero: state => state.hero.url,
            heroText: state => state.hero.text,
            heroType: state => state.hero.type,
            showPlaybutton: state => state.hero.playbutton,
        }),
        heroIdFromUrl() {
            const url = this.showHero.split('/')
            return url.pop()
        }
    },
    methods: {
        onResize() {
            this.heroHeight = this.$el.offsetWidth / 1.8
        },
        getThumbnailFromYt(url) {
            return ytThumbnail(url, 'max')
        }
    },
    mounted() {
        this.heroHeight = this.$el.offsetWidth / 1.8
        this.$nextTick(() => { 
            window.addEventListener('resize', this.onResize) })
    },
    watch: {
        $route() {
            // console.log('remounting hero')
            // console.log(this.$store)
            // Clear the hero between pages
            this.$store.commit('CLEAR_HERO')
        },
        heroHeight() {
            if(!this.showHero) return
            Object.assign(this.$el.style, {height: this.heroHeight + 'px'})
        }
    },
    beforeUnmount() {
        window.removeEventListener('resize', this.onResize)
    },
    
}
</script>

<style lang="postcss">
.hero
    background-color: rebeccapurple
    min-height: 35%
    width: 100%
    &--image
        width: 100%
        > img
            width: 100%
        &--overlay
            color: #ffffff
            position: absolute
            top: 30%
            width: 100%
    .embedded
        height: 100%
        width: 100%
</style>