<script lang="ts">
	import { api } from '$lib/api';

	let email = $state('');
	let isLoading = $state(false);
	let message = $state('');
	let error = $state('');

	async function handleSubmit(e: Event) {
		e.preventDefault();
		isLoading = true;
		message = '';
		error = '';

		try {
			const res = await api.post<{ message: string }>('/auth/forgot-password', { email });
			if (res.data) {
				message = res.data.message;
				email = ''; // Clear email field on success
			} else {
				error = res.error || 'Ein Fehler ist aufgetreten.';
			}
		} catch (err: any) {
			error = err.message || 'Ein Fehler ist aufgetreten.';
		} finally {
			isLoading = false;
		}
	}
</script>

<div class="container">
	<div class="card forgot-card">
		<h1>Passwort vergessen</h1>
		<p class="subtitle">Gib deine E-Mail-Adresse ein, um dein Passwort zurückzusetzen.</p>

		{#if message}
			<div class="alert alert-success">
				<div class="alert-content">
					{message}
				</div>
				<button onclick={() => message = ''} class="btn-ghost" style="padding: 0; min-height: auto; width: auto;">×</button>
			</div>
		{/if}

		{#if error}
			<div class="alert alert-error">
				<div class="alert-content">
					{error}
				</div>
				<button onclick={() => error = ''} class="btn-ghost" style="padding: 0; min-height: auto; width: auto;">×</button>
			</div>
		{/if}

		<form onsubmit={handleSubmit}>
			<div class="form-group">
				<label for="email" class="form-label">E-Mail-Adresse</label>
				<input
					type="email"
					id="email"
					class="form-input"
					bind:value={email}
					placeholder="Deine E-Mail-Adresse"
					disabled={isLoading}
					required
				/>
			</div>

			<button type="submit" class="btn btn-primary btn-block" disabled={isLoading}>
				{isLoading ? 'Senden...' : 'Passwort zurücksetzen'}
			</button>
		</form>

		<p class="back-to-login text-center text-sm mt-md">
			<a href="/login">Zurück zum Login</a>
		</p>
	</div>
</div>

<style>
	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		background: var(--neutral-50);
		padding: var(--space-md);
	}

	.forgot-card {
		width: 100%;
		max-width: 400px;
	}

	h1 {
		margin: 0 0 var(--space-xs);
		font-family: var(--font-heading);
		font-size: var(--text-2xl);
		text-align: center;
	}

	.subtitle {
		color: var(--neutral-500);
		text-align: center;
		margin: 0 0 var(--space-xl);
	}
</style>
