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

    import Markdown          from '../../Components/MarkdownEditor.svelte';

    let content = $state({source:null,rendered:null});
    let router  = useTinyRouter();
    let timer   = null;
    let title   = $state(null);

    async function onsubmit(ev){
        ev.preventDefault();
        ev.stopPropagation();
        const url = api(`wiki/${title}`);
        const res = await fetch(url,{
            credentials:'include',
            method:'POST',
            body:content.source
        });
        if (res.ok){
            yikes();
            localStorage.removeItem('wiki/new/content');
            router.navigate(`/wiki/${title}/view`);
        } else {
            error(res);
        }
    }

    function checkTitle(){
        if (title) {
            if (timer) clearTimeout(timer);
            timer = setTimeout(requestTitle,1000);
        }
    }

    async function requestTitle(){
        timer = null;
        var url = api(`wiki/available/${title}`);
        var res = await fetch(url,{credentials:'include'});
        const body = await res.text();
        if (res.ok){
            if (body == 'true') {
                yikes();
            } else error(t('title_not_available',{title:title}));
        } else {
            error(body ? body : t('failed_to_check_availability'));
        }
    }

    $effect(checkTitle)
</script>

<h1>{t('create_new_object',{object:t('page')})}</h1>
<form {onsubmit}>
    <label>
        {t('Name')}
        <input type="text" bind:value={title} />
    </label>
    <label>
        {t('content')}
        <Markdown bind:value={content} simple={true} store_id="wiki/new/content" />
        <button type="submit">{t('save')}</button>
    </label>
</form>