<script lang="ts">
	import Button from '$lib/Button.svelte';
	import Spacer from '$lib/Spacer.svelte';
	import { onMount } from 'svelte';

	import Avif from './logo.avif?w=192&format=avif';
	import Jpeg from './logo.avif?w=192&format=jpeg';
	import WebP from './logo.avif?w=192&format=webp';
	import List from 'phosphor-svelte/lib/List';
	import { afterNavigate } from '$app/navigation';
	// @ts-ignore
	import { PagefindUI } from '@pagefind/default-ui';
	import '@pagefind/default-ui/css/ui.css';

	function loadPagefind() {
		// @ts-ignore
		new PagefindUI({ element: '#search', showSubResults: true });
	}

	onMount(() => {
		try {
			console.debug('Pagefind loaded, not waiting');
			loadPagefind();
			console.debug('Pagefind not loaded, waiting for DOMContentLoaded');
		} catch (e) {
			window.addEventListener('DOMContentLoaded', () => {
				loadPagefind();
			});
		}
	});

	let expanded = false;

	afterNavigate(() => {
		expanded = false;
	});
</script>

<header>
	<a class="logo" href="/">
		<picture>
			<source srcset={Avif} type="image/avif" />
			<source srcset={WebP} type="image/webp" />
			<img
				src={Jpeg}
				class="circle"
				alt="A vibrant and artistic representation of the letters KBG. Each letter is made out of multiple curved black lines running together, and is adorned with colorful leaves. The ends of the letters extend and narrow into thin lines capped with colorful dots."
			/>
		</picture>
	</a>
	<Spacer />
	<div class="collapse-container">
		<div class="collapse" class:expanded>
			<div id="search"></div>
			<Button href="/posts/">Blog</Button>
			<Button href="/portfolio/">Portfolio</Button>
		</div>
	</div>
	<button
		class="hamburger"
		on:click={() => {
			expanded = !expanded;
		}}
	>
		<List aria-label="menu" />
	</button>
</header>

<style lang="scss">
	@import '../vars';
	@import '../button';

	header {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-right: 4rem;
		gap: 2rem;
		margin-bottom: -3rem;
	}
	@media (max-width: $size-container) {
		header {
			margin-bottom: unset;
		}
	}
	.collapse-container {
		position: relative;
	}
	.collapse {
		display: flex;
		flex-direction: row;
		gap: 1rem;
		align-items: center;
	}
	.hamburger {
		@include button($color-primary, $color-primary-text, 1.5);
		display: none;
		flex-direction: row;
	}

	@media (max-width: $size-container) {
		header {
			margin-right: 1.5rem;
		}

		#search {
			width: 100%;
		}

		.collapse {
			z-index: 1;
			display: none;
			position: absolute;
			right: 0;
			flex-direction: column;
			align-items: end;
			background-color: $color-bg;
			width: calc($min-w-supported * 0.66);
			box-shadow: $shadow-medium;
			padding: 1.5rem;

			&.expanded {
				display: flex;
			}
		}
		.hamburger {
			display: flex;
		}
	}

	.logo {
		width: 12rem;
		height: 12rem;
	}
</style>
