<script lang="ts">
  import { pageTitle } from '$lib/branding';
  import { forgotPassword } from '$lib/auth/store.svelte';

  let email = $state('');
  let submitted = $state(false);
  let submitting = $state(false);

  async function onSubmit(e: SubmitEvent) {
    e.preventDefault();
    submitting = true;
    try {
      await forgotPassword(email);
    } catch {
      // Swallow — the page always shows the same success message
      // regardless of outcome, to mirror the server's no-enumeration
      // posture. A failed call must not surface as an unhandled
      // rejection in the browser console.
    } finally {
      submitted = true;
      submitting = false;
    }
  }
</script>

<svelte:head><title>{pageTitle('Forgot password')}</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">Forgot password</h1>

    {#if !submitted}
      <p class="mb-4 text-sm text-text-secondary">
        Enter your email. If an account uses it, you'll receive a reset link shortly.
      </p>
      <form class="space-y-4" onsubmit={onSubmit}>
        <label class="block">
          <span class="mb-1 block text-sm text-text-secondary">Email</span>
          <input
            id="email"
            type="email"
            required
            autocomplete="email"
            bind:value={email}
            class="w-full rounded border border-border bg-background px-3 py-2 outline-none focus:border-accent"
          />
        </label>
        <button
          type="submit"
          disabled={submitting}
          aria-busy={submitting ? 'true' : undefined}
          class="w-full rounded bg-accent px-3 py-2 font-medium text-background disabled:opacity-60"
        >
          {submitting ? 'Sending…' : 'Send reset link'}
        </button>
      </form>
    {:else}
      <p class="text-sm text-text-primary">
        If your email is on file, you'll receive a reset link shortly.
        Check your inbox (and spam folder).
      </p>
    {/if}

    <p class="mt-4 text-center text-sm text-text-secondary">
      Remembered? <a href="/login" class="text-accent hover:underline">Log in</a>
    </p>
  </div>
</main>
