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

    import Autocomplete       from './Autocomplete.svelte';

    let {
        getCandidates = async text => {},
        heading       = t('add_object',{object:t('user')}),
        users         = $bindable({})
    } = $props();

    function dropUser(id){
        delete users[id];
    }

    function onSelect(entry){
        users[entry.id] = entry;
    }

    let sortedUsers = $derived.by(() => Object.values(users).sort((a, b) => a.name.localeCompare(b.name)));
</script>

<table>
    <tbody>
    {#each sortedUsers as usr,idx}
    <tr>
        <td>{usr.name}</td>
        <td>
            {#if usr.id != user.id}
            <button onclick={() => dropUser(usr.id)}>x</button>
            {/if}
        </td>
    </tr>
    {/each}
    <tr>
        <td>{heading}</td>
        <td>
            <Autocomplete {getCandidates} {onSelect} />
        </td>
    </tr>
    </tbody>
</table>
