<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import * as api from '../services/api'
import { setSession } from '../stores/session'
import { t } from '../i18n'

const router = useRouter()
const mode = ref<'login' | 'register'>('login')
const loading = ref(false)
const error = ref('')
const form = reactive({ email: '', password: '' })

async function submit() {
  loading.value = true
  error.value = ''
  try {
    if (mode.value === 'register') {
      await api.register(form)
    }
    const data = await api.login(form)
    setSession(data.access_token, form.email)
    router.push('/todos')
  } catch (e) {
    error.value = t('auth_failed')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <section class="page login-page">
    <header class="page-head">
      <div>
        <h2>{{ t('login_title') }}</h2>
        <p>{{ t('login_subtitle') }}</p>
      </div>
    </header>
    <div class="auth-card">
      <h1>{{ t('brand_name') }}</h1>
      <p>{{ t('login_hint') }}</p>
      <div class="segmented">
        <button class="btn" :class="{ primary: mode === 'login' }" @click="mode = 'login'">
          {{ t('login_tab') }}
        </button>
        <button class="btn" :class="{ primary: mode === 'register' }" @click="mode = 'register'">
          {{ t('register_tab') }}
        </button>
      </div>
      <label>
        {{ t('email') }}
        <input v-model="form.email" type="email" placeholder="you@company.com" />
      </label>
      <label>
        {{ t('password') }}
        <input v-model="form.password" type="password" placeholder="******" />
      </label>
      <button class="btn primary full" :disabled="loading" @click="submit">
        {{ loading ? t('loading_wait') : mode === 'login' ? t('login_tab') : t('register_and_login') }}
      </button>
      <p v-if="error" class="error">{{ error }}</p>
    </div>
  </section>
</template>
