<script lang="ts">
    import Header from "$lib/navigation/header.svelte";
    import Nav from "$lib/navigation/nav.svelte";
    import { getApiUrl } from "$lib/scripts/upstream";
    import { uuid } from "$lib/stores/uuid";

    const title = "Submit Registration";
    let state = false;
    let status: string;
    let inputString: string;

    async function handleSubmit() {
        console.log(`Code: ${inputString}`);
        const res = await submit(inputString);
        console.log(`Registration Status: ${res}`);
        if (res == 201) {
            status = "okay";
        } else if (res == 401) {
            status = "fail";
        } else {
            console.error("Unable to register: ", status);
        }
        state = true;
    }

    async function submit(id: string): Promise<number> {
        const url = `${getApiUrl()}/api/v2/user/register`;
        const request = {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                uuid: id,
            }),
        };
        const res = await fetch(url, request);
        const body = await res.json();
        if (body.api_key) {
            uuid.set(body.api_key);
            return 201;
        } else {
            return res.status;
        }
    }
</script>

<svelte:head>
    <meta name="robots" content="noindex">
</svelte:head>

<Header {title} />

{#if state}
    {#if status == "okay"}
        <p class="title-ish">You are now registered</p>
        <p>Your secret key will be stored in your browser.</p>
        <p>If you change browsers, change device or clear your browsing data, you may have to register again.</p>
    {:else if status == "fail"}
        <p class="title-ish">Your code was not accepted</p>
        <p>The code expires after 1 hour, you can check the code and enter it again or request a <a href="/more/reg">new code</a>.</p>
    {/if}
{:else}
    <p class="title-ish">Enter your registration code below</p>
    <form on:submit={handleSubmit} id="codeInputForm">
            <input class="code-in" bind:value={inputString} id={'input'} maxlength="6" autocomplete="off">
        <br />
        <button type="submit">Submit</button>
    </form>
{/if}

<Nav />

<style>
    .title-ish {
        font-size: 20px;
    }
    .code-in {
        margin: 3px;
        margin-bottom: 20px;
        width: calc(29px * 6);
        height: 39px;
        font-size: 30px;
        text-align: center;
        text-transform: uppercase;
        border-radius: 10px;
        border: none;
    }
    button {
        border: none;
        background-color: var(--island-bg-color);
        color: var(--main-text-color);
        width: 35%;
        min-width: 95px;
        max-width: 231px;
        height: 30px;
        border-radius: 50px;
        font-size: 18px;
    }
    p {
        margin-left: 40px;
        margin-right: 40px;
    }
</style>
