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

    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 register({ username, password });
            session.setUser(user);
            await goto('/');
        } catch (e) {
            error = (e as Error).message;
        } finally {
            submitting = false;
        }
    }
</script>

<h1>Register</h1>
<form onsubmit={submit} action="javascript:void(0)" data-testid="register-form">
    <label class="form-field">
        <span>Username</span>
        <input
            type="text"
            bind:value={username}
            autocomplete="username"
            minlength="3"
            maxlength="32"
            required
            data-testid="register-username"
        />
    </label>
    <label class="form-field">
        <span>Password</span>
        <input
            type="password"
            bind:value={password}
            autocomplete="new-password"
            minlength="8"
            required
            data-testid="register-password"
        />
    </label>
    <button class="primary" type="submit" disabled={submitting} data-testid="register-submit">
        {submitting ? 'Registering…' : 'Register'}
    </button>
    {#if error}
        <p class="form-error" role="alert" data-testid="register-error">{error}</p>
    {/if}
</form>
<p class="hint">
    Already have an account? <a href="/login">Log in</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>
