<template>
  <div
    class="popover fade show"
    v-show="popupVisible"
    :class="{ above: above, below: !above, overflow: overflow, 'bs-popover-bottom': !above, 'bs-popover-top': above }"
    ref="popup"
    @mousedown.stop
  >
    <div class="arrow"></div>
    <h3 class="popover-header"></h3>
    <div class="popover-body" v-if="popupVisible" v-scroll-stop>
      <slot>
        <!-- This is fallback content, used for the docs page -->
        Hier komt de inhoud van het popup-element.
      </slot>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.popover {
  max-width: 300px;
  width: 300px;
}

.overflow {
  .popover-body {
    max-height: 45vh;
    overflow: auto;
  }
}
</style>

<script>
export default {
  docs: 'Toont de inhoud in een popup',
  props: {
    overflow: {
      type: Boolean,
      default: false,
      docs: `Beperk de grootte van de popup, met scrollbars indien nodig.`
    }
  },
  data() {
    return {
      anchorEl: null,
      popupVisible: false,
      above: false
    };
  },
  methods: {
    show: function (anchorEl) {
      if (this.popupVisible) {
        // Clean-up, then reposition
        this.hide();
      }
      this.anchorEl = anchorEl;
      this.anchorEl.addEventListener('mousedown', this.dontBubble);
      document.addEventListener('mousedown', this.hide);
      document.addEventListener('scroll', this.hide);

      this.popupVisible = true;

      this.$nextTick(() => {
        var bcr = this.anchorEl.getBoundingClientRect();
        var bcrOffset = this.$el.offsetParent.getBoundingClientRect();
        this.$refs.popup.style.left = bcr.left - bcrOffset.left + 'px';
        this.above = bcr.top + bcr.height / 2 > window.innerHeight / 2;
        if (this.above) {
          this.$refs.popup.style.top = 'auto';
          this.$refs.popup.style.bottom = bcrOffset.bottom - bcr.top + 'px';
        } else {
          this.$refs.popup.style.top = bcr.bottom - bcrOffset.top + 'px';
          this.$refs.popup.style.bottom = 'auto';
        }
      });
    },
    hide: function () {
      if (!this.popupVisible) return;
      this.popupVisible = false;
      document.removeEventListener('scroll', this.hide);
      document.removeEventListener('mousedown', this.hide);
      this.anchorEl.removeEventListener('mousedown', this.dontBubble);
      this.anchorEl = null;
    },
    toggle: function (anchorEl) {
      if (this.popupVisible) {
        this.hide();
      } else {
        this.show(anchorEl);
      }
    },
    dontBubble(event) {
      event.cancelBubble = true;
    }
  }
};
</script>
