<script lang="ts">
	import { persisted } from '$lib/helpers/localStore';
	import { fade } from 'svelte/transition';
	import TextSplit from './TextSplit.svelte';

	let tempName = '';

	let data = persisted('data', {
		name: '',
		adelsTitel: ''
	});

	let loadingAdelsTitel = false;
	async function fetchAdelsTitel() {
		if (loadingAdelsTitel) return;
		loadingAdelsTitel = true;

		const res = await fetch('https://adels-generator.herokuapp.com/');
		const data = await res.json();
		$data.adelsTitel = data.adelsTitel;
		loadingAdelsTitel = false;
	}
</script>

<section in:fade={{ delay: 2000 }}>
	{#if $data.name}
		<h3>Name: {$data.name}</h3>
		<button
			on:click={() => {
				$data.name = '';
			}}>name ändern</button
		>
	{:else}
		<TextSplit content="Fantastisch, wie lautet euer Name?" />
		<input type="text" bind:value={tempName} />
		{#if tempName}
			<button
				on:click={() => {
					$data.name = tempName;
					tempName = '';
					fetchAdelsTitel();
				}}>name speichern</button
			>
		{/if}
	{/if}
</section>

{#if $data.name}
	<section in:fade />
{/if}

<style>
	section {
		color: white;
		font-family: 'Parisienne', cursive;
		max-width: 500px;
		margin: 0 auto;
		font-size: 2em;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20px;
	}
</style>
