<script lang="ts" module>
export type Tab = {
	path: string,
	title: string,
	icon: string,
	component?: Component,
	hidden?: boolean,
	hide_background?: boolean,
	hide_frame?: boolean,
	subpages?: Tab[],
};
</script>
<script lang="ts">
import { onMount, type Component } from "svelte";
import { breadcrumbs_store } from "wrap/BreadcrumbStore";
import { current_page_store } from "wrap/RouterStore";

let { title = $bindable(""), pages = $bindable([]) }: {
	title?: string;
	pages?: Tab[];
} = $props();

const get_page = () => {
	current_page = null
	current_subpage = null

	for (const page of pages) {
		if (window.location.pathname.endsWith(page.path)) {
			current_page = page
		}

		if (page.subpages) {
			page.subpages.forEach(subpage => {
				if (window.location.pathname.endsWith(subpage.path)) {
					current_page = page
					current_subpage = subpage
				}
			})
		}
	}

	// If no page is active, default to home
	if (!current_page) {
		current_page = pages[0]
	}

	// If no subpage is active, default to the first subpage, if there are any
	if (!current_subpage && current_page.subpages) {
		current_subpage = current_page.subpages[0]
	}

	title = current_subpage === null ? current_page.title : current_subpage.title
	window.document.title = title+" / Nova"

	breadcrumbs_store.set(breadcrumbs)
}

let current_page: Tab = $state(null)
let current_subpage: Tab = $state(null)

onMount(() => {
	get_page()
	return current_page_store.subscribe(get_page)
})
</script>

{#snippet breadcrumbs()}
	{current_page.title}
	{#if current_subpage !== null}
		<i class="icon">chevron_right</i>
		{current_subpage.title}
	{/if}
{/snippet}

{#if current_page !== null && current_page.hide_frame !== true}
	<header>
		<div class="tab_bar">
			{#each pages as page}
				{#if !page.hidden}
					<a class="button"
						href="{page.path}"
						class:button_highlight={current_page && page.path === current_page.path}
					>
						<i class="icon">{page.icon}</i>
						<span>{page.title}</span>
					</a>
				{/if}
			{/each}
		</div>
	</header>
{/if}

{#if current_page !== null}
	<div id="page_content" class:page_content={current_page.hide_background !== true}>
		{#if current_page.subpages}
			<div class="tab_bar submenu">
				{#each current_page.subpages as page}
					{#if !page.hidden}
						<a class="button"
							href="{page.path}"
							class:button_highlight={current_subpage && page.path === current_subpage.path}
						>
							<i class="icon">{page.icon}</i>
							<span>{page.title}</span>
						</a>
					{/if}
				{/each}
			</div>

			{#if current_subpage}
				<current_subpage.component />
			{/if}
		{:else}
			<current_page.component />
		{/if}
	</div>
{/if}

<style>

header, .submenu {
	border-bottom: 1px solid var(--separator);
}
.tab_bar > .button {
	flex-direction: column;
	gap: 0;
}
.button_highlight {
	background: var(--body_background);
}
</style>
