<script lang="ts">
	import { login } from "../components/stores";
	import { getProfiles, getUsername } from "../lib/api";

	let profilesPromise: ReturnType<typeof getProfiles> = new Promise(() => {});
	$: if ($login !== undefined) {
		profilesPromise = getProfiles($login?.token);
	}
</script>

<svelte:head>
	<title>Skyblock Data Tracker</title>
</svelte:head>

<div id="list">
	{#await profilesPromise}
		<div class="item">
			<h2>Fetching profiles...</h2>
		</div>
	{:then profiles}
		{#each profiles as profile}
			<button type="button" class="item">
				{#each profile.data.members as member, idx}
					{#await getUsername(member)}
						<a href="/profile/{profile.profile}/member/{member}"
							>...</a
						>
					{:then username}
						<a href="/profile/{profile.profile}/member/{member}">
							{username}
							{#if idx === 0 && profile.data.name}
								@ {profile.data.name}
							{/if}
						</a>
					{:catch error}
						<p style="color: red">{error.message}</p>
					{/await}
				{/each}
			</button>
		{/each}
		<!-- svelte-ignore a11y-missing-content -->
		<a class="item add" href="/profile/new" />
	{:catch error}
		<div class="item">
			<h2 style="color: red">{error.message}</h2>
		</div>
	{/await}
</div>

<style lang="scss">
	@use "../styles/GridList";
	.item {
		font-size: 1.17em;

		a {
			display: block;
			margin: 1em 0;
			color: hsl(30, 20%, 90%);
			text-decoration: none;
			font-family: "Minecraft";
			&:hover {
				text-decoration: underline;
			}
		}
		a:nth-child(1) {
			color: hsl(60, 100%, 50%);
			font-size: 2em;
		}
	}
</style>
