<script lang="ts">
    import Button from "$lib/ui/button.svelte";
    import { clear_auth_session, get_transactions, init_auth_session } from "./sb1.remote";
    import type { PageProps } from "./$types";

    let navigating = $state(false);
    let { data }: PageProps = $props();

    async function authorize() {
        navigating = true;
        const url = await init_auth_session();
        location.href = url;
        navigating = false;
    }

    async function logout() {
        await clear_auth_session();
    }
</script>

<main>
    {#if data.sb1.accounts?.length}
        <ul>
            {#each data.sb1.accounts as account}
                <li>{account.name}</li>
                {#if (await get_transactions(account.key))?.length}
                    <ul>
                        {#each await get_transactions(account.key) as transaction}
                            <li>{JSON.stringify(transaction)}</li>
                        {/each}
                    </ul>
                {:else}
                    <small>Ingen transaksjoner</small>
                {/if}
            {/each}
        </ul>
        <Button onclick={logout}>Logg ut</Button>
    {:else}
        <Button onclick={authorize} loading={navigating}>Autentisér hos Sparebanken 1</Button>
    {/if}

    {#if data.actual.meta}
        <pre>{JSON.stringify(data.actual.meta, null, 2)}</pre>
    {/if}
</main>

<style>
    main {
        display: flex;
        justify-content: center;
        width: 100%;
        height: 90vh;
    }
</style>
