<template>
  <div>
    <slot />
  </div>
</template>
<script>
  export default {
    name: 'TfTabWrapper',
    componentName: 'TfTabWrapper',

    inject: {
      $themeActiveTabColor: { default: () => null },
    },
    computed: {
      /**
       * Return color value as reactive value
       *
       * @returns {string | null}
       */
      themeActiveTabColor() {
        return this.$themeActiveTabColor ? this.$themeActiveTabColor() : null;
      },
    },

    watch: {
      /**
       * toggle colors when themeActiveTabColor changes
       */
      themeActiveTabColor() {
        this.toggleColors();
      },
    },

    mounted() {
      this.toggleColors();
    },

    methods: {
      /**
       * Update all the colors with inline styles if needed.
       */
      toggleColors() {
        this.$nextTick(() => {
          const tabItems = this.$el.querySelectorAll('.el-tabs__item');
          const activeTabItem = this.$el.querySelector('.is-active');

          // eslint-disable-next-line no-restricted-syntax
          for (const tabItem of tabItems) {
            // clear out existing active styles
            tabItem.removeAttribute('style');

            // stick in a listener once so we don't have to observe state
            if (tabItem.className.indexOf('has-listener') === -1) {
              tabItem.addEventListener('click', () => { this.toggleColors(); });
              tabItem.className += ' has-listener';
            }
          }

          if (!this.themeActiveTabColor) {
            if (activeTabItem) {
              activeTabItem.removeAttribute('style');
            }
            return;
          }
          if (activeTabItem) {
            activeTabItem.style.color = this.themeActiveTabColor;
          }
        });
      },
    },
  };
</script>
