<script lang="ts">
	import { goto } from "$app/navigation";
	import { page } from "$app/stores";
	import { TOKEN_KEY, type User } from "$lib/api";
	import { addToast } from "$lib/toast";
	import {
		Navbar,
		NavbarBrand,
		NavbarToggler,
		Collapse,
		Nav,
		NavItem,
		NavLink,
		Dropdown,
		DropdownToggle,
		DropdownMenu,
		DropdownItem,
	} from "@sveltestrap/sveltestrap";

	export let user: User | null;

	let isOpen = false;

	const logOut = async () => {
		localStorage.removeItem(TOKEN_KEY);

		addToast({ header: "Logged out", body: "Successfully logged out." });

		await goto("/", { invalidateAll: true });
	};
</script>

<Navbar expand="lg" color="dark" dark={true}>
	<NavbarBrand href="/">Catalogger</NavbarBrand>
	<NavbarToggler on:click={() => (isOpen = !isOpen)} />
	<Collapse {isOpen} navbar expand="lg">
		<Nav class="ms-auto" navbar>
			<NavItem>
				<NavLink href="/" active={$page.url.pathname === "/"}>About</NavLink>
			</NavItem>
			{#if user}
				<Dropdown nav inNavbar>
					<DropdownToggle nav caret>
						<img
							src={user.avatar_url}
							alt="Your avatar"
							style="border-radius: 0.75em; height: 1.5em;"
						/>
						{user.tag}
					</DropdownToggle>
					<DropdownMenu end>
						<DropdownItem
							href="/dash"
							active={$page.url.pathname.startsWith("/dash")}
						>
							Dashboard
						</DropdownItem>
						<DropdownItem on:click={logOut}>Log out</DropdownItem>
					</DropdownMenu>
				</Dropdown>
			{:else}
				<NavItem>
					<NavLink href="/api/authorize">Log in with Discord</NavLink>
				</NavItem>
			{/if}
		</Nav>
	</Collapse>
</Navbar>
