<script lang="ts">
    import {t} from "$lib/i18n";
    import {API_ROOT} from "$lib/config";
    import {onMount} from "svelte";
    import {setCookie} from "$lib/cookie";

    let isLoading = true;
    let hasError = false;
    let error = "";

    onMount(() => {
        // content loaded - start checking the api
        const urlParams = new URLSearchParams(window.location.search);
        if (!urlParams.has("email")) {
            error = t('magiclink.missing_email');
            hasError = true;
            isLoading = false;
            return;
        } else if (!urlParams.has("token")) {
            error = t('magiclink.missing_token');
            hasError = true;
            isLoading = false;
            return;
        }

        let token = urlParams.get("token");

        let xhr = new XMLHttpRequest();
        xhr.timeout = 10000;
        xhr.open('POST', `${API_ROOT}/v1/auth/verify-magic-link`);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(JSON.stringify({
            magicLinkToken: token
        }));

        xhr.ontimeout = () => {
            hasError = true;
            error = t('magiclink.apierror.timeout');
            isLoading = false;
        };

        xhr.onload = () => {
            if (xhr.status != 200) {
                // error
                hasError = true;
                const rawerror = JSON.parse(xhr.responseText).errors[0].message;

                error = t(`magiclink.apierror.${rawerror}`);

                isLoading = false;
            } else {
                let resp = JSON.parse(xhr.responseText);

                if (resp.data === undefined || resp.data.sessionToken === undefined) {
                    error = t("magiclink.apierror.badresponse");
                    hasError = true;
                    isLoading = false;
                    return;
                }

                let sess = resp.data.sessionToken;
                // Set a really, really long expiry date. We will remove it when the server starts giving us unauthorized errors, but we don't know ahead of time what the server's expiration time is.
                setCookie("sessionToken", sess, (86400 * 365));

                isLoading = false;
                hasError = false;

                // redirect them to the homepage
                window.location.href = "/admin"
            }
        };

        xhr.onerror = () => {
            hasError = true;
            error = t('magiclink.apierror.xhrerror');
            isLoading = false;
        };
    });
</script>

<div class="flex in-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="w-full max-w-md">
        {#if isLoading}
            <div>
                <h1 class="font-semibold text-2xl">{t('magiclink.loadtitle')}</h1>
                <h2 class="text-sm">{t('magiclink.loadsubtitle')}</h2>
            </div>
        {:else}
            {#if hasError}
                <h1 class="font-semibold text-2xl">{t('magiclink.failed')}</h1>
                <h2 class="text-sm">{error}</h2>
                <a class="text-xs font-bold text-purple-400 dark:text-purple-600" href="/auth/login">{t('magiclink.tryAgain')}</a>
            {:else}
                <h1 class="font-semibold text-2xl">{t('magiclink.finished')}</h1>
                <h2 class="text-sm">{t('magiclink.redirecting')}</h2>
            {/if}
        {/if}
    </div>
</div>