<script>
    import {onMount} from "svelte";
    import {location, link} from "svelte-spa-router";
    import {logout_user} from "$app/lib/services/user-service";
    import {random_string} from "$shared/lib/helpers";
    import {get_session_data} from "$shared/lib/session";
    import ProfileModal from "$app/pages/views/profile-modal.svelte";
    import {Menu, MenuItem, MenuItemSeparator} from "$shared/components/menu";
    import Button from "$shared/components/button.svelte";
    import {IconNames} from "$shared/lib/configuration";
    import LL from "$app/lib/i18n/i18n-svelte";
    import BlowoutToolbelt from "$shared/components/blowout-toolbelt.svelte";
    import {NavWrapper, NavItem} from "./nav";

    let ProfileModalFunctions = {};
    let showUserMenu = false;
    let userMenuTriggerNode;
    const userMenuId = "__menu_" + random_string(3);
    const username = get_session_data()?.profile.username;

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

<ProfileModal bind:functions={ProfileModalFunctions}/>
<BlowoutToolbelt/>

<NavWrapper>
    <ul slot="navigation-items">
        <NavItem to="/home" text="{$LL.nav.home()}"/>
        <NavItem to="/data" text="{$LL.nav.data()}"/>
        <NavItem to="/settings" text="{$LL.nav.settings()}"/>
    </ul>
    <div slot="navigation-footer" class="tabs-nav-v2 justify-between">
        <div class="tab-v2 padding-x-sm">
            <Button class="user-menu-control"
                    variant="reset"
                    id="open-user-menu"
                    on:click={() => showUserMenu = !showUserMenu}
                    text={username}
                    icon={IconNames.chevronDown}
                    icon_width="2rem"
                    icon_height="2rem"
                    icon_right_aligned="true"
                    title="{$LL.nav.usermenu.toggleTitle()}"
                    aria-controls="{userMenuId}"
            />
            <Menu bind:show="{showUserMenu}"
                  trigger={userMenuTriggerNode}
                  id="{userMenuId}">
                <div slot="options">
                    <MenuItem on:click={() => ProfileModalFunctions.open()}>
                        <span title="{$LL.nav.usermenu.profileTitle()}">{$LL.nav.usermenu.profile()}</span>
                    </MenuItem>
                    <MenuItemSeparator/>
                    <MenuItem danger="true"
                              on:click={() => logout_user()}>
                        <span title="{$LL.nav.usermenu.logoutTitle()}">{$LL.nav.usermenu.logout()}</span>
                    </MenuItem>
                </div>
            </Menu>
        </div>
    </div>
    <slot slot="main-content"/>
</NavWrapper>