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

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

    let {
        caption,
        onselect = (company) => console.log('selected '+company.name)
    } = $props();

    let companies       = $state(null);
    let message         = t('loading');
    let value           = 0;
    let sortedCompanies = $derived.by(() => Object.values(companies).sort((a, b) => a.name.localeCompare(b.name)));

    async function loadCompanies(){
        const url  = api('company/list');
        const resp = await fetch(url,{ credentials: 'include'});
        if (resp.ok){
            companies = await resp.json();
        } else {
            message   = await resp.text();
        }
    }

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

    onMount(loadCompanies)
</script>

{#if companies}
<select onchange={select} bind:value>
    <option value={0}>{caption}</option>
    {#each sortedCompanies as company}
    <option value={company.id}>{company.name}</option>
    {/each}
</select>
{:else}
<span>{message}</span>
{/if}

