<script>
import { onMount }       from 'svelte';
import { useTinyRouter } from 'svelte-tiny-router';

import { api, get }      from '../urls.svelte';
import { error }         from '../warn.svelte';
import { logout, user }  from '../user.svelte';
import { t }             from '../translations.svelte';

import TimeRecorder from './TimeRecorder.svelte';

let key = $state(null);
const router  = useTinyRouter();
let modules = $state(null);
let expand = $state(false);

async function fetchModules(){
    let url = api('settings/menu');
    const res = await get(url);
    if (res.ok){
        modules = await res.json();
    } else {
        error(res);
    }
}

function onclick(e){
    e.preventDefault();
    expand = false;
    let href = e.target.getAttribute('href');
    if (href) {
        if (href.includes('://')) {
            window.location.href = href;
        } else router.navigate(href);
    }
    return false;
}

async function search(e){
    e.preventDefault();
    expand = false;
    router.navigate(`/search?key=${key}`);
    return false;
}

onMount(fetchModules);
</script>

<style>
    nav a{
        padding: 3px;
    }
</style>

<nav class={expand?"expanded":"collapsed"}>
    <form onsubmit={search}>
        <input type="text" bind:value={key} />
        <button type="submit">{t('search')}</button>
    </form>
    <button class="symbol" onclick={e => expand = !expand}> </button>
    {#each modules as module,i}
    <a href={module.module.includes('://') ? module.module : '/'+module.module} {onclick} class={module.class}>{@html t(module.title)}</a>
    {/each}
    {#if user.id == 2}
    <a href="https://svelte.dev/tutorial/svelte/state" target="_blank">{t('tutorial')}</a>
    {/if}
    {#if user.name }
    <a class="logout" onclick={logout}>{t('logout_user',{user:user.name})}</a>
    {/if}
    <TimeRecorder />
</nav>
