<script>
    import { onMount } from 'svelte';
    import { t } from '../../translations.svelte.js';
    import { useTinyRouter } from 'svelte-tiny-router';
    import StateSelector from './StateSelector.svelte';
    let { id } = $props();
    let error = null;
    let doc = $state(null);

    async function loadDoc(){
        const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/document/${id}`;
        const resp = await fetch(url,{credentials:'include'});
        if (resp.ok){
            doc = await resp.json();
        } else {
            error = await resp.text();
        }
    }

    onMount(loadDoc);
</script>

{#if error}
<span class="error">{error}</span>
{/if}

{#if doc}
    <fieldset>
        <legend>{t('document.customer')}</legend>
        <div>
            {#each doc.customer.name.split("\n") as line}
            {line}<br/>
            {/each}
        </div>
        <div>
            <span>{t('document.customer_number',doc.customer.id)}</span>
        </div>
        <div>
            <span>{t('document.tax_id',doc.customer.tax_id)}</span>
        </div>
        <div>
            <span>{t('document.email',doc.customer.email)}</span>
        </div>
    </fieldset>
    <fieldset>
        <legend>{t('document.sender')}</legend>
        <div>
            {#each doc.sender.name.split("\n") as line}
            {line}<br/>
            {/each}
        </div>
        <div>
            <span>{t('document.court',doc.sender.court)}</span>
        </div>
        <div>
            <span>{t('document.tax_id',doc.sender.tax_id)}</span>
        </div>
        <div>
            <span>{t('document.bank_account',doc.sender.bank_account)}</span>
        </div>
    </fieldset>
    <fieldset>
        <legend>{t('document.type_'+doc.type)}</legend>
        <div>{t('document.number')}: {doc.number}</div>
        <div>{t('document.state')}: <StateSelector /></div>
        <div>{t('document.date')}: {doc.date}</div>
        <div>{t('document.delivery')}: {doc.delivery}</div>
        <div>{t('document.template')}: {doc.template.name} <span class="error">SElektor hier!</span></div>
    </fieldset>
    <fieldset>
        <legend>{t('document.head')}</legend>
        {doc.head}
    </fieldset>
    <fieldset>
        <legend>{t('document.positions')}</legend>
        <span class="error">laden!</span>
    </fieldset>
    <fieldset>
        <legend>{t('document.footer')}</legend>
        {doc.footer}
    </fieldset>
    <fieldset>
        <legend>{t('document.actions')}</legend>
        <span class="error">laden!</span>
    </fieldset>
{/if}
