<script lang="ts">
    import { goto } from '$app/navigation';
    import { login } from '$lib/api/auth';
    import { session } from '$lib/session.svelte';
    import { safeNext } from '$lib/safeNext';

    let username = $state('');
    let password = $state('');
    let error: string | null = $state(null);
    let submitting = $state(false);

    async function submit(e: SubmitEvent) {
        e.preventDefault();
        error = null;
        submitting = true;
        try {
            const user = await login({ username, password });
            session.setUser(user);
            // Return the user to the page they were bounced from (?next=),
            // guarded against open redirects; default to the site root.
            const next = new URLSearchParams(window.location.search).get('next');
            await goto(safeNext(next));
        } catch (e) {
            error = (e as Error).message;
        } finally {
            submitting = false;
        }
    }
</script>

<h1>Log in</h1>
<form onsubmit={submit} action="javascript:void(0)" data-testid="login-form">
    <label class="form-field">
        <span>Username</span>
        <input
            type="text"
            bind:value={username}
            autocomplete="username"
            required
            data-testid="login-username"
        />
    </label>
    <label class="form-field">
        <span>Password</span>
        <input
            type="password"
            bind:value={password}
            autocomplete="current-password"
            required
            data-testid="login-password"
        />
    </label>
    <button class="primary" type="submit" disabled={submitting} data-testid="login-submit">
        {submitting ? 'Logging in…' : 'Log in'}
    </button>
    {#if error}
        <p class="form-error" role="alert" data-testid="login-error">{error}</p>
    {/if}
</form>
<p class="hint">
    No account? <a href="/register">Register</a>.
</p>

<style>
    form {
        display: flex;
        flex-direction: column;
        gap: var(--space-3);
        max-width: 24rem;
    }

    .primary {
        background: var(--primary);
        color: var(--primary-contrast);
        border-color: var(--primary);
        margin-top: var(--space-1);
    }

    .primary:hover:not(:disabled) {
        background: var(--primary-hover);
        border-color: var(--primary-hover);
    }

    .form-error {
        color: var(--danger);
        font-size: var(--font-sm);
    }

    .hint {
        margin-top: var(--space-3);
        color: var(--text-muted);
        font-size: var(--font-sm);
    }
</style>
