<script lang="ts">
  let identifier = $state('');
  let error = $state('');
  let success = $state(false);
  let loading = $state(false);

  async function handleSubmit(e: Event) {
    e.preventDefault();
    error = '';
    loading = true;

    try {
      const res = await fetch('/api/auth/forgot', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ identifier }),
      });

      const data = await res.json();

      if (!res.ok) {
        error = data.error || 'Request failed';
        return;
      }

      success = true;
    } catch (err) {
      error = 'Connection error';
    } finally {
      loading = false;
    }
  }
</script>

<div class="min-h-screen flex items-center justify-center bg-base-200" data-theme="light">
  <div class="card bg-base-100 shadow-xl w-full max-w-md">
    <div class="card-body">
      <h1 class="text-2xl font-bold text-center mb-4">Reset Password</h1>
      
      {#if error}
        <div class="alert alert-error mb-4">
          <span>{error}</span>
        </div>
      {/if}

      {#if success}
        <div class="alert alert-success mb-4">
          <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span>If an account exists with that email or username, a password reset link has been sent.</span>
        </div>
        <div class="text-center mt-4">
          <a href="/auth/login" class="btn btn-primary">Back to Login</a>
        </div>
      {:else}
        <p class="text-base-content/60 text-center mb-6">Enter your email address or username and we'll send you a link to reset your password.</p>

        <form onsubmit={handleSubmit} class="space-y-4">
          <fieldset class="fieldset">
            <legend class="fieldset-legend">Email or Username</legend>
            <input
              type="text"
              class="input input-bordered w-full"
              bind:value={identifier}
              placeholder="user@example.org or username"
              required
              disabled={loading}
            />
          </fieldset>

          <button type="submit" class="btn btn-primary w-full" disabled={loading}>
            {#if loading}
              <span class="loading loading-spinner loading-sm"></span>
              Sending...
            {:else}
              Send Reset Link
            {/if}
          </button>
        </form>

        <div class="text-center mt-4">
          <a href="/auth/login" class="link link-primary">Back to Login</a>
        </div>
      {/if}
    </div>
  </div>
</div>
