<script lang="ts">
	import type { LayoutData } from './$types';
	import { goto } from '$app/navigation';

	import Analytics from 'analytics';
	// import doNotTrack from 'analytics-plugin-do-not-track';
	// import googleAnalytics from '@analytics/google-analytics';

	const analytics = Analytics({
		app: 'Barretthousen - Web Client',
		version: '1.0',
		debug: process.env.NODE_ENV !== 'production',
		plugins: [
			// googleAnalytics({
			// 	measurementIds: ['UA-143763293-1']
			// })
			// doNotTrack()
		]
	});

	/* Track a page view */
	analytics.page();

	import SearchBox from '$lib/SearchBox.svelte';

	import AuthForm from '$lib/AuthForm.svelte';
	import '../app.css';
	import { loginAction, logoutAction, registerAction, session } from '$lib/state';

	export let data: LayoutData;

	async function onLogin(evt: CustomEvent) {
		const { email, password } = evt.detail;
		await loginAction({ email, password });
	}

	async function onLogout() {
		analytics.track('user.logout', {});
		logoutAction();
	}

	async function onRegister(evt: CustomEvent) {
		const { email, password } = evt.detail;
		analytics.track('user.register', { email });
		await registerAction({ email, password });
	}

	async function onSubmit(evt: CustomEvent) {
		let { query } = evt.detail;

		// TODO: refactor to one source of truth for building query string parameters
		await goto(query ? `/?query=${query}` : '/', {
			invalidateAll: true
		});

		analytics.track('user.query', { query });
	}

	interface SessionInfo {
		sessionId?: string;
		account?: {
			id: string;
			email: string;
			role: 'BIDDER' | 'USER' | 'ADMINISTRATOR' | 'ANONYMOUS';
			createdTs: string;
		};
	}

	let sessionVal: SessionInfo;

	session.subscribe((v) => {
		sessionVal = v;
		if (v && v.sessionId && v.account) {
			const { id, email, role } = v.account;
			analytics.identify(id, { email, role });
		}
	});

	$: isLoggedIn = !!sessionVal?.sessionId;
	// $: pageTitle =
	// 	data.query !== ''
	// 		? `'${data.query}' Search`
	// 		: 'Barretthousen: The best rare collectibles from all over the web';
</script>

<svelte:head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />

	<title>Barretthousen: The best rare collectibles from all over the web</title>

	<meta name="description" content="Search results for '{data.query}'" />
</svelte:head>

<main class="flex flex-col w-full">
	<nav
		class="flex w-full bg-bh-gold text-bh-black fixed top-0 left-0 right-0"
		style="height: 80px;"
	>
		<img
			class="pr-5"
			style="width: 450px; height: 80px;"
			src="/logo_black_gold.svg"
			alt="BarrettHousen"
		/>
		<ul class="flex w-full py-3 items-center justify-between">
			<li class="flex grow justify-center">
				<span class="flex grow" style="max-width: 75%;">
					<SearchBox on:search={onSubmit} query={data.query} page={data.page} />
				</span>
			</li>
			<li class="pr-5">
				<!-- <span>I want email alerts!</span> -->
				{#if !isLoggedIn}
					<AuthForm on:login={onLogin} on:register={onRegister} />
				{:else}
					<span>
						{sessionVal.account?.email}
					</span>
					<button
						class="bg-bh-gold border-bh-black px-2 py-1 text-bh-black"
						on:click|stopPropagation={onLogout}>Log out</button
					>
				{/if}
			</li>
		</ul>
	</nav>
	<div class="flex flex-row flex-grow h-full" style="padding-top: 80px;">
		<div id="gutter" class="h-full" style="min-width: 195px; max-width: 195px;" />
		<section id="content" class="py-6 pl-4 grow border-l border-bh-gold" style="min-height: 100vh;">
			<slot />
		</section>
	</div>
	<footer
		class="flex justify-center bg-bh-gold text-bh-black w-full py-10 shadow-inner shadnow-md shadow-bh-black"
	>
		<p>
			We find great auctions of rare and one of a kind collectibles from around the web and compile
			them in one easy place.
		</p>
	</footer>
</main>
