<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuth } from '@/composables/useAuth'

const route = useRoute()
const router = useRouter()
const { login, isAuthenticated } = useAuth()

const identifier = ref('demo@strapi-demo.local')
const password = ref('Demo1234!')
const error = ref<string | null>(null)
const loading = ref(false)

onMounted(() => {
  if (isAuthenticated.value) {
    router.replace((route.query.redirect as string) || '/members')
  }
})

async function onSubmit() {
  error.value = null
  loading.value = true
  try {
    await login(identifier.value, password.value)
    const redirect = (route.query.redirect as string) || '/members'
    await router.push(redirect)
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Login failed.'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <main class="page narrow">
    <h1>Log in</h1>
    <p class="lead">
      Demo account (created by Strapi bootstrap):
      <code>demo@strapi-demo.local</code> / <code>Demo1234!</code>
    </p>

    <form class="login-form" @submit.prevent="onSubmit">
      <label>
        Email or username
        <input v-model="identifier" type="text" autocomplete="username" required />
      </label>
      <label>
        Password
        <input v-model="password" type="password" autocomplete="current-password" required />
      </label>
      <p v-if="error" class="error">{{ error }}</p>
      <button type="submit" class="btn btn-primary" :disabled="loading">
        {{ loading ? 'Signing in…' : 'Sign in' }}
      </button>
    </form>
  </main>
</template>

<style scoped>
.login-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 1.5rem;
}

label {
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
  font-weight: 500;
  font-size: 0.9rem;
}

input {
  padding: 0.65rem 0.75rem;
  border: 1px solid var(--border);
  border-radius: 8px;
  font: inherit;
  background: var(--surface);
  color: var(--text);
}

code {
  font-size: 0.85em;
  background: var(--surface-elevated);
  padding: 0.1em 0.35em;
  border-radius: 4px;
}
</style>
