<script>
    import {onMount} from 'svelte';
    import {t} from '../translations.svelte.js';
    let { caption, onselect = (contact) => console.log('selected '+contact.FN||contact.ORG) } = $props();
    let message = t('contacts.loading');
    let contacts = $state(null);
    let value = 0;

    async function loadContacts(){
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/document/contacts`;
        var 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}

