<script lang="ts">
	import { onMount } from 'svelte';
	import { page } from '$app/state';
	import { PUBLIC_KRATOS_URL } from '$env/static/public';
	import FlowForm from '$lib/components/FlowForm.svelte';
	import type { LoginFlow } from '@ory/client';
	import { kratosClient } from '$lib/kratos';

	let flow = $state<LoginFlow | null>(null);
	let loading = $state(true);
	let error = $state<string | null>(null);

	onMount(async () => {
		const flowId = page.url.searchParams.get('flow');

		if (flowId) {
			try {
				// Use SDK method to fetch flow - handles credentials automatically
				const { data } = await kratosClient.getLoginFlow({ id: flowId });
				flow = data;
			} catch (err) {
				console.error('Login flow error:', err);
				error = 'Flow expired or invalid. Please try again.';
			} finally {
				loading = false;
			}
		} else {
			window.location.href = `${PUBLIC_KRATOS_URL}/self-service/login/browser`;
		}
	});
</script>

<svelte:head>
	<title>Login - Example App</title>
</svelte:head>

<div class="flex min-h-full flex-col justify-center px-4 py-12 sm:px-6 lg:px-8">
	<div class="mx-auto w-full max-w-sm sm:max-w-md">
		<h2 class="text-center text-2xl font-bold leading-9 tracking-tight text-theme sm:text-3xl">
			Sign in to your account
		</h2>
	</div>

	<div class="mx-auto mt-8 w-full max-w-sm sm:max-w-md">
		<div class="card-padded shadow-theme">
			{#if loading}
				<p class="text-center text-theme-muted">Loading...</p>
			{:else if error}
				<div class="alert-error mb-4">
					<p>{error}</p>
				</div>
				<p class="text-center">
					<a href="/login" class="text-primary-500 hover:text-primary-600">Try again</a>
				</p>
			{:else if flow}
				<FlowForm {flow} groups={['default', 'password']} />
			{:else}
				<div class="alert-error">
					<p>Failed to load login form</p>
				</div>
			{/if}
		</div>

		<p class="mt-6 text-center text-sm text-theme-secondary">
			Don't have an account?
			<a href="/registration" class="font-semibold leading-6 text-primary-500 hover:text-primary-600">
				Register here
			</a>
		</p>

		<p class="mt-2 text-center text-sm text-theme-secondary">
			<a href="/recovery" class="font-semibold leading-6 text-primary-500 hover:text-primary-600">
				Forgot your password?
			</a>
		</p>
	</div>
</div>
