<script lang="ts">
	import { goto } from '$app/navigation';
	import { onMount } from 'svelte';
	import { setup } from '$lib/auth.svelte';
	import { errMsg } from '$lib/api';
	import { t } from '$lib/i18n';
	import { initTheme } from '$lib/theme.svelte';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import AuthLayout from '$lib/components/AuthLayout.svelte';

	let username = $state('admin');
	let password = $state('');
	let confirmPassword = $state('');
	let error = $state('');
	let submitting = $state(false);
	let mounted = $state(false);

	onMount(() => { initTheme(); mounted = true; });

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		error = '';
		if (password !== confirmPassword) { error = t('auth.passwordMismatch'); return; }
		if (password.length < 8) { error = t('auth.passwordTooShort'); return; }
		submitting = true;
		try {
			await setup(username, password);
			window.location.href = '/';
		} catch (err: unknown) { error = errMsg(err, t('auth.setupFailed')); }
		submitting = false;
	}
</script>

<AuthLayout visible={mounted}>
	<div class="text-center mb-8">
		<div class="auth-logo-icon">
			<MdiIcon name="mdiShieldAccount" size={28} />
		</div>
		<h1 class="text-xl font-semibold mt-4 tracking-tight">
			<span style="color: var(--color-primary);">Notify</span> Bridge
		</h1>
		<p class="text-sm mt-1" style="color: var(--color-muted-foreground);">{t('auth.setupDescription')}</p>
	</div>

	{#if error}
		<div class="auth-error animate-fade-slide-in">
			<MdiIcon name="mdiAlertCircle" size={16} />
			{error}
		</div>
	{/if}

	<form onsubmit={handleSubmit} class="space-y-4">
		<div>
			<label for="username" class="auth-label">{t('auth.username')}</label>
			<input id="username" type="text" bind:value={username} required class="auth-input" />
		</div>
		<div>
			<label for="password" class="auth-label">{t('auth.password')}</label>
			<input id="password" type="password" bind:value={password} required class="auth-input" />
		</div>
		<div>
			<label for="confirm" class="auth-label">{t('auth.confirmPassword')}</label>
			<input id="confirm" type="password" bind:value={confirmPassword} required class="auth-input" />
		</div>
		<button type="submit" disabled={submitting} class="auth-submit">
			{#if submitting}
				<div class="w-4 h-4 rounded-full border-2 border-current border-t-transparent animate-spin"></div>
			{/if}
			{submitting ? t('auth.creatingAccount') : t('auth.createAccount')}
		</button>
	</form>
</AuthLayout>
