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

  let username = $state('');
  let password = $state('');
  let confirmPassword = $state('');
  let inviteToken = $state('');
  let displayName = $state('');
  let submitting = $state(false);
  let error = $state<string | null>(null);

  function errorMessageFor(code: string): string {
    switch (code) {
      case 'username_invalid':
        return 'Username must be 3–32 characters: letters, numbers, underscores, hyphens.';
      case 'password_too_short':
        return 'Password must be at least 8 characters.';
      case 'invite_required':
        return 'This server requires an invite token to register. Ask an admin for one.';
      case 'invite_invalid':
        return 'That invite token is invalid, expired, or already used.';
      case 'username_taken':
        return 'That username is already taken.';
      default:
        return 'Registration failed. Please try again.';
    }
  }

  async function handleSubmit(e: SubmitEvent) {
    e.preventDefault();
    if (submitting) return;
    error = null;
    if (password !== confirmPassword) {
      error = 'Passwords do not match.';
      return;
    }
    submitting = true;
    try {
      await register({
        username,
        password,
        inviteToken: inviteToken || undefined,
        displayName: displayName || undefined,
      });
      await goto('/', { replaceState: true });
    } catch (err: unknown) {
      error = errorMessageFor(errCode(err));
    } finally {
      submitting = false;
    }
  }
</script>

<svelte:head><title>{pageTitle('Register')}</title></svelte:head>

<main class="flex min-h-screen items-center justify-center bg-background text-text-primary">
  <div class="w-full max-w-sm rounded-lg border border-border bg-surface p-6 shadow">
    <h1 class="mb-6 text-center text-2xl font-semibold">Create account</h1>
    <form class="space-y-4" onsubmit={handleSubmit}>
      <label class="block">
        <span class="mb-1 block text-sm text-text-secondary">Username</span>
        <input
          type="text"
          autocomplete="username"
          required
          minlength="3"
          maxlength="32"
          class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          bind:value={username}
        />
      </label>
      <label class="block">
        <span class="mb-1 block text-sm text-text-secondary">
          Display name <span class="text-text-secondary opacity-60">(optional)</span>
        </span>
        <input
          type="text"
          autocomplete="name"
          maxlength="64"
          class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          bind:value={displayName}
        />
      </label>
      <label class="block">
        <span class="mb-1 block text-sm text-text-secondary">Password</span>
        <input
          type="password"
          autocomplete="new-password"
          required
          minlength="8"
          class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          bind:value={password}
        />
      </label>
      <label class="block">
        <span class="mb-1 block text-sm text-text-secondary">Confirm password</span>
        <input
          type="password"
          autocomplete="new-password"
          required
          minlength="8"
          class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          bind:value={confirmPassword}
        />
      </label>
      <label class="block">
        <span class="mb-1 block text-sm text-text-secondary">
          Invite token <span class="text-text-secondary opacity-60">(if required by your server)</span>
        </span>
        <input
          type="text"
          autocomplete="off"
          class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          bind:value={inviteToken}
        />
      </label>

      <button
        type="submit"
        class="w-full rounded bg-accent px-3 py-2 font-medium text-background disabled:opacity-60"
        aria-busy={submitting ? 'true' : undefined}
        disabled={submitting}
      >
        {submitting ? 'Creating account…' : 'Create account'}
      </button>

      {#if error}
        <p role="alert" class="text-sm text-danger">{error}</p>
      {/if}
    </form>

    <p class="mt-4 text-center text-sm text-text-secondary">
      Already have an account?
      <a href="/login" class="text-accent hover:underline">Sign in</a>
    </p>
  </div>
</main>
