<script>
  import Popper from 'popper.js'

  export default {
    name: 'flyout',
    data: function () {
      return {
        isActive: false,
        popperOptions:
          {
            placement: 'bottom-start',
            modifiers: {
              arrow: {enabled: false},
              preventOverflow: {
                boundariesElement: 'viewport'
              },
              flip: {
                behavior: ['bottom-start', 'bottom-end', 'top-start', 'top-end'],
                boundariesElement: 'viewport'
              }
            }
          }
      }
    },
    render () {
      return this.$scopedSlots.default({
        isActive: this.isActive,
        toggle: this.toggle
      })
    },
    created () {},
    destroyed () {
      this.destroyPopper()
    },
    mounted () {
      this.referenceElement = this.$el.querySelectorAll('[data-reference]')[0]
      this.popperElement = this.$el.querySelectorAll('[data-popper]')[0]
      this.popper = null
    },
    watch: {
      isActive: function (isActive) {
        (isActive) ? this.createPopper() : this.destroyPopper()
      }
    },
    methods: {
      toggle () {
        this.isActive = !this.isActive
      },
      createPopper () {
        if (this.popper) {
          return
        }
        this.popper = new Popper(
          this.referenceElement,
          this.popperElement,
          this.popperOptions
        )
        document.addEventListener('click', this.handleDocumentClick)
      },
      destroyPopper () {
        if (!this.popper) {
          return
        }
        this.popper.destroy()
        this.popper = null
        document.removeEventListener('click', this.handleDocumentClick)
      },
      handleDocumentClick (e) {
        let target = e.target
        if (
          this.referenceElement === target ||
          this.popperElement === target ||
          this.referenceElement.contains(target) ||
          this.popperElement.contains(target)
        ) {
          return
        }
        this.isActive = false
      }
    }
  }
</script>