<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue'
import { App } from '@capacitor/app'
import { useNavigationStore } from '@/stores/navigation'
import { useModalStore } from '@/stores/modal'
import { stackRoots, type StackRootNames } from '@/router'

import TabStack from '@/components/Navigation/TabStack.vue'
import ToastStack from '@/components/UI/Toast/ToastStack.vue'
import NavigationBar from '@/components/Navigation/NavigationBar.vue'

import NewPostModal from '../Modals/NewPostModal.vue'

const nav = useNavigationStore()
const modals = useModalStore()

const activeTab = computed(() => nav.activeTab)
const tabs: StackRootNames[] = stackRoots.map((p) => p.name)

const handleBackNavigation = () => {
	if (!nav.canGoBack) {
		if (activeTab.value !== 'home') {
			nav.switchTab('home')
			return
		}

		// exit if we are at root of home
		App.exitApp().catch(() => {})
	}
	nav.pop()
}

function isTypingInInput(): boolean {
	const active = document.activeElement as HTMLElement | null
	if (!active) return false
	return (
		active.tagName === 'INPUT' ||
		active.tagName === 'TEXTAREA' ||
		active.tagName === 'SELECT' ||
		active.isContentEditable
	)
}

function handleKeybings(e: KeyboardEvent) {
	if (isTypingInInput()) return
	if (!e.ctrlKey) {
		switch (e.key) {
			case 'c':
				modals.open(NewPostModal)
				break
		}
	}
}

onMounted(() => {
	App.addListener('backButton', handleBackNavigation)
	document.addEventListener('keyup', (e) => {
		if (e.key === 'e' && e.altKey) handleBackNavigation()
	})
	window.addEventListener('keyup', handleKeybings)
})

onUnmounted(() => {
	App.removeAllListeners()
	window.removeEventListener('keyup', handleKeybings)
})
</script>

<template>
	<div class="app-shell">
		<div class="skip-links">
			<a href="#main-content" id="skip-to-content" class="skip-link"> skip to main content </a>
			<a href="#navigation-bar" class="skip-link"> skip to navigation </a>
		</div>

		<div class="viewport" id="main-content">
			<ToastStack />
			<TabStack
				v-for="t in tabs"
				:key="t"
				:tab="t"
				v-show="activeTab === t"
				:class="{ active: activeTab === t }"
			/>
		</div>
		<NavigationBar ref="navBar" />
	</div>
</template>

<style scoped>
.app-shell {
	position: relative;
	height: 100vh;
	width: 100vw;
	overflow: hidden;
	background-color: hsla(var(--mantle) / 1);
	display: flex;
	flex-direction: column;
}

.viewport {
	position: relative;
	flex: 1;
	overflow: hidden;
	z-index: 0;
}

@media (min-width: 512px) {
	.app-shell {
		flex-direction: row;
		justify-content: center;
	}

	.viewport {
		flex: 1;
		order: 2;
		max-width: 668px;
	}
}

.skip-links {
	position: absolute;
	top: -100px;
	left: 0;
	z-index: 1000;
}

.skip-link {
	position: absolute;
	top: -100px;
	left: 8px;
	background: hsl(var(--overlay0));
	color: hsl(var(--blue));
	padding: 8px 16px;
	text-decoration: none;
	border-radius: 4px;
	font-weight: 600;
	z-index: 11000;
	&:focus {
		top: 128px;
		width: fit-content;
	}
}
</style>
