<script>
    import {PUBLIC_API_URL} from "$env/static/public";
    import {goto} from "$app/navigation";
    import {toast} from "$lib/toast.svelte.js";
    import favicon from "$lib/assets/favicon.png";

    let name = $state("");
    let email = $state("");
    let password = $state("");
    let confirmPassword = $state("");
    let url = $state("");

    const submit = async ()=>{
        const body = {
            name: name,
            email: email,
            password: password,
            confirm_password: confirmPassword,
            url: url
        };

        const response = await fetch(`${PUBLIC_API_URL}/user`, {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify(body)
        });

        const responseBody = await response.json();
        if(!response.ok){
            toast(responseBody.error.message, "error")
        }else{
            goto("/login");
        }
    }
</script>

<main>
    <a href="/" class="logo">
        <span class="logo-icon">
            <img src={favicon} alt="ChatRPG logo" width="35" height="35" />
        </span>
        <span class="logo-text">ChatRPG</span>
    </a>

    <div class="form-glow">
        <form class="standardForm" onsubmit={submit}>
            <h2>Join The Adventure</h2>

            <label>Name
                <!-- svelte-ignore a11y_autofocus -->
                <input bind:value={name} type="text" required autofocus>
            </label>

            <label>Email
                <input bind:value={email} type="email" required>
            </label>

            <label>Password
                <input bind:value={password} type="password" required>
            </label>

            <label>Confirm Password
                <input bind:value={confirmPassword} type="password" required>
            </label>

            <input bind:value={url} type="hidden" required>

            <button type="submit">Register</button>

            <p>Already have an account? <a href="/login">Log in</a></p>
        </form>
    </div>
</main>

<style>
    main {
        min-height: 100vh;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 1.75rem;
        padding: 2rem 1rem;
    }

    a.logo {
        display: flex;
        align-items: center;
        gap: 14px;
        text-decoration: none;
        color: #e5e5ea;
        font-weight: 700;
        font-size: 32px;
        letter-spacing: -0.5px;
    }

    a.logo img {
        width: 48px;
        height: 48px;
    }

    a.logo .logo-icon {
        color: #c084fc;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    h2{
        text-align: center;
    }

</style>
