<script lang="ts">
	import { goto } from "$app/navigation";
	import { resolve } from "$app/paths";
	import X from "$icon/x";
	import Button from "$lib/components/ui/Button.svelte";
	import Logo from "$lib/components/ui/Logo.svelte";
	import FinishStep from "$lib/components/welcome/FinishStep.svelte";
	import KeysStep from "$lib/components/welcome/KeysStep.svelte";
	import ProfileStep from "$lib/components/welcome/ProfileStep.svelte";
	import SocialStep from "$lib/components/welcome/SocialStep.svelte";
	import WelcomeCard from "$lib/components/welcome/WelcomeCard.svelte";
	import { profileFilled } from "$lib/components/welcome/draft.svelte";
	import { LAST_STEP, WELCOME_TOTAL } from "$lib/components/welcome/steps";

	// the appview keeps the index in the onboarding table and gives each step its
	// own GET route; with nothing wired up yet this is local state, so wiring it
	// later means splitting this into /welcome/[step] and reading the record.
	let step = $state(0);
	let direction = $state(1);

	const go = (to: number) => {
		if (to < 0 || to >= WELCOME_TOTAL) return;
		direction = to > step ? 1 : -1;
		step = to;
	};

	// the appview greens Next on every step past the profile, where it is earned
	const nextReady = $derived(step === 0 ? profileFilled() : true);

	const leave = () => goto(resolve("/"));
</script>

<svelte:head>
	<title>Welcome &middot; Tangled</title>
</svelte:head>

<div class="flex min-h-screen w-full items-start justify-center px-4 pt-16 pb-8">
	<main class="w-full max-w-3xl">
		<h1 class="mb-4 flex place-content-center">
			<Logo wordmark class="h-10" />
		</h1>

		<WelcomeCard
			{step}
			{direction}
			{nextReady}
			onBack={() => go(step - 1)}
			onNext={() => (step === LAST_STEP ? leave() : go(step + 1))}
		>
			{#snippet children(current)}
				{#if current === 0}
					<ProfileStep />
				{:else if current === 1}
					<SocialStep />
				{:else if current === 2}
					<KeysStep />
				{:else}
					<FinishStep />
				{/if}
			{/snippet}
		</WelcomeCard>

		{#if step < LAST_STEP}
			<div class="mt-4 flex justify-center">
				<Button variant="ghost" icon={X} onclick={leave}>Skip onboarding</Button>
			</div>
		{/if}
	</main>
</div>
