<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import { page } from '$app/state';
  import { goto } from '$app/navigation';
  import { login } from '$lib/auth/store.svelte';
  import type { ApiError } from '$lib/api/client';

  let username = $state('');
  let password = $state('');
  let error = $state<string | null>(null);
  let pending = $state(false);

  function safeReturnTo(raw: string | null): string {
    if (!raw) return '/';
    // Starts with exactly one '/' (not '//', which is a protocol-relative URL)
    // AND is not the login page itself.
    if (!/^\/(?!\/)/.test(raw)) return '/';
    if (raw === '/login' || raw.startsWith('/login?') || raw.startsWith('/login/')) return '/';
    return raw;
  }

  async function handleSubmit(e: SubmitEvent) {
    e.preventDefault();
    if (pending) return;
    error = null;
    pending = true;
    try {
      await login(username, password);
      const dest = safeReturnTo(page.url.searchParams.get('returnTo'));
      goto(dest, { replaceState: true });
    } catch (err) {
      const apiErr = err as ApiError;
      if (apiErr?.status === 401 && apiErr?.code === 'invalid_credentials') {
        error = 'Invalid username or password.';
        password = '';
      } else {
        error = 'Sign-in unavailable. Try again in a moment.';
      }
    } finally {
      pending = false;
    }
  }
</script>

<svelte:head><title>{pageTitle('Sign in')}</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">Minstrel</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"
          class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          bind:value={username}
          required
        />
      </label>
      <label class="block">
        <span class="mb-1 block text-sm text-text-secondary">Password</span>
        <input
          type="password"
          autocomplete="current-password"
          class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          bind:value={password}
          required
        />
      </label>
      <button
        type="submit"
        class="w-full rounded bg-accent px-3 py-2 font-medium text-background disabled:opacity-60"
        aria-busy={pending ? 'true' : undefined}
        disabled={pending}
      >
        Sign in
      </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">
      <a href="/forgot-password" class="text-accent hover:underline">Forgot password?</a>
    </p>
    <p class="mt-2 text-center text-sm text-text-secondary">
      Don't have an account?
      <a href="/register" class="text-accent hover:underline">Register</a>
    </p>
  </div>
</main>
