<script lang="ts">
    import { onMount } from 'svelte';
    import { goto } from '$app/navigation';
    import { register } from '$lib/api/auth';
    import { authConfig } from '$lib/auth-config.svelte';
    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);

    // Direct navigation to /register bypasses the root layout's
    // onMount — re-trigger the config load here so the disabled state
    // renders correctly even when this is the first page hit.
    onMount(() => {
        if (!authConfig.loaded) authConfig.load();
    });

    async function submit(e: SubmitEvent) {
        e.preventDefault();
        error = null;
        submitting = true;
        try {
            const user = await register({ username, password });
            session.setUser(user);
            // Honour ?next= the same way login does (registration logs the
            // user in), guarded against open redirects.
            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>Register</h1>
{#if authConfig.loaded && !authConfig.self_register_enabled}
    <p class="notice" role="status" data-testid="register-disabled">
        Self-registration is disabled on this server. Ask an administrator to
        create an account for you.
    </p>
{:else}
<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>
{/if}
<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);
    }

    .notice {
        padding: var(--space-3);
        border: 1px solid var(--border);
        border-radius: var(--radius-md);
        background: var(--surface-elevated);
        color: var(--text);
        max-width: 32rem;
        margin: 0;
    }
</style>
