<script lang="ts">
	import { goto } from '$app/navigation';
	import { onMount } from 'svelte';
	import { api } from '$lib/api';
	import { login } from '$lib/auth.svelte';
	import { t, getLocale, setLocale } from '$lib/i18n';
	import { initTheme, getTheme, setTheme, type Theme } from '$lib/theme.svelte';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import AuthLayout from '$lib/components/AuthLayout.svelte';

	const theme = getTheme();
	let username = $state('');
	let password = $state('');
	let error = $state('');
	let submitting = $state(false);
	let mounted = $state(false);

	let backendDown = $state(false);

	onMount(async () => {
		initTheme();
		mounted = true;
		// If the user is already signed in (valid access token in storage),
		// there is no reason to show them the login form. loadUser() runs in
		// the root layout; we just check the resolved state after a short tick.
		const { isAuthenticated } = await import('$lib/api');
		if (isAuthenticated()) {
			try {
				await api('/auth/me');
				goto('/');
				return;
			} catch {
				// Token was stale; fall through to the login form.
			}
		}
		try {
			const res = await api<{ needs_setup: boolean }>('/auth/needs-setup');
			if (res.needs_setup) goto('/setup');
		} catch {
			// The backend is unreachable — surface that distinctly so the user
			// doesn't blame the login form for a network/backend problem.
			backendDown = true;
		}
	});

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		error = '';
		submitting = true;
		try {
			await login(username, password);
			window.location.href = '/';
		} catch (err: any) {
			error = err.message || t('auth.loginFailed');
		}
		submitting = false;
	}
</script>

<AuthLayout visible={mounted}>
	<!-- Controls -->
	<div class="flex justify-end gap-1.5 mb-6">
		<button onclick={() => { setLocale(getLocale() === 'en' ? 'ru' : 'en'); }}
			class="auth-control-btn">
			{getLocale().toUpperCase()}
		</button>
		<button onclick={() => { const o: Theme[] = ['light','dark','system']; setTheme(o[(o.indexOf(theme.current)+1)%3]); }}
			class="auth-control-btn">
			<MdiIcon name={theme.resolved === 'dark' ? 'mdiWeatherNight' : 'mdiWeatherSunny'} size={13} />
		</button>
	</div>

	<!-- Logo / title -->
	<div class="text-center mb-8">
		<div class="auth-logo-icon">
			<MdiIcon name="mdiLan" 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.signInTitle')}</p>
	</div>

	{#if backendDown}
		<div class="auth-error animate-fade-slide-in">
			<MdiIcon name="mdiAlertCircle" size={16} />
			{t('auth.backendUnreachable')}
		</div>
	{:else 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" placeholder="admin" />
		</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>
		<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.signingIn') : t('auth.signIn')}
		</button>
	</form>
</AuthLayout>
