<script lang="ts">
    import ChatInput from "./ChatInput.svelte";
    import ChatMessage from "./ChatMessage.svelte";
    import Avatar from "./Avatar.svelte";
    import { onMount, afterUpdate } from "svelte";

    let messages: ({ type: string; text: string } | { text: { submit: string }; type: string })[] = [];
    let sessionToken = "";
    const backendUrl = import.meta.env.VITE_BACKEND_URL;
    let message = "";
    let element: HTMLDivElement;

    onMount(async () => {
        const response = await fetch(`${backendUrl}/api/session`);
        const data = await response.json();
        sessionToken = data.token;
    });

    // Either afterUpdate()
    afterUpdate(() => {
        element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
    });

    async function sendMessage(messageInput: CustomEvent<{submit:string}>): Promise<void> {

        messages = [...messages, { type: "user", text: messageInput.detail }];
        const response = await fetch(`${backendUrl}/api/chat`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                token: sessionToken,
                message: messageInput.detail
            }),
        });

        const data = await response.json();
        messages = [...messages, { type: "bot", text: data.reply }];
    }
</script>

<main>
    <div id="chat-container"  bind:this={element} >
        {#each messages as message}
            <div class="message-container">
            {#if message.type === "bot"}
                <Avatar />
            {/if}
            <ChatMessage type="{message.type}" text="{message.text}" />
                </div>

        {/each}

    </div>
    <footer id="footer">
        <ChatInput bind:message on:submit="{sendMessage}" />
    </footer>
</main>

