<script lang="ts">
    import { api_host, authToken } from "$lib";
	import type { Appointment } from "$lib/dbdata";
	import { onMount } from "svelte";

    let appointmentData: Appointment[] = [];
    let ready: boolean = false;

    async function fetchAppointments() {
        try {
            const response = await fetch(`${api_host}/api/users/appointments`, {
                method: "GET",
                headers: {
                    "Authorization": "Bearer " + $authToken
                },
            });

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            const data: Appointment[] = await response.json();
            appointmentData = data;
        } catch (error) {
            console.log('Error during fetch:', error);
        }
    }


    onMount(async () => {
       await fetchAppointments();
       
       ready = true;
    });
</script>

<table class="border large-space large-text">
    <thead>
        <tr>
            <th class="min center-align">Veranstaltung</th>
            <th class="min center-align">Teilnehmerliste</th>
        </tr>
    </thead>
    <tbody>
        {#each appointmentData as data}
            <tr>
                <td>{data.title}</td>
                <td class="center-align">
                    <a href={`/user/participants?id=${data._id}`} class="button medium secondary">
                        <span>Teilnehmer</span>
                    </a>
                </td>
            </tr> 
        {/each}
    </tbody>
</table>
