<script>
    import Card             from './Card.svelte';
    import { byName }       from '../../vcard.js';
    import { api }          from '../../urls.svelte';
    import { error, yikes } from '../../warn.svelte';
    import { onMount }      from 'svelte';
    import { t }            from '../../translations.svelte';

    let contacts = $state(null)

    async function load(){
        const url = api('contact/list');
        const res = await fetch(url,{credentials:'include'});
        if (res.ok){
            yikes();
            var data = await res.json();
            contacts = Object.values(data).sort(byName);
            contacts.unshift({
                id: 0,
                vcard: `BEGIN:VCARD
VERSION:3.0
PRODID:Umbrella Contact manager by SRSoftware
FN:${t('formatted_name')}
N:${t('family_name')};${t('given_name')};;;
ORG:${t('organization')}
EMAIL;TYPE=WORK:${t('email')}
ADR;TYPE=WORK:;;${t('street')};${t('locality')};${t('region')};${t('post_code')};${t('country')}
TEL;TYPE=CELL;:${t('phone_cell')}
X-TAX-NUMBER:${t('tax_id')}
X-BANK-ACCOUNT:${t('bank_account')}\\nIBAN:XXXX\\nBIC:XXXX
X-COURT:${t('local_court')}
URL:https://example.com
END:VCARD`
            });
        } else {
            error(res);
        }
    }

    onMount(load);
</script>

<h1>{t('contacts')}</h1>
{#each contacts as contact}
<Card {contact} />
{/each}