<script lang="ts">
import Spacer from "$lib/Layout/Spacer.svelte";
import { dumpUser } from "$lib/Data/AniList/user";
import RateLimited from "$lib/Error/RateLimited.svelte";
import { parseJsonStringOrDefault } from "$lib/Effect/json";
import Skeleton from "$lib/Loading/Skeleton.svelte";
import InputTemplate from "./InputTemplate.svelte";
import LZString from "lz-string";

let submission = "";

// Credit: @hoh
const decodeJSON = (about: string): unknown | null => {
	const match = (about || "").match(/^\[\]\(json([A-Za-z0-9+/=]+)\)/);

	if (match) {
		const directDecoded = parseJsonStringOrDefault<unknown | null>(
			atob(match[1]),
			null,
		);

		if (directDecoded !== null) return directDecoded;

		const decompressed = LZString.decompressFromBase64(match[1]);

		if (!decompressed) return null;

		return parseJsonStringOrDefault<unknown | null>(decompressed, null);
	}

	return null;
};
</script>

<InputTemplate field="Username" bind:submission event="Dump User" submitText="Dump">
  {#await dumpUser(submission)}
    <Skeleton card={false} count={1} height="500px" />
  {:then dump}
    {@const decoded = decodeJSON(dump.about)}

    <pre>{JSON.stringify(dump, null, 2)}</pre>

    {#if decoded && (dump.about || '').includes('[](json')}
      <Spacer />

      <pre>{JSON.stringify(decoded, null, 2).replaceAll(/\\n/g, '\n')}</pre>
    {/if}
  {:catch}
    <RateLimited type="User" list={false} />
  {/await}
</InputTemplate>

<style>
  pre {
    margin: 0;
  }
</style>
