<script setup lang="ts">
import type { Tab } from '@bagelink/vue'
import type { SetupContext, VNode } from 'vue'
import { TabsNav } from '@bagelink/vue'
import { computed, defineComponent, h, useSlots } from 'vue'

import { useTabs } from './tabsManager'

const props = defineProps<{
	tabs: Tab[]
	modelValue?: string
	flat?: boolean
}>()

const emit = defineEmits(['update:modelValue'])
const slots: SetupContext['slots'] = useSlots()
const group = Math.random().toString(36).slice(7)
const { currentTab } = useTabs(group)

const tabValue = (tab: Tab) => (typeof tab === 'string' ? tab : tab.value)

const slctTab = computed({
	get: () => props.modelValue || tabValue(props.tabs[0]),
	set: (value) => {
		emit('update:modelValue', value)
	},
})

const tabComponent = defineComponent({
	render() {
		const currentTabIndex = props.tabs.findIndex(
			tab => tabValue(tab) === currentTab.value
		)
		if (currentTabIndex === -1) { return }
		const slotChildren = slots.default?.()[1]?.children

		return h('div', (slotChildren as VNode[])[currentTabIndex])
	},
})
</script>

<template>
	<TabsNav v-model="slctTab" :flat="flat" :tabs="tabs" :group class="mb-05" />
	<div v-if="currentTab">
		<template v-if="slots[currentTab]">
			<slot :name="currentTab" />
		</template>
		<template v-else-if="currentTab">
			<component :is="tabComponent" />
		</template>
	</div>
</template>
