<template>
    <div>
        <div class="sm:hidden my-4">
            <div class="font-bold mb-2">Tab Menu</div>
            <select class="form-select block w-full rounded-sm"
                    aria-label="Selected tab"
                    @change="selectTab($event.target.value)"
            >
                <option v-for="tab in tabs" :value="tab.href" :selected="isSelected(tab)">
                    {{ tab.name }}
                </option>
            </select>
        </div>
        <div
            :class="['hidden px-4 mb-6 bg-white shadow sm:px-6 sm:block sm:rounded-bl-sm sm:rounded-br-sm', classList]"
        >
            <nav class="flex flex-wrap -mb-px">
                <a v-for="(tab, index) in tabs"
                   :class="['mr-8', isActive(tab)]"
                   :href="tab.href"
                   @click="selectTab(tab)"
                   class="group inline-flex items-center py-3 px-1 border-b-2 font-medium text-sm leading-5 focus:outline-none"
                >
                    <span>{{ tab.name }}</span>
                </a>
            </nav>
        </div>
        <div class="tabs-container">
            <slot></slot>
        </div>
    </div>
</template>


<script>
export default {
    props : {
        classList : {
            type : String
        }
    },
    data() {
        return {
            tabs : [],
        }
    },
    created() {
        this.tabs = this.$children;
    },
    methods : {
        selectTab(selectedTab) {
            let href = (typeof selectedTab === 'string' ? selectedTab : selectedTab.href);
            this.tabs.forEach(tab => {
                tab.isActive = false;
                if ((tab.href === href)) {
                    tab.isActive = true;
                    window.EventBus.$emit('tabActive', tab);
                }
            });
        },
        isSelected(tab) {
            return tab.href === location.hash;
        },
        isActive(tab) {
            return tab.isActive
                ? 'border-gray-500 text-gray-600 focus:text-gray-800 focus:border-gray-700'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:text-gray-700 focus:border-gray-300'
        }
    },
    mounted() {
        if (location.hash) {
            this.tabs.forEach(tab => {
                tab.isActive = false;
                if (this.isSelected(tab)) {
                    tab.isActive = true;
                    window.EventBus.$emit('tabActive', tab);
                }
            });
        }
    }
}
</script>
