<template>
  <div class="min-h-screen flex flex-col items-center justify-center bg-base-200 p-4">
    <div class="card w-full max-w-sm bg-base-100 shadow-xl">
      <div class="card-body">
        <h1 class="card-title justify-center">First-time setup</h1>
        <p class="text-sm text-base-content/80">
          This is the first run. Create the administrator account using the bootstrap password
          from the server configuration (e.g. <code class="text-xs">HNHMAP_BOOTSTRAP_PASSWORD</code>).
        </p>
        <form @submit.prevent="submit" class="flex flex-col gap-4">
          <PasswordInput
            v-model="pass"
            label="Bootstrap password"
            required
            autocomplete="current-password"
          />
          <p v-if="error" class="text-error text-sm">{{ error }}</p>
          <button type="submit" class="btn btn-primary" :disabled="loading">
            <span v-if="loading" class="loading loading-spinner loading-sm" />
            <span v-else>Create and log in</span>
          </button>
        </form>
      </div>
    </div>
    <NuxtLink to="/" class="link link-hover underline underline-offset-2 mt-4 text-primary">Map</NuxtLink>
  </div>
</template>

<script setup lang="ts">
// No auth required; auth.global skips this path

const pass = ref('')
const error = ref('')
const loading = ref(false)
const router = useRouter()
const api = useMapApi()

onMounted(async () => {
  try {
    const { setupRequired: required } = await api.setupRequired()
    if (!required) await navigateTo('/login')
  } catch {
    // If API fails, stay on page
  }
})

async function submit() {
  error.value = ''
  loading.value = true
  try {
    await api.login('admin', pass.value)
    await router.push('/profile')
  } catch (e: unknown) {
    error.value = (e as Error)?.message === 'Unauthorized'
      ? 'Invalid bootstrap password.'
      : (e as Error)?.message || 'Setup failed'
  } finally {
    loading.value = false
  }
}
</script>
