<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 error = $state(null);
    let {
        getCandidates = async text => {},
        heading       = t('add_user'),
        users         = $bindable({})
    } = $props();

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

    function onSelect(entry){
        for (let [k,v] of Object.entries(entry)){
            users[k] = {name:v,id:k};
        }
    }

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

{#if error}
<span class="error">{error}</span>
{/if}
<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>
