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

	let flow = $state<SettingsFlow | null>(null);
	let isLoading = $state(true);
	const isUpdated = $derived(page.url.searchParams.has('updated'));

	onMount(async () => {
		const url = new URL(window.location.href);
		const flowId = url.searchParams.get('flow');

		if (!flowId) {
			// Redirect to create flow
			window.location.href = `${PUBLIC_KRATOS_URL}/self-service/settings/browser`;
			return;
		}

		try {
			// Use SDK method to fetch flow - handles credentials automatically
			const { data } = await kratosClient.getSettingsFlow({ id: flowId });
			flow = data;
			isLoading = false;
		} catch (error) {
			console.error('Failed to fetch settings flow:', error);
			// Restart flow on error
			window.location.href = `${PUBLIC_KRATOS_URL}/self-service/settings/browser`;
		}
	});
</script>

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

<div class="mx-auto max-w-2xl">
	<h1 class="mb-8 text-2xl font-bold text-theme sm:text-3xl">Account Settings</h1>

	{#if isUpdated}
		<div class="alert-success mb-6">
			<p>Your settings have been updated successfully!</p>
		</div>
	{/if}

	{#if isLoading}
		<div class="card-padded shadow-theme">
			<p class="text-center text-theme-muted">Loading settings…</p>
		</div>
	{:else if flow}
		<div class="card-padded shadow-theme">
			<h2 class="mb-4 text-xl font-semibold text-theme">Profile Settings</h2>
			<p class="mb-4 text-sm text-theme-secondary">Update your personal information</p>
			<SettingsProfileForm {flow} />
		</div>

		<div class="card-padded mt-6 shadow-theme">
			<h2 class="mb-4 text-xl font-semibold text-theme">Password</h2>
			<FlowForm {flow} groups={['password']} />
		</div>

		<div class="card-padded mt-6 shadow-theme">
			<h2 class="mb-4 text-xl font-semibold text-theme">Authenticator App (TOTP)</h2>
			<p class="mb-4 text-sm text-theme-secondary">
				Use an authenticator app like Google Authenticator, Authy, or 1Password to generate verification codes.
			</p>
			<FlowForm {flow} groups={['totp']} />
		</div>

		<div class="card-padded mt-6 shadow-theme">
			<h2 class="mb-4 text-xl font-semibold text-theme">Security Keys & Biometrics (WebAuthn)</h2>
			<p class="mb-4 text-sm text-theme-secondary">
				Use hardware security keys (like YubiKey) or biometric authentication (like Face ID or Touch ID) for enhanced security.
			</p>
			<FlowForm {flow} groups={['webauthn']} />
		</div>
	{/if}
</div>
