<script lang="ts">
	import { onMount } from 'svelte';
	import { currentStep, selectedCard } from '$lib/stores';
	import { cardTypes } from '$lib/cards';
	import type { Card } from '$lib/cards/types';
	import Navigator from './subcomponents/Navigator.svelte';

	let selected: Card | null = $state(null);

	onMount(() => {
		const savedCardName = localStorage.getItem('selectedCardName');
		if (savedCardName) {
			const foundCard = cardTypes.find((c) => c.name === savedCardName);
			if (foundCard) {
				selected = foundCard;
				selectedCard.set(foundCard);
			}
		}
	});

	function selectCard(card: Card) {
		selected = card;
		selectedCard.set(card);
		localStorage.setItem('selectedCardName', card.name);
	}

	function onNext() {
		if (selected) {
			currentStep.set($currentStep + 1);
		}
	}

	function onBack() {
		currentStep.set($currentStep - 1);
	}
</script>

<div class="p-6">
	<div class="max-w-5xl mx-auto">
		<div class="mb-6">
			<h2 class="text-xl font-semibold text-gray-900 mb-2">Select Card Type</h2>
			<p class="text-sm text-gray-700 mb-4">
				Choose the type of card you want to generate. This will determine the layout and dimensions of the final PDFs.
			</p>
		</div>

		<!-- Card Type Selector -->
		<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mb-8">
			{#each cardTypes as card (card.name)}
				<button
					class="relative rounded-lg border-2 p-2 transition-all duration-200"
					class:border-blue-600={selected?.name === card.name}
					class:border-gray-200={selected?.name !== card.name}
					class:shadow-lg={selected?.name === card.name}
					onclick={() => selectCard(card)}
				>
					<img src={card.image} alt={card.name} class="w-full h-auto rounded-md mb-2" />
					<p class="text-sm font-medium text-center text-gray-800">{card.name}</p>
					{#if selected?.name === card.name}
						<div
							class="absolute top-2 right-2 bg-blue-600 text-white rounded-full w-6 h-6 flex items-center justify-center"
						>
							<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M5 13l4 4L19 7"
								></path>
							</svg>
						</div>
					{/if}
				</button>
			{/each}
		</div>

		<Navigator onForward={onNext} onBack={onBack} nextDisabled={!selected} />
	</div>
</div>
