<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 inputs: { id: string; value: string }[] = [
        { id: "1", value: "" },
        { id: "2", value: "" },
        { id: "3", value: "" },
        { id: "4", value: "" },
        { id: "5", value: "" },
        { id: "6", value: "" }
    ];

    function handleInput(index: number, event: KeyboardEvent): void {
        if (event.key === "Backspace" && index > 0 && inputs[index].value === "") {
            const prevInput = document.getElementById(`input-${index}`);
            if (prevInput) {
                prevInput.focus();
            }
        } else if (inputs[index].value.length === 1) {
            const nextInput = document.getElementById(`input-${index + 2}`);
            if (nextInput) {
                nextInput.focus();
            }
        }
    }

    async function handleSubmit() {
        let submitString: string = "";
        for (const input of inputs) {
            submitString += input.value.toUpperCase();
        }
        console.log(`Code: ${submitString}`);
        const res = await submit(submitString);
        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>

<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">
        {#each inputs as input, index}
            <input class="code-in" bind:value={input.value} id={`input-${input.id}`} maxlength="1" autocomplete="off" on:keydown={(event) => handleInput(index, event)} />
        {/each}
        <br />
        <button type="submit">Submit</button>
    </form>
{/if}

<Nav />

<style>
    .title-ish {
        font-size: 20px;
    }
    .code-in {
        margin: 3px;
        margin-bottom: 20px;
        width: 29px;
        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>
