<script>
  import { api } from '../api.js'
  import { saveSession } from '../db.js'

  let { onlogin } = $props()

  let username = $state('')
  let password = $state('')
  let error = $state('')
  let loading = $state(false)

  async function submit(e) {
    e.preventDefault()
    error = ''
    loading = true
    try {
      const { token, user } = await api.login(username, password)
      await saveSession(token, user)
      onlogin({ token, user })
    } catch (err) {
      error = err.message || 'Login failed'
    } finally {
      loading = false
    }
  }
</script>

<div class="login-wrap">
  <div class="login-box">
    <h1 class="login-title">Turnpike</h1>
    <p class="login-sub">Event management</p>
    {#if error}
      <div class="alert alert-error">{error}</div>
    {/if}
    <form onsubmit={submit}>
      <div class="form-group">
        <label for="username">Username</label>
        <input id="username" bind:value={username} autocomplete="username" required />
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <input id="password" type="password" bind:value={password} autocomplete="current-password" required />
      </div>
      <button type="submit" class="btn btn-primary" style="width:100%" disabled={loading}>
        {loading ? 'Signing in…' : 'Sign in'}
      </button>
    </form>
  </div>
</div>
