<script setup lang="ts">
const auth = useAuth()
const route = useRoute()

const password = ref('')
const confirm = ref('')
const submitting = ref(false)
const done = ref(false)
const error = ref<string | null>(null)

const token = computed(() => String(route.params.token || ''))

async function submit() {
  error.value = null
  if (password.value !== confirm.value) {
    error.value = 'Passwords do not match.'
    return
  }
  submitting.value = true
  try {
    await auth.resetPassword(token.value, password.value)
    done.value = true
  } catch (e: any) {
    error.value = e?.data?.error || e?.message || 'Reset failed'
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="mx-auto max-w-md py-12">
    <h1 class="mb-6 text-2xl font-semibold">Choose a new password</h1>

    <div v-if="done" class="card text-sm">
      <p class="mb-2 font-medium text-brand-300">Password updated.</p>
      <p class="mb-4 text-zinc-400">All previous sessions have been signed out. Sign in to continue.</p>
      <NuxtLink to="/login" class="btn-primary w-full">Sign in</NuxtLink>
    </div>

    <form v-else class="card space-y-4" @submit.prevent="submit">
      <div>
        <label class="label">New password</label>
        <input
          v-model="password"
          type="password"
          class="input"
          autocomplete="new-password"
          minlength="8"
          maxlength="72"
          required
        />
        <p class="mt-1 text-xs text-zinc-500">At least 8 characters.</p>
      </div>
      <div>
        <label class="label">Confirm password</label>
        <input
          v-model="confirm"
          type="password"
          class="input"
          autocomplete="new-password"
          minlength="8"
          maxlength="72"
          required
        />
      </div>
      <button class="btn-primary w-full" :disabled="submitting || password.length < 8 || !confirm">
        {{ submitting ? 'Updating…' : 'Update password' }}
      </button>
      <p v-if="error" class="text-sm text-red-400">{{ error }}</p>
    </form>
  </section>
</template>
