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

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

    let {
        caption,
        onselect = (contact) => console.log('selected '+contact.FN||contact.ORG)
    } = $props();

    let contacts = $state(null);
    let message = t('loading');
    let value   = 0;

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

    function select(){
        onselect(contacts[value]);
    }

    onMount(loadContacts)
</script>

{#if contacts}
<select onchange={select} bind:value>
    <option value={0}>{caption}</option>
    {#each contacts as contact,idx}
    <option value={idx}>{contact.FN||contact.ORG}</option>
    {/each}
</select>
{:else}
<span>{message}</span>
{/if}

