<script>
    import {onMount} from 'svelte';

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

    let {
        caption  = t('select_state'),
        onchange = (val) => console.log('changed to '+val),
        selected = $bindable(0)
    } = $props();

    let message = $state(t('loading'));
    let states  = $state(null);

    async function loadStates(){
        const url  = api('document/states');
        const resp = await fetch(url,{credentials: 'include'});
        if (resp.ok){
            states  = await resp.json();
        } else {
            message = await resp.text();
        }
    }

    onMount(loadStates)
</script>

{#if states}
<select bind:value={selected} onchange={() => onchange(selected)}>
    {#each Object.entries(states) as [k,s]}
    <option value={+k}>{t('state_'+s.toLowerCase())}</option>
    {/each}
</select>
{:else}
<span>{message}</span>
{/if}