<script lang="ts">
import localforage from "localforage";
import { onMount } from "svelte";
import { browser } from "$app/environment";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
import { env } from "$env/dynamic/public";
import type { UserIdentity } from "$lib/Data/AniList/identity";
import HeadTitle from "$lib/Home/HeadTitle.svelte";
import root from "$lib/Utility/root";

onMount(async () => {
	if (browser) {
		const identity = await localforage.getItem<UserIdentity>("identity");
		const user = identity?.name;

		if (user) {
			if (browser && $page.url.searchParams.get("badges") !== null) {
				goto(root(`/user/${user}/badges`));
			} else {
				goto(root(`/user/${user}`));
			}
		} else {
			goto(
				`https://anilist.co/api/v2/oauth/authorize?client_id=${env.PUBLIC_ANILIST_CLIENT_ID}&redirect_uri=${env.PUBLIC_ANILIST_REDIRECT_URI}&response_type=code`,
			);
		}
	}
});
</script>

<HeadTitle routeKey="profile" path="/user" />
