<script lang="ts">
    import {error_banner, info_banner, rpc, session, show_working, token, workingWrapperO} from './store';
    import {Banner, Navbar, NavBrand, Spinner} from 'flowbite-svelte';
    import Router, {replace} from 'svelte-spa-router';
    import {routes} from './routes';
    import {FileStorage} from './icons';
    import LinkButton from './components/LinkButton.svelte';
    import A from './components/A.svelte';

    const s = session.s;

    async function leaveSudo() {
        await workingWrapperO(() => rpc.Admin_unsudo($token ?? ''));
        await session.update($token);
        await replace('/admin');
    }

    function logout() {
        rpc.Auth_logout($token ?? '');
        token.set(null);
    }
</script>

<main class="h-screen w-screen p-4 flex flex-col">
    {#if $error_banner.length > 0}
        <Banner dismissable position="absolute" divClass="z-10 flex justify-between p-4 !bg-red-50" on:close={() => error_banner.set('')}>
            {$error_banner}
        </Banner>
    {/if}
    {#if $info_banner.length > 0}
        <Banner dismissable position="absolute" on:close={() => info_banner.set('')}>
            {$info_banner}
        </Banner>
    {/if}
    {#if $show_working}
        <Banner position="absolute" dismissable={false}><Spinner size="5" class="mr-2" />Working</Banner>
    {/if}
    <Navbar class="flex-grow-0">
        <NavBrand href={$token == null ? '#/login' : '#/view/0'}>
            <FileStorage width="1.5em" height="1.5em"/>
            <span id="navbar-text" class="ml-2">MFileserver</span>
        </NavBrand>

        {#if $token != null}
            <div class="flex md:order-2 gap-x-2">
                {#if $s?.sudo} <LinkButton on:click={leaveSudo}>Leave sudo</LinkButton> {/if}
                {#if $s?.admin} <A href="#/admin">Admin</A> {/if}
                <A href="#/view/0">Files</A>
                <A href="#/profile">Profile</A>
                <LinkButton on:click={logout}>Logout</LinkButton>
            </div>
        {/if}
    </Navbar>
    <span class="grid justify-items-center mt-10">
        <Router {routes} />
    </span>
</main>
