<template>
    <div class="pmb-tabs-list" role="tablist" :aria-label="ariaLabel">
        <span
            v-for="tab in tabs"
            :key="tab.id"
            class="pmb-tabs-item"
            :class="{ 'pmb-tabs-item-locked': tab.locked }"
        >
            <button
                type="button"
                role="tab"
                :id="'tab_' + tab.id"
                :aria-selected="tab.id === active ? 'true' : 'false'"
                :aria-controls="tab.id"
                :tabindex="tab.id === active ? 0 : -1"
                ref="tabButtons"
                class="pmb-tabs-tab"
                :class="{ 'pmb-tabs-tab-active': tab.id === active }"
                @click="onTabClick(tab)"
                @keydown="onKeydown($event, tab)"
            >{{ tab.title }}</button>
            <button
                v-if="tab.closable && !tab.locked"
                type="button"
                class="pmb-tabs-tab-close"
                :aria-label="closeLabel(tab)"
                @click.stop="close(tab)"
            ><i class="fa fa-times" aria-hidden="true"></i></button>
        </span>
    </div>
</template>

<script>
export default {
  name: "tabs",
  props: {
    tabs: {
      type: Array,
      required: true
    },
    active: {
      type: String,
      default: null
    },
    ariaLabel: {
      type: String,
      default: ""
    },
    closeLabelTemplate: {
      // Gabarit du libelle accessible du bouton de fermeture, avec "%s"
      // remplace par le titre de l'onglet (fourni par l'appelant : ce
      // composant est generique, il ne connait aucune cle de traduction).
      type: String,
      default: "Close %s"
    }
  },
  methods: {
    onTabClick(tab) {
      this.select(tab);
    },
    select(tab) {
      this.$emit("select", tab);
    },
    close(tab) {
      this.$emit("close", tab);
    },
    closeLabel(tab) {
      return this.closeLabelTemplate.replace("%s", tab.title);
    },
    onKeydown(event, tab) {
      const buttons = this.$refs.tabButtons;
      if (!buttons || !buttons.length) {
        return;
      }
      const currentIndex = this.tabs.findIndex(t => t.id === tab.id);
      const lastIndex = this.tabs.length - 1;
      let targetIndex = null;
      switch (event.key) {
        case "ArrowLeft":
          targetIndex = (currentIndex - 1 + this.tabs.length) % this.tabs.length;
          break;
        case "ArrowRight":
          targetIndex = (currentIndex + 1) % this.tabs.length;
          break;
        case "Home":
          targetIndex = 0;
          break;
        case "End":
          targetIndex = lastIndex;
          break;
        default:
          return;
      }
      if (buttons[targetIndex]) {
        event.preventDefault();
        buttons[targetIndex].focus();
      }
    }
  }
}
</script>
