<script>
    import { onMount }  from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';
    import { api }           from '../../urls.svelte';
    import { error, yikes }  from '../../warn.svelte';
    import { t }             from '../../translations.svelte';

    let lastLetter = null;
    let pages      = $state(null);
    let router     = useTinyRouter();

    function onclick(e){
        e.preventDefault();
        let href = e.target.getAttribute('href');
        if (href) router.navigate(href);
        return false;
    }

    async function loadPageList(){
        const url = api('wiki');
        const res = await fetch(url,{credentials:'include'});
        if (res.ok){
            pages = await res.json();
            yikes();
        } else {
            error(res);
        }
    }

    onMount(loadPageList);
</script>

<h1>{t('wiki')}</h1>
<button onclick={() => router.navigate('/wiki/add')}><span class="symbol"></span> {t('create_new_object',{object:t('page')})}</button>

{#if pages}
{#each pages as page}
{#if page.charAt(0).toUpperCase() != lastLetter}

<h2>{lastLetter = page.charAt(0).toUpperCase()||page.charAt(0).toUpperCase()}</h2>
{/if}
<a class="wikilink" href={`/wiki/${encodeURIComponent(page)}/view`} {onclick} >{page}</a>
{/each}
{/if}