<script lang="ts">
	import { enhance } from '$app/forms';
	import type { PageData, ActionData } from './$types';

	let { data, form }: { data: PageData; form: ActionData } = $props();

	const error = $derived(form?.error ?? data.error);
</script>

<div class="flex min-h-screen items-center justify-center bg-background px-4">
	<div class="w-full max-w-sm">

		<!-- Logo / marca -->
		<div class="mb-8 flex flex-col items-center gap-3 text-center">
			<div class="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground shadow-lg">
				<svg class="h-7 w-7" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
					<path stroke-linecap="round" stroke-linejoin="round" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
				</svg>
			</div>
			<div>
				<p class="text-xs font-semibold uppercase tracking-widest text-muted-foreground">Mi Aplicación</p>
				<h1 class="text-xl font-bold">Unirse a una empresa</h1>
				<p class="mt-1 text-sm text-muted-foreground">Ingresa el código que te compartió tu administrador.</p>
			</div>
		</div>

		<!-- PASO: INPUT DEL CÓDIGO -->
		{#if data.step === 'input'}
			<form method="POST" action="?/validate" use:enhance class="space-y-4">
				<div class="space-y-2">
					<input
						name="code"
						type="text"
						value={data.code}
						placeholder="Ej: HD96V79A"
						maxlength="16"
						autocomplete="off"
						spellcheck="false"
						class="w-full rounded-xl border bg-card px-4 py-3 text-center font-mono text-xl font-bold uppercase tracking-widest shadow-sm outline-none ring-primary transition focus:ring-2 {error ? 'border-destructive' : 'border-border'}"
					/>
					{#if error}
						<p class="text-center text-sm text-destructive">{error}</p>
					{/if}
				</div>
				<button
					type="submit"
					class="w-full rounded-xl bg-primary py-3 text-sm font-semibold text-primary-foreground shadow transition hover:bg-primary/90 active:scale-[0.98]"
				>
					Verificar código →
				</button>
			</form>

		<!-- PASO: PREVIEW — datos del código -->
		{:else if data.step === 'preview' && data.codeInfo}
			<div class="space-y-4">
				<!-- tarjeta con info del código -->
				<div class="rounded-xl border bg-card p-4 shadow-sm space-y-3">
					<div class="flex items-center justify-between">
						<span class="text-xs text-muted-foreground uppercase tracking-wide">Código</span>
						<code class="font-mono font-bold tracking-widest">{data.code}</code>
					</div>
					<div class="flex items-center justify-between">
						<span class="text-xs text-muted-foreground uppercase tracking-wide">Workspace</span>
						<span class="font-medium">{data.codeInfo.tenant_slug}</span>
					</div>
					<div class="flex items-center justify-between">
						<span class="text-xs text-muted-foreground uppercase tracking-wide">Rol asignado</span>
						<span class="inline-flex items-center rounded-full bg-primary/10 px-2.5 py-0.5 text-xs font-semibold text-primary">
							{data.codeInfo.role}
						</span>
					</div>
					{#if data.codeInfo.remaining_uses !== null}
						<div class="flex items-center justify-between">
							<span class="text-xs text-muted-foreground uppercase tracking-wide">Usos restantes</span>
							<span class="text-sm font-medium">{data.codeInfo.remaining_uses}</span>
						</div>
					{/if}
					{#if data.codeInfo.expires_at}
						<div class="flex items-center justify-between">
							<span class="text-xs text-muted-foreground uppercase tracking-wide">Vence</span>
							<span class="text-sm">
								{new Date(data.codeInfo.expires_at).toLocaleDateString('es-MX', { day: '2-digit', month: 'short', year: 'numeric' })}
							</span>
						</div>
					{/if}
				</div>

				{#if error}
					<p class="rounded-lg bg-destructive/10 px-4 py-2 text-center text-sm text-destructive border border-destructive/20">
						{error}
					</p>
				{/if}

				<form method="POST" action="?/join" use:enhance class="space-y-2">
					<input type="hidden" name="code" value={data.code} />
					<button
						type="submit"
						class="w-full rounded-xl bg-primary py-3 text-sm font-semibold text-primary-foreground shadow transition hover:bg-primary/90 active:scale-[0.98]"
					>
						Unirse a la empresa →
					</button>
				</form>
				<a
					href="/join"
					class="block text-center text-sm text-muted-foreground hover:underline"
				>
					Usar otro código
				</a>
			</div>

		<!-- PASO: PREVIEW sin codeInfo — error de validación -->
		{:else if data.step === 'preview'}
			<div class="space-y-4 text-center">
				<p class="rounded-lg bg-destructive/10 px-4 py-3 text-sm text-destructive border border-destructive/20">
					{error ?? 'Código inválido, expirado o agotado. Verifica con tu administrador.'}
				</p>
				<a href="/join" class="block text-sm text-primary hover:underline">← Intentar con otro código</a>
			</div>

		<!-- PASO: ÉXITO -->
		{:else if data.step === 'success'}
			<div class="space-y-5 text-center">
				<div class="flex justify-center">
					<div class="flex h-16 w-16 items-center justify-center rounded-full bg-green-100 text-green-600">
						<svg class="h-8 w-8" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
							<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
						</svg>
					</div>
				</div>
				<div>
					<h2 class="text-lg font-bold">¡Bienvenido!</h2>
					<p class="mt-1 text-sm text-muted-foreground">
						Te uniste al workspace <strong>{data.result?.tenant_slug}</strong>
						{#if data.result?.company_id}
							como <strong>{data.result?.role}</strong>.
						{/if}
					</p>
				</div>
				<a
					href="/dashboard"
					class="block w-full rounded-xl bg-primary py-3 text-sm font-semibold text-primary-foreground shadow transition hover:bg-primary/90"
				>
					Ir al dashboard →
				</a>
			</div>
		{/if}

	</div>
</div>
