<script setup lang="ts">
import type { Raw } from 'vue'
import type { Router } from 'vue-router'
import { onMounted, ref } from 'vue'

const props = defineProps<{
	title?: string
	tabs: string[]
	modelValue?: string
	router?: Raw<Router>
	sideTabs?: boolean
}>()

const emit = defineEmits(['update:modelValue'])

const activeTab = ref<string>()
function changeTab(tab: string) {
	activeTab.value = tab
	emit('update:modelValue', activeTab.value)
	if (!props.router) { return }
	void props.router.push({
		path: props.router.currentRoute.value.path,
		query: { ...props.router.currentRoute.value.query, t: tab },
		hash: props.router.currentRoute.value.hash,
	})
}

onMounted(() => {
	const firstTab
		= props.modelValue
			|| props.router?.currentRoute.value.query.t
			|| props.tabs[0]
	activeTab.value = firstTab as string
})
</script>

<template>
	<div class="h-100 grid list-view gap-1" :class="{ 'side-tabs': sideTabs }">
		<div class="bgl_card tabs-top">
			<slot name="top-section" />
			<div class="tabs grid auto-flow-columns fit-content">
				<div
					v-for="tab in tabs" :key="tab" :class="{
						active:
							tab === activeTab
							|| tab === router?.currentRoute.value.path.split('/').slice(-1)[0],
					}" class="tab" @click="changeTab(tab)"
				>
					{{ tab }}
				</div>
			</div>
		</div>
		<div v-for="tab in tabs.filter((item) => item === activeTab)" :key="tab" class="list-content">
			<slot :key="tab" :name="tab" />
		</div>
	</div>
</template>

<style scoped>
.tab {
	text-transform: capitalize;
}

.side-tabs {
	display: flex;
}

.side-tabs .tabs-top {
	margin-inline-end: 1rem;
}

.side-tabs .tabs {
	display: block;
	padding: 0;
	margin: 0;
	border: none;
}

.side-tabs .tab {
	border: none;
}
</style>
