<script>
	import {end_session} from "$shared/lib/session";
	import {onMount} from "svelte";
	import {Menu, MenuItem, MenuItemSeparator} from "$shared/components/menu";
	import {replace} from "svelte-spa-router";

	let userMenuTrigger;
	let showUserMenu = false;

	export let avatar = "";
	export let name;
	export let secondary = "";
	let userMenuId;

	async function on_logout() {
		await end_session(() => {
			replace("/login");
		});
	}

	onMount(() => {
		userMenuTrigger = document.getElementById("open-user-menu");
	});
</script>

<button class="reset user-menu-control"
        id="open-user-menu"
        aria-controls="{userMenuId}"
        on:click={() => showUserMenu = true}>
    {#if avatar}
        <figure class="user-menu-control__img-wrapper radius-50%">
            <img class="user-menu-control__img"
                 src="{avatar}"
                 alt="Avatar">
        </figure>
    {/if}

    <div class="margin-x-xs user-menu__meta">
        <p class="user-menu__meta-title text-sm line-height-1 padding-y-xxxxs font-semibold color-contrast-higher text-truncate">{name}</p>
        {#if secondary}
            <p class="text-xs color-contrast-medium line-height-1 padding-bottom-xxxxs">{secondary}</p>
        {/if}
    </div>

    <svg class="icon icon--xxs"
         aria-hidden="true"
         viewBox="0 0 12 12">
        <polyline points="1 4 6 9 11 4"
                  fill="none"
                  stroke="currentColor"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"/>
    </svg>
</button>

<Menu trigger={userMenuTrigger}
      bind:id={userMenuId}
      bind:show="{showUserMenu}">
    <div slot="options">
        <MenuItem on:click={() => replace("/profile")}>
            <span>Profile</span>
        </MenuItem>
        <MenuItemSeparator/>
        <MenuItem danger="true"
                  on:click={() => on_logout()}>
            Logout
        </MenuItem>
    </div>
</Menu>
