<script lang="ts">
    import {push} from 'svelte-spa-router'
    import {apiSignup} from '../lib/api/index'
    import {auth} from '../lib/stores/auth.svelte'

    let name = $state('')
  let email = $state('')
  let password = $state('')
  let loading = $state(false)
  let error = $state('')
  let success = $state(false)

  $effect(() => {
    if (auth.isLoggedIn) push('/')
  })

  async function handleSignup() {
    if (!name || !email || !password) return
    loading = true
    error = ''
    try {
      await apiSignup(name, email, password)
      success = true
      setTimeout(() => push('/login'), 1500)
    } catch (e: unknown) {
      error = e instanceof Error ? e.message : 'Signup failed'
    } finally {
      loading = false
    }
  }
</script>

<div class="min-h-screen bg-base-200 flex items-center justify-center p-4">
  <div class="card bg-base-100 shadow-xl w-full max-w-sm">
    <div class="card-body gap-4">
      <div class="text-center mb-2">
        <h1 class="text-3xl font-extrabold text-primary">Join the Hunt</h1>
        <p class="text-base-content/60 mt-1">Create your account</p>
      </div>

      {#if success}
        <div class="alert alert-success text-sm">Account created! Redirecting to login…</div>
      {/if}

      {#if error}
        <div class="alert alert-error text-sm">{error}</div>
      {/if}

      <form onsubmit={(e) => { e.preventDefault(); handleSignup() }} class="flex flex-col gap-3">
        <label class="floating-label">
          <input
            type="text"
            placeholder="Name"
            class="input input-bordered w-full"
            bind:value={name}
            required
          />
          <span>Name</span>
        </label>

        <label class="floating-label">
          <input
            type="email"
            placeholder="Email"
            class="input input-bordered w-full"
            bind:value={email}
            required
          />
          <span>Email</span>
        </label>

        <label class="floating-label">
          <input
            type="password"
            placeholder="Password"
            class="input input-bordered w-full"
            bind:value={password}
            required
          />
          <span>Password</span>
        </label>

        <button type="submit" class="btn btn-primary w-full mt-2" disabled={loading || success}>
          {#if loading}<span class="loading loading-spinner loading-sm"></span>{/if}
          Create Account
        </button>
      </form>

      <p class="text-center text-sm text-base-content/60">
        Already have an account?
        <a href="#/login" class="link link-primary font-medium">Sign in</a>
      </p>
    </div>
  </div>
</div>
