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

  let { onlogin, error: initialError = '' } = $props()

  let email = $state('')
  let password = $state('')
  let error = $state(initialError)
  let loading = $state(false)
  let ssoEnabled = $state(false)
  let ssoLoading = $state(false)

  onMount(async () => {
    try {
      const res = await api.sso.enabled()
      ssoEnabled = res.enabled
    } catch {}
  })

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

  async function startSSO() {
    error = ''
    ssoLoading = true
    try {
      const { redirect_url } = await api.sso.init()
      window.location.href = redirect_url
    } catch (err) {
      error = err.message || 'SSO failed'
      ssoLoading = 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="email">Email</label>
        <input id="email" type="email" bind:value={email} autocomplete="email" 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>
    {#if ssoEnabled}
      <div class="sso-divider"><span>or</span></div>
      <button class="btn btn-ghost" style="width:100%" onclick={startSSO} disabled={ssoLoading}>
        {ssoLoading ? 'Redirecting…' : 'Log in with Discourse'}
      </button>
    {/if}
  </div>
</div>

<style>
  .sso-divider {
    display: flex;
    align-items: center;
    margin: 1rem 0;
    gap: 0.75rem;
    color: var(--c-muted);
    font-size: 0.8rem;
  }
  .sso-divider::before,
  .sso-divider::after {
    content: '';
    flex: 1;
    border-top: 1px solid var(--c-border);
  }
</style>
