<script>
    import { api } from '../../urls.svelte.js';
    import { t }   from '../../translations.svelte.js';

    let { editPassword = $bindable() } = $props();

    let caption  = $state(t('update'));
    let newPass  = $state("");
    let mismatch = $derived(newPass != repeat);
    let newEmpty = $derived(!/\S/.test(newPass));
    let oldPass  = $state("");
    let oldEmpty = $derived(!/\S/.test(oldPass));
    let repeat   = $state("");
    let sent     = $state(false);

    function abort(){
        editPassword = false;
    }

    async function submit(){
        caption    = t('data_sent');
        const url  = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/password`;
        const data = {
            old : oldPass,
            new : newPass
        };
        const resp = await fetch(url,{
            method      : 'PATCH',
            body        : JSON.stringify(data),
            credentials : 'include'
        });

        if (resp.ok){
            caption = t('saved');
        } else {
            caption = t('failed');
        }
    }
</script>

<style>
    label{
        display: block;
    }
</style>

<fieldset class="overlay">
    <legend>{t('edit_password')}</legend>
    <label>
        <input type="password" bind:value={oldPass} /> {t('old_password')}
        {#if oldEmpty}
        <span class="error">{t('must_not_be_empty')}</span>
        {/if}
    </label>
    <label>
        <input type="password" bind:value={newPass} /> {t('new_password')}
        {#if newEmpty}
        <span class="error">{t('must_not_be_empty')}</span>
        {/if}
    </label>
    <label>
        <input type="password" bind:value={repeat} /> {t('repeat_new_password')}
        {#if mismatch}
        <span class="error">{t('mismatch')}</span>
        {/if}
    </label>
    <button onclick={submit} disabled={sent||oldEmpty||newEmpty||mismatch}>{caption}</button>
    <button onclick={abort} disabled={sent}>{t('abort')}</button>
</fieldset>