<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'
import { IconArrowBackRounded } from '@iconify-prerendered/vue-material-symbols'
import { useNavigationStore, type StackEntry, type TabKey } from '@/stores/navigation'

const appBarElement = ref<HTMLElement | null>(null)
const overlayElement = ref<HTMLElement | null>(null)
defineExpose({ $el: appBarElement, $overlay: overlayElement })

const nav = useNavigationStore()
const props = defineProps<{
	left?: number
	root?: boolean
	title?: string
}>()

const mountedStack = ref<StackEntry[] | null>(null)
const canGoBack = ref(false)

onMounted(() => {
	if (!appBarElement.value) {
		const inst = getCurrentInstance()
		const root = inst?.proxy?.$el as HTMLElement | undefined
		if (root instanceof HTMLElement) appBarElement.value = root
	}

	if (!appBarElement.value) return

	let contextTab: TabKey | null = null
	let contextEntryId: string | null = null

	const tabEl = appBarElement.value.closest('[data-tab]')
	if (tabEl instanceof HTMLElement && tabEl.dataset.tab) contextTab = tabEl.dataset.tab as TabKey

	const entryEl = appBarElement.value.closest('[data-entry-id]')
	if (entryEl instanceof HTMLElement && entryEl.dataset.entryId) {
		contextEntryId = entryEl.dataset.entryId
	}

	const tab = (contextTab ?? nav.activeTab) as TabKey
	const s = nav.stacks[tab]
	mountedStack.value = s ?? null

	if (props.root || !s || s.length <= 1) {
		canGoBack.value = false
		return
	}

	if (contextEntryId) {
		const index = s.findIndex((e: StackEntry) => e.id === contextEntryId)
		canGoBack.value = index > 0
		return
	}

	canGoBack.value = true
})

function goBack() {
	if (canGoBack.value) nav.popStack()
}
</script>

<template>
	<div ref="appBarElement" class="app-bar">
		<button v-if="canGoBack" @click="goBack" class="back-button" aria-label="Go back" type="button">
			<IconArrowBackRounded class="icon" aria-hidden="true" />
		</button>
	</div>
</template>

<style lang="scss" scoped>
.back-button {
	border: none;
	background: transparent;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	color: hsl(var(--text));
	border-radius: 50%;
	padding: 0.5rem;

	&:hover {
		background: hsla(var(--surface0) / 1);
	}
	&:active {
		background: hsla(var(--surface0) / 0.5);
	}

	.icon {
		width: 1.5rem;
		height: 1.5rem;
	}
}
</style>
