<template>
  <div :class="{ show: isOpen }" v-on:click.stop="onClick" class="dropdown-menu-container">
    <button
      type="button"
      class="btn dropdown-toggle"
      :disabled="disabled"
      :class="[{ disabled }, buttonClass]"
      :id="dropdownName"
      @click.prevent="toggleDropdown"
      role="button"
      data-toggle="dropdown"
      aria-haspopup="true"
      :aria-expanded="isOpen"
    >
      <span v-if="iconClass" :class="iconClass"></span>{{ label }}
    </button>
    <div class="dropdown-menu" :class="{ show: isOpen }" :aria-labelledby="dropdownName">
      <div v-on:click="toggleDropdown">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import '../variables.scss';

.dropdown-menu-container {
  position: relative;
}

.dropdown-menu {
  z-index: $z-index-dropdown-menu;
}
</style>

<script>
export default {
  props: {
    label: {
      type: String,
      default: '',
      docs: `De tekst van de link waarmee je de dropdown opent.`,
      demoValue: 'Dropdown'
    },
    iconClass: {
      type: String,
      required: false
    },
    disabled: {
      type: Boolean,
      required: false
    },
    buttonClass: {
      type: String,
      required: false
    },
    dropdownName: {
      type: String,
      required: false
    }
  },
  created() {
    document.addEventListener(
      'click',
      () => {
        // close dropdown when click outside element.
        if (this.isOpen) {
          this.toggleDropdown();
        }
      },
      false
    );
  },
  data() {
    return {
      isOpen: false
    };
  },
  methods: {
    toggleDropdown() {
      this.isOpen = !this.isOpen;
    },
    onClick() {
      // purpose: clicking outside the dropdown should close the dropdown, but when clicking inside nothing should happen (stop propagation)
      return true;
    }
  }
};
</script>
