<script lang="ts">
    import { goto } from "$app/navigation";
    import {
        mapLinkErrorToSessionEndReason,
        resolveLinkFresh,
    } from "$lib/domains/link/client";
    import { prepareLinkSC } from "$lib/domains/link/link.remote";
    import { onMount } from "svelte";

    let state: "boot" | "validating" | "preparing" = "boot";
    let statusText = "Initializing session...";

    onMount(() => {
        const run = async () => {
            const token =
                new URLSearchParams(window.location.search)
                    .get("token")
                    ?.trim() || "";

            if (!token) {
                await goto("/unauthorized?reason=missing_token", {
                    replaceState: true,
                });
                return;
            }

            state = "validating";
            statusText = "Validating your access link...";

            const resolved = await resolveLinkFresh(token);
            if (resolved?.error || !resolved?.data) {
                const reason = mapLinkErrorToSessionEndReason(resolved?.error);
                await goto(
                    `/session-ended?reason=${encodeURIComponent(reason)}`,
                    {
                        replaceState: true,
                    },
                );
                return;
            }

            state = "preparing";
            statusText = "Preparing your app session...";

            const prepared = await prepareLinkSC({ token });
            if (prepared?.error || !prepared?.data) {
                const reason = mapLinkErrorToSessionEndReason(prepared?.error);
                await goto(
                    `/session-ended?reason=${encodeURIComponent(reason)}`,
                    {
                        replaceState: true,
                    },
                );
                return;
            }

            await goto(`/session?token=${encodeURIComponent(token)}`, {
                replaceState: true,
            });
        };

        void run();
    });
</script>

<main
    class="bg-background text-foreground flex min-h-screen items-center justify-center px-6"
>
    <section
        class="w-full max-w-sm rounded-xl border border-border bg-card p-6 text-center"
    >
        <h1 class="text-xl font-semibold">Starting your session</h1>
        <p class="mt-3 text-sm text-muted-foreground">{statusText}</p>
        <div class="mt-5 h-1.5 overflow-hidden rounded-full bg-muted">
            <div
                class="bg-primary h-full animate-pulse"
                style={`width: ${state === "boot" ? "35%" : state === "validating" ? "65%" : "88%"}`}
            ></div>
        </div>
    </section>
</main>
