<script lang="ts">
  import { goto } from '$app/navigation';
  import { page } from '$app/state';
  import { api, ApiError } from '$lib/api';

  const token = $derived(page.url.searchParams.get('token') ?? '');

  let password = $state('');
  let error = $state('');
  let busy = $state(false);
  let done = $state(false);

  async function submit(e: SubmitEvent) {
    e.preventDefault();
    error = '';
    busy = true;
    try {
      await api.post('/auth/reset-password', { token, new_password: password });
      done = true;
      setTimeout(() => goto('/login'), 1500);
    } catch (err) {
      error = err instanceof ApiError ? err.message : 'something broke';
    } finally {
      busy = false;
    }
  }
</script>

<svelte:head><title>new password · consume·rs</title></svelte:head>

<div class="mx-auto max-w-md">
  <div class="panel panel-acid p-8">
    <p class="label">set new password</p>
    <h1 class="mb-6 font-display text-3xl font-bold">FORGE A NEW KEY</h1>

    {#if !token}
      <p class="border-2 border-rose bg-rose/10 px-3 py-3 text-sm text-rose">
        no reset token in this link. request a fresh one.
      </p>
      <p class="mt-5 text-center text-sm text-mute"><a href="/forgot">request reset</a></p>
    {:else if done}
      <p class="border-2 border-mint bg-mint/10 px-3 py-3 text-sm text-mint">
        password changed. redirecting to login…
      </p>
    {:else}
      <form class="space-y-4" onsubmit={submit}>
        <div>
          <label class="label" for="pw">new password <span class="text-mute">(min 10)</span></label>
          <input id="pw" class="field mt-1" type="password" bind:value={password} required minlength="10" autocomplete="new-password" />
        </div>
        {#if error}
          <p class="border-2 border-rose bg-rose/10 px-3 py-2 text-sm text-rose">{error}</p>
        {/if}
        <button class="btn btn-acid w-full" disabled={busy}>{busy ? 'cutting…' : 'set password'}</button>
      </form>
    {/if}
  </div>
</div>
