<template>
  <div class="detail-main__article">
    <div v-html="rawHtml" ref="content"></div>
    <div class="tooltip-block" ref="tooltipBlock" v-show="tooltipShow">
      <div class="tooltip-block_title">{{ tooltipTitle }}</div>
      <div class="tooltip-block_text">{{ tooltipText }}</div>
      <div class="tooltip-block_close" @click="tooltipShow = false">
        <v-icon>mdi-close</v-icon>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import VueSlickCarousel from "vue-slick-carousel";
import "vue-slick-carousel/dist/vue-slick-carousel.css";
import { createPopper } from "@popperjs/core";
import Tinybox from "vue-tinybox";

export default {
  props: {
    rawHtml: {
      type: String
    },
    isAdvert: {
      type: Boolean
    }
  },
  data () {
    return {
      tooltipShow: false,
      tooltipTitle: "",
      tooltipText: "",
      images: null,
      index: null
    };
  },
  computed: {
    content() {
      return this.rawHtml.split("##");
    },
  },
  mounted () {

    const secondParagaph = this.$refs.content.querySelectorAll("p")[1]
    if(this.$nuxt.$device.isMobile){
      const banner = document.createElement('p');

      banner.innerHTML = `
      <div id="adfox_167091964852627830" style="max-height: 80vh;">
        <div style="min-height: 300px;" class="adfox_placeholder"></div>
      </div>
    `
      secondParagaph.appendChild(banner)

      addEventListener('load', () => {
        window.yaContextCb.push(() => {
          // eslint-disable-next-line no-undef
          Ya.adfoxCode.createAdaptive({
            ownerId: 359693,
            containerId: 'adfox_167091964852627830',
            params: {
              pp: 'bufl',
              ps: 'gduo',
              p2: 'hywx'
            },
            lazyLoad: {
              fetchMargin: 100,
              mobileScaling: 1.3
            }
          },
          ['tablet', 'phone'], {
            tabletWidth: 899,
            phoneWidth: 480,
            isAutoReloads: true
          })
        })
        setInterval(function () {
          Ya.adfoxCode.reload('adfox_167091964852627830', {onlyIfWasVisible: true});
        }, 30000)
      })
    } else {
      const thirdParagraph = this.$refs.content.querySelectorAll('p')[2]
      if (typeof thirdParagraph !== 'undefined' && !this.isAdvert && 0) {
        // const videLib = document.createElement('script')
        // videLib.src = 'https://moevideo.biz/embed/js/mvpt.min.js'
        // thirdParagraph.appendChild(videLib)
        const videoBanner = document.createElement('p')
        videoBanner.innerHTML = '<div id="adv"></div>'
        thirdParagraph.appendChild(videoBanner)
        const script = document.createElement('script')
        script.innerHTML = `
          var moevideoQueue = moevideoQueue || []
          moevideoQueue.push(function () {
            moevideo.ContentRoll({
              mode: 'manual',
              el: '#adv',
              videoInstream: 'https://cdn1.playreplay.me/country.mp4',
              closeInstream: 'true',
              instream: true,
              maxRefresh: 3,
              ignorePlayers: true
            })
          })`
        thirdParagraph.appendChild(script)
      }
    }

    this.$refs.content.addEventListener("click", this.onClickContent);

    const galleries = this.$refs.content.querySelectorAll(".gallery");

    const slickComponent = Vue.extend({
      template: `<div><div class="detail-top__images"><vue-slick-carousel ref="galleryImages" :asNavFor="$refs.galleryThumbs" @beforeChange="syncSliders" v-if="images.length">
            <div class="single-article-content-slider-item" v-for="(image, i) in images" :key="i" >
              <img @click="index = i"  :src="image.url" :alt="image.name"></img>
              <div v-if="image.name" class="image-title">{{ image.name }}</div>
            </div>


            <template #prevArrow="arrowOption">
              <button class="button button_news-slider button_news-slider-prev">
                <BaseIcon :name="'h-slider-prev'" clear />
              </button>
            </template>

            <template #nextArrow="arrowOption">
              <button class="button button_news-slider button_news-slider-next">
                <BaseIcon :name="'h-slider-next'" clear />
              </button>
            </template>
        </vue-slick-carousel>        <div class="detail-top__thumbs">
          <vue-slick-carousel
            ref="galleryThumbs"
            :asNavFor="$refs.galleryImages"
            :focusOnSelect="true"
            :draggable="false"
            :touchThreshold="4"
            :slidesToScroll="1"
            :slidesToShow="4"
            :arrows="false"
            @beforeChange="syncSliders"
          >
            <div class="detail-top__thumb" v-for="(image, i) in images" :key="i">
              <img :src="image.url" :alt="image.name" />
            </div>
          </vue-slick-carousel>
        </div></div><Tinybox v-model="index" :images="img" /></div>`,
      components: { VueSlickCarousel, Tinybox },
      methods: {
        syncSliders(currentPosition, nextPosition) {
          this.$refs.galleryThumbs.goTo(nextPosition);
          this.$refs.galleryImages.goTo(nextPosition);
        }
      },
      props: ["images","img","index"],
    });

    galleries.forEach((gallery) => {
      const images = this.images = [...gallery.querySelectorAll("img")].map((img) => ({
        url: img.src,
        name: img.alt,
      }));
      const index = this.index,
        img_arr = this.images.map((elem, index) => {
          return index = {'src':elem.url,'caption':elem.name}
        } ),
        img = JSON.parse(JSON.stringify(img_arr));
      const slickMounted = new slickComponent({
        propsData: { images,img,index },
      }).$mount();

      gallery.replaceWith(slickMounted.$el);
    });

    const iframes =  this.$refs.content.querySelectorAll('iframe');
    iframes.forEach(iframe => {
      if(iframe.getAttribute('class') != 'iframe-instagram'){
        const widthAttr = iframe.getAttribute('width');
        const heightAttr = iframe.getAttribute('height');
        if(widthAttr && heightAttr) {
          iframe.style.aspectRatio = `${widthAttr} / ${heightAttr}`;
        }
      }
    });

    window.addEventListener('load', () => {
      try{
        const iframeInstagram =  this.$refs.content.querySelectorAll('.iframe-instagram');
        iframeInstagram.forEach(iframe => {
          iframe.removeAttribute('height');
        })
      } catch (e) {
        console.log('InstaIframe loading fail')
      }

    });

  },

  beforeDestroy() {
    this.$refs.content.removeEventListener("click", this.onClickContent);
  },

  methods: {
    onClickContent(e) {
      if (!e.target.classList.contains("tooltip")) return;
      this.tooltipShow = true;

      const tooltipBlock = this.$refs.tooltipBlock;
      const tooltipBtn = e.target;

      this.tooltipTitle = e.target.dataset.title;
      this.tooltipText = e.target.dataset.text;

      createPopper(tooltipBtn, tooltipBlock, {
        placement: "bottom",
      });
    },
  },
};
</script>

