<template>
  <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-8 w-full">
    <h2 class="text-2xl font-semibold text-gray-900 mb-1">Set a new password</h2>
    <p class="text-sm text-gray-500 mb-6">Choose a strong password for your account.</p>

    <template v-if="!done">
      <form @submit.prevent="submit" class="space-y-4">
        <div>
          <label class="block text-sm font-semibold text-gray-700 mb-1">New password</label>
          <input
            v-model="newPassword"
            type="password"
            required
            autocomplete="new-password"
            class="block w-full rounded-lg px-3 py-3 text-sm border border-gray-300 bg-white text-gray-900 transition-colors focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 focus:outline-none"
          />
          <PasswordStrengthBar :password="newPassword" />
        </div>

        <div v-if="error" class="p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
          {{ error }}
        </div>

        <button
          type="submit"
          :disabled="loading"
          class="w-full flex items-center justify-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-lg text-sm font-semibold hover:bg-indigo-700 transition-colors disabled:opacity-75 min-h-[44px]"
        >
          <AppSpinner v-if="loading" />
          {{ loading ? 'Setting password…' : 'Set password' }}
        </button>
      </form>
    </template>

    <template v-else>
      <div class="p-4 bg-green-50 border border-green-200 text-sm text-green-800 rounded-lg mb-4">
        Password updated. Please sign in.
      </div>
      <router-link to="/login" class="text-indigo-600 hover:underline text-sm">Sign in</router-link>
    </template>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import * as api from '../../api/client.js'
import PasswordStrengthBar from '../../components/auth/PasswordStrengthBar.vue'
import AppSpinner from '../../components/ui/AppSpinner.vue'

const route = useRoute()
const newPassword = ref('')
const loading = ref(false)
const error = ref(null)
const done = ref(false)

async function submit() {
  loading.value = true
  error.value = null
  const token = route.query.token
  try {
    await api.passwordResetConfirm(token, newPassword.value)
    done.value = true
  } catch (e) {
    error.value = e.message
  } finally {
    loading.value = false
  }
}
</script>
