<script lang="ts">
    import { goto } from "$app/navigation";
    import { env } from "$env/dynamic/public";
    import UserState, { type UserObj } from "$lib/User.svelte";
    import axios from "axios";

    let username = $state("");
    let password = $state("");
    let error = $state("");

    async function login() {
        axios
            .post(
                `${env.PUBLIC_JEOPARDY_SERVER_PROTOCOL}://${env.PUBLIC_JEOPARDY_SERVER}/auth/login`,
                {
                    username: username,
                    password: password
                },
                { withCredentials: true }
            )
            .then((response) => {
                if (response.status === 200) {
                    UserState.user = response.data as UserObj;
                    console.log(UserState.id, UserState.username, UserState.role);
                    goto("/");
                }
            })
            .catch((e) => {
                error = "Login fehlgeschlagen";
            });
    }
</script>

<div class="flex h-full w-full items-center justify-center">
    <div class="borders flex-col items-center justify-center">
        <div>
            <label for="username" class="ms-4">Name</label>
            <input
                type="text"
                name="username"
                id="username"
                class="borders ms-4 me-4 mt-2 mb-4"
                bind:value={username}
            />
            <label for="password" class="ms-4">Passwort</label>
            <input
                type="password"
                name="password"
                id="password"
                class="borders ms-4 me-4 mt-2 mb-4"
                bind:value={password}
            />
        </div>
        <button type="button" class="btn mb-2 w-fit ps-4 pe-4" onclick={login}>Login</button>
        {#if error.length > 0}
            <div class="text-red-700">{error}</div>
        {/if}
    </div>
</div>

<style>
    .borders {
        border: 1px solid black;
        border-radius: 5px;
        display: flex;
        font-size: larger;
        padding: 2px;
    }
</style>