<style lang="less" scoped>
::v-deep .single-article-content-slider-item img {
     margin: auto;
}
::v-deep .slick-track {
  align-items: center;
  background-color: rgba(59, 85, 115, 0.08);
}

::v-deep .button_news-slider {
  box-shadow: 0px 0px 20px 10px rgba(34, 60, 80, 0.2);
}

::v-deep .image-title {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px 0;
}

::v-deep .tooltip {
  cursor: pointer;
  border-bottom: 1px dashed #5a748b;
}

.tooltip-block {
  background-color: #fff;
  min-width: 300px;
  border: 1px solid rgba(59, 85, 115, 0.08);
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  line-height: 20px;
  max-width: 700px;
  margin: 0 auto;
  inset: 0px  auto auto auto !important;
  box-shadow: 0px 20px 40px rgba(0,0,0,.1);
  z-index: 2;
  @media screen and (max-width: 768px) {
    max-width: 300px;
  }


  &_title {
    font-weight: bold;
  }
  &_text {
  }

  &_close {
    position: absolute;
    top: 0px;
    right: 0;
    cursor: pointer;
  }
}

::v-deep .style1 {
  display: block;
  padding: 20px;
  background-color: #fdf7e6;
}

::v-deep iframe {
  width: 100%;
}

::v-deep .iframe-wrapper {
  max-width: 100%;
  margin: 0 auto;

  iframe {
    min-height: 500px;
    width: 100%;
  }
  .iframe-instagram{
    height: 1015px;
    min-height: auto;
  }

  @media screen and (max-width: 768px) {
    iframe {
      min-height: 200px;
    }
    .iframe-instagram{
      height: 630px;
      min-height: auto;
    }
  }
}

//Audio style
::v-deep audio {
  width: 100%;
}

//Video style
::v-deep iframe[allow*="autoplay"],
::v-deep iframe[allow*="fullscreen"],
::v-deep iframe[allow*="picture-in-picture"] {
  width: 100%;
  height: 300px;

  @supports (aspect-ratio: 1) {
    height: auto;
    aspect-ratio: 16 / 9;
  }
}

//Inject style
::v-deep .detail-article-news {
  @media screen and (max-width: 768px) {
    &__side {
      max-width: 100%;
      flex: 1 0 auto;
      margin-right: 0;
    }
    &__figure {
      height: auto;
      padding-top: 20px;
      border-top: 1px solid #EAEAEA;
    }
    &__img {
      max-width: 100%;
      margin-right: 0;
    }
  }
}
@media screen and (min-device-width: 900px) {
  #adfox_167091964852627830 {
    display: none;
  }
}
</style>
