<script lang="ts">
    import { onMount } from "svelte";
    import { goto } from "$app/navigation";

    onMount(async () => {
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get("code");
        if (!code) {
            goto("/");
            return;
        }
        try {
            const res = await fetch(`/api/exchange-code?code=${code}`);
            if (!res.ok) {
                console.error("Failed to exchange code for token");
                goto("/");
                return;
            }
            const data = await res.json();
            const token = data.access_token;
            if (token) {
                localStorage.setItem("access_token", token);
                goto("/");
            } else {
                console.error("No access token in response");
                goto("/");
            }
        } catch (error) {
            console.error("Error during token exchange", error);
            goto("/");
        }
    });
</script>

<p>Authenticating… please wait.</p>
