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

    import { api }           from '../../urls.svelte.js';
    import { error }  from '../../warn.svelte';
    import { t }             from '../../translations.svelte.js';

    let caption  = t('send_mail');
    let mail     = "";
    const router = useTinyRouter();

    async function submit(ev){
        ev.preventDefault();
        const url  = api(`user/reset_pw`);
        const resp = await fetch(url,{
            method : 'POST',
            body   : mail
        });
        if (resp.ok) {
            caption = t('data_sent');
        } else {
            caption = await resp.text();
        }
    }

    async function checkToken(){
        const urlParams = new URLSearchParams(window.location.search);
        const token     = urlParams.get('token');
        if (token) {
            const url  = api(`user/validate/${token}`);
            const resp = await fetch(url,{
                credentials: 'include'
            });
            if (resp.ok){
                router.navigate('/user')
            } else {
                error(resp);
            }
        }
    }

    onMount(checkToken);


</script>

<style>
    label{display:block}
    fieldset{
        display       : block;
        position      : relative;
        left          : 50%;
        width         : 200px;
        margin-left   : -100px;
        margin-bottom : 30px;
        text-align    : center;
    }
</style>

<form onsubmit={submit}>
<fieldset>
    <legend>{t('reset_pw')}</legend>
    <label>
        <input type="email" bind:value={mail}/>
        {t('enter_email')}
    </label>
    <button type="submit">{caption}</button>
</fieldset>
</form>