<template>
  <button
    ref="tabItem"
    :disabled="disabled"
    :class="[wrapperClass, tabWrapperClasses]"
    v-on="$listeners"
    @click="update"
  >
    <slot />
  </button>
</template>

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "NTab",
  inject: {
    selectedValue: {
      from: "selectedValue",
      default: "",
    },
    updateValue: {
      from: "updateValue",
      default: undefined,
    },
    variant: {
      from: "variant",
      default: "text",
    },
  },
  props: {
    wrapperClass: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      index: 0,
    };
  },
  computed: {
    isActive() {
      const { index, selectedValue } = this;

      return String(index) === String(selectedValue);
    },
    tabWrapperClasses() {
      const { isActive, variantClass } = this;
      let classes = "n-tab";

      if (variantClass) {
        classes += variantClass;
      }

      if (isActive) {
        classes += " n-tab--active";
      }

      return classes;
    },
    variantClass() {
      const { variant } = this;
      const isValidVariant = ["primary", "text"].includes(variant);

      return isValidVariant ? ` n-tab--${variant}` : "";
    },
  },
  mounted() {
    const current = this.$refs.tabItem;
    let elementPlaceholder = current;
    let count = 0;

    while (elementPlaceholder) {
      count += 1;
      elementPlaceholder = elementPlaceholder.previousElementSibling;
    }

    this.index = count ? count - 1 : count;
  },
  methods: {
    update() {
      if (!this.isActive) {
        this.updateValue(this.index);
      }
    },
  },
});
</script>
