<script lang="ts">
  import { login, isAuthenticated } from '$lib/api';
  import { goto } from '$app/navigation';
  import { browser } from '$app/environment';
  import { toast } from 'svelte-sonner';

  let username = '';
  let password = '';
  let loading = false;

  if (browser && isAuthenticated()) {
    goto('/');
  }

  async function handleLogin(e: Event) {
    e.preventDefault();
    if (!username || !password) {
      toast.error('Заполните имя и пароль');
      return;
    }
    loading = true;
    try {
      await login(username, password);
      toast.success('Вход выполнен');
      goto('/');
    } catch (err: any) {
      toast.error(err.message || 'Ошибка входа');
    } finally {
      loading = false;
    }
  }
</script>

<div class="min-h-screen flex items-center justify-center bg-secondary">
  <div class="w-full max-w-sm p-8 bg-card rounded-lg border shadow-sm">
    <div class="text-center mb-6">
      <span class="text-4xl">📞</span>
      <h1 class="text-xl font-bold mt-2">pulse-lets-go</h1>
      <p class="text-sm text-muted-foreground">Telephone Balancer</p>
    </div>

    <form on:submit={handleLogin} class="space-y-4">
      <div>
        <label for="username" class="block text-sm font-medium mb-1">Имя пользователя</label>
        <input
          id="username"
          type="text"
          bind:value={username}
          class="w-full px-3 py-2 border rounded-md text-sm bg-background focus:outline-none focus:ring-2 focus:ring-ring"
          placeholder="admin"
          required
        />
      </div>

      <div>
        <label for="password" class="block text-sm font-medium mb-1">Пароль</label>
        <input
          id="password"
          type="password"
          bind:value={password}
          class="w-full px-3 py-2 border rounded-md text-sm bg-background focus:outline-none focus:ring-2 focus:ring-ring"
          placeholder="••••••"
          required
        />
      </div>

      <button
        type="submit"
        disabled={loading}
        class="w-full py-2 px-4 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50"
      >
        {loading ? 'Вход...' : 'Войти'}
      </button>
    </form>

    <p class="mt-4 text-xs text-muted-foreground text-center">
      По умолчанию: admin / admin
    </p>
  </div>
</div>
