<script lang="ts">
  import { login } from "$lib/api/auth";
  import { goto } from "$app/navigation";
  import { auth } from "$lib/auth/store.svelte";
  import { onMount } from "svelte";
  import { today } from "$lib/utils/date";

  let username = $state("");
  let password = $state("");
  let error = $state("");
  let loading = $state(false);

  onMount(() => {
    if (auth.isAuthenticated) goto(`/diary/${today()}`);
  });

  async function handleSubmit(e: SubmitEvent) {
    e.preventDefault();
    error = "";
    loading = true;
    try {
      await login(username, password);
      goto(`/diary/${today()}`);
    } catch (err: unknown) {
      error = "Invalid username or password";
    } finally {
      loading = false;
    }
  }
</script>

<div class="min-h-screen flex items-center justify-center px-4">
  <div class="w-full max-w-sm">
    <h1 class="text-3xl font-bold text-center mb-8 text-green-500">Fooder</h1>

    <form onsubmit={handleSubmit} class="space-y-4">
      <div>
        <label
          for="username"
          class="block text-sm font-medium text-zinc-400 mb-1">Username</label
        >
        <input
          id="username"
          type="text"
          bind:value={username}
          autocomplete="username"
          required
          class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
        />
      </div>

      <div>
        <label
          for="password"
          class="block text-sm font-medium text-zinc-400 mb-1">Password</label
        >
        <input
          id="password"
          type="password"
          bind:value={password}
          autocomplete="current-password"
          required
          class="w-full bg-zinc-900 border border-zinc-700 rounded-xl px-4 py-3 text-zinc-100 focus:outline-none focus:border-green-500 transition-colors"
        />
      </div>

      {#if error}
        <p class="text-red-400 text-sm">{error}</p>
      {/if}

      <button
        type="submit"
        disabled={loading}
        class="w-full bg-green-600 hover:bg-green-500 disabled:opacity-50 rounded-xl py-3 font-semibold transition-colors"
      >
        {loading ? "Signing in…" : "Sign in"}
      </button>
    </form>

    <p class="text-center mt-6 text-zinc-500 text-sm">
      No account?
      <a href="/register" class="text-green-500 hover:text-green-400"
        >Register</a
      >
    </p>
  </div>
</div>
