<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { getErrorMessage } from '$lib/shared/errors';
import { enhance } from '$app/forms';
import AuthHeader from '../AuthHeader.svelte';

let {
	data,
	form
}: {
	data: {
		code: string | null;
		prefill: { firstName?: string; lastName?: string; email?: string } | null;
		codeError: string | null;
	};
	form?: { error?: string };
} = $props();

let showPassword = $state(false);
let showPasswordConfirm = $state(false);
let password = $state('');
let passwordConfirm = $state('');
let notifyOnMention = $state(true);
let submitAttempted = $state(false);
let submitting = $state(false);

const pwValid = $derived(password.length >= 8);
const pwMatch = $derived(passwordConfirm.length > 0 && password === passwordConfirm);
const pwMismatch = $derived(passwordConfirm.length > 0 && password !== passwordConfirm);
const showPwHint = $derived(submitAttempted || password.length > 0);
const showMatchHint = $derived(submitAttempted || passwordConfirm.length > 0);

$effect(() => {
	if (form?.error) submitting = false;
});
</script>

<svelte:head>
	<title>{m.register_heading()} – Familienarchiv</title>
</svelte:head>

<div class="flex min-h-screen flex-col bg-canvas">
	<AuthHeader />

	<main class="flex flex-1 items-center justify-center px-4 py-12">
		<div class="w-full max-w-2xl">
			{#if data.codeError}
				<div class="rounded-sm border border-line bg-surface p-8 text-center shadow-sm">
					<svg
						class="mx-auto mb-4 h-10 w-10 text-red-400"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="1.5"
							d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
						/>
					</svg>
					<h1 class="mb-2 font-sans text-sm font-bold tracking-widest text-ink uppercase">
						{data.codeError === 'NO_INVITE_CODE' ? m.register_invite_only() : m.register_invalid_code()}
					</h1>
					<p class="mb-6 font-serif text-sm text-ink-2">
						{data.codeError === 'NO_INVITE_CODE'
							? m.register_invite_only_desc()
							: m.register_invalid_code_desc()}
					</p>
					<a
						href="/login"
						class="font-sans text-xs font-bold tracking-widest text-brand-navy/60 uppercase transition-colors hover:text-brand-navy"
					>
						{m.forgot_password_back_to_login()}
					</a>
				</div>
			{:else}
				<!-- Hero -->
				<div class="mb-8 text-center">
					<p
						class="mb-3 inline-block font-sans text-xs font-bold tracking-widest text-ink-3 uppercase"
					>
						{m.register_eyebrow()}
					</p>
					<h1 class="mb-3 font-serif text-4xl font-normal text-ink sm:text-[46px] sm:leading-tight">
						{m.register_hero_headline()}
					</h1>
					<p class="mx-auto max-w-lg font-serif text-lg text-ink-2">
						{m.register_hero_subtext()}
					</p>
				</div>

				<!-- Form card -->
				<div class="rounded-sm border border-line bg-surface p-8 shadow-sm sm:p-10">
					<form
						method="POST"
						class="space-y-8"
						use:enhance={() => {
							if (!pwValid || pwMismatch) {
								submitAttempted = true;
								return async () => {};
							}
							submitAttempted = true;
							submitting = true;
							return async ({ update }) => {
								await update();
							};
						}}
					>
						<input type="hidden" name="code" value={data.code ?? ''} />

						<!-- Section: Über dich -->
						<section class="space-y-5">
							<p class="font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
								{m.register_section_about()}
							</p>
							<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
								<div>
									<label
										for="firstName"
										class="mb-1.5 block font-sans text-xs font-bold tracking-widest text-ink-2 uppercase"
										>{m.register_label_first_name()}</label
									>
									<input
										type="text"
										name="firstName"
										id="firstName"
										autocomplete="given-name"
										value={data.prefill?.firstName ?? ''}
										class="block w-full border border-line px-3 py-3 font-serif text-[17px] text-ink placeholder-ink-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
									/>
								</div>
								<div>
									<label
										for="lastName"
										class="mb-1.5 block font-sans text-xs font-bold tracking-widest text-ink-2 uppercase"
										>{m.register_label_last_name()}</label
									>
									<input
										type="text"
										name="lastName"
										id="lastName"
										autocomplete="family-name"
										value={data.prefill?.lastName ?? ''}
										class="block w-full border border-line px-3 py-3 font-serif text-[17px] text-ink placeholder-ink-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
									/>
								</div>
							</div>
						</section>

						<!-- Section: Konto -->
						<section class="space-y-5">
							<p class="font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
								{m.register_section_account()}
							</p>

							<div>
								<label
									for="email"
									class="mb-1.5 block font-sans text-xs font-bold tracking-widest text-ink-2 uppercase"
									>{m.register_label_email()}</label
								>
								<input
									type="email"
									name="email"
									id="email"
									required
									autocomplete="email"
									value={data.prefill?.email ?? ''}
									class="block w-full border border-line px-3 py-3 font-serif text-[17px] text-ink placeholder-ink-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
								/>
								{#if data.prefill?.email}
									<p class="mt-1.5 font-sans text-xs text-ink-3">{m.register_prefill_hint()}</p>
								{/if}
							</div>

							<div>
								<label
									for="password"
									class="mb-1.5 block font-sans text-xs font-bold tracking-widest text-ink-2 uppercase"
									>{m.register_label_password()}</label
								>
								<div class="relative">
									<input
										type={showPassword ? 'text' : 'password'}
										name="password"
										id="password"
										required
										autocomplete="new-password"
										bind:value={password}
										class="block w-full border border-line px-3 py-3 pr-20 font-serif text-[17px] text-ink placeholder-ink-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
									/>
									<button
										type="button"
										onclick={() => (showPassword = !showPassword)}
										class="absolute inset-y-0 right-0 flex items-center px-3 font-sans text-xs font-bold text-ink-3 hover:text-ink"
										aria-label={showPassword ? m.register_password_hide() : m.register_password_show()}
									>
										{showPassword ? m.register_password_hide() : m.register_password_show()}
									</button>
								</div>
								{#if showPwHint}
									<p class="mt-1.5 font-sans text-xs {pwValid ? 'text-green-700' : 'text-ink-3'}">
										{pwValid ? m.register_pw_ok() : m.register_pw_hint()}
									</p>
								{/if}
							</div>

							<div>
								<label
									for="passwordConfirm"
									class="mb-1.5 block font-sans text-xs font-bold tracking-widest text-ink-2 uppercase"
									>{m.register_label_password_confirm()}</label
								>
								<div class="relative">
									<input
										type={showPasswordConfirm ? 'text' : 'password'}
										id="passwordConfirm"
										autocomplete="new-password"
										bind:value={passwordConfirm}
										aria-invalid={submitAttempted && pwMismatch}
										class="block w-full border px-3 py-3 pr-20 font-serif text-[17px] text-ink placeholder-ink-3 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring
											{submitAttempted && pwMismatch ? 'border-red-400' : 'border-line'}"
									/>
									<button
										type="button"
										onclick={() => (showPasswordConfirm = !showPasswordConfirm)}
										class="absolute inset-y-0 right-0 flex items-center px-3 font-sans text-xs font-bold text-ink-3 hover:text-ink"
										aria-label={showPasswordConfirm ? m.register_password_hide() : m.register_password_show()}
									>
										{showPasswordConfirm ? m.register_password_hide() : m.register_password_show()}
									</button>
								</div>
								{#if showMatchHint}
									{#if pwMatch}
										<p class="mt-1.5 font-sans text-xs text-green-700">
											{m.register_pw_match_ok()}
										</p>
									{:else if pwMismatch}
										<p class="mt-1.5 font-sans text-xs text-red-600">{m.register_pw_match_no()}</p>
									{/if}
								{/if}
							</div>
						</section>

						<!-- Section: Benachrichtigungen -->
						<section>
							<p class="mb-4 font-sans text-xs font-bold tracking-widest text-ink-3 uppercase">
								{m.register_section_notifications()}
							</p>
							<label
								class="flex cursor-pointer items-start gap-3 rounded-sm border p-4 transition-colors
									{notifyOnMention ? 'border-brand-navy bg-brand-mint/10' : 'border-line bg-white'}"
							>
								<input
									type="checkbox"
									name="notifyOnMention"
									bind:checked={notifyOnMention}
									class="sr-only"
								/>
								<!-- Visual checkbox -->
								<span
									class="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-sm border transition-colors
										{notifyOnMention ? 'border-brand-navy bg-brand-navy' : 'border-line bg-white'}"
									aria-hidden="true"
								>
									{#if notifyOnMention}
										<svg class="h-3 w-3 text-white" viewBox="0 0 12 12" fill="none">
											<path
												d="M2 6l3 3 5-5"
												stroke="currentColor"
												stroke-width="1.8"
												stroke-linecap="round"
												stroke-linejoin="round"
											/>
										</svg>
									{/if}
								</span>
								<span>
									<span class="block font-sans text-sm font-bold text-ink"
										>{m.register_notify_title()}</span
									>
									<span class="mt-0.5 block font-serif text-sm text-ink-2"
										>{m.register_notify_desc()}</span
									>
								</span>
							</label>
						</section>

						{#if form?.error}
							<div class="font-sans text-xs font-medium text-red-600">
								{getErrorMessage(form.error)}
							</div>
						{/if}

						<div class="space-y-4">
							<button
								type="submit"
								disabled={submitting}
								class="flex w-full items-center justify-center gap-2 bg-primary py-3 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-colors hover:bg-primary/90 disabled:cursor-wait disabled:opacity-70"
							>
								{#if submitting}
									<svg class="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
										<circle
											class="opacity-25"
											cx="12"
											cy="12"
											r="10"
											stroke="currentColor"
											stroke-width="4"
										/>
										<path
											class="opacity-75"
											fill="currentColor"
											d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
										/>
									</svg>
									{m.register_btn_loading()}
								{:else}
									{m.register_btn_submit()}
									<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M17 8l4 4m0 0l-4 4m4-4H3"
										/>
									</svg>
								{/if}
							</button>

							<p class="text-center font-sans text-xs text-ink-3">
								{m.register_already_have_account()}
								<a
									href="/login"
									class="font-bold tracking-widest text-brand-navy uppercase transition-colors hover:text-brand-navy/70"
									>{m.register_sign_in()}</a
								>
							</p>
						</div>
					</form>
				</div>
			{/if}
		</div>
	</main>

	<div class="py-4 text-center">
		<p class="font-sans text-xs tracking-widest text-ink-3 uppercase">Familienarchiv</p>
	</div>
</div>
