<template>
  <q-page class="flex flex-center">
    <q-card style="width: 400px; max-width: 90vw;">
      <q-card-section>
        <!-- Update title -->
        <div class="text-h6">
          Register Passkey
        </div>
      </q-card-section>

      <q-card-section>
        <q-input
          v-model="username"
          label="Username"
          outlined
          class="q-mb-md"
          :rules="[val => !!val || 'Username is required']"
          @keyup.enter="handleRegister"
        />
        <!-- Make Email and Full Name required -->
        <q-input
          v-model="email"
          label="Email"
          type="email"
          outlined
          class="q-mb-md"
          :rules="[val => !!val || 'Email is required', val => /.+@.+\..+/.test(val) || 'Email must be valid']"
          @keyup.enter="handleRegister"
        />
        <q-input
          v-model="fullName"
          label="Full Name"
          outlined
          class="q-mb-md"
          :rules="[val => !!val || 'Full Name is required']"
          @keyup.enter="handleRegister"
        />
        <q-btn
          label="Register Passkey"
          color="primary"
          class="full-width"
          @click="handleRegister"
          :loading="loading"
          :disable="loading || !username || !email || !fullName"
        />
        <div
          v-if="successMessage"
          class="text-positive q-mt-md"
        >
          {{ successMessage }}
        </div>
        <div
          v-if="errorMessage"
          class="text-negative q-mt-md"
        >
          {{ errorMessage }}
        </div>
      </q-card-section>

      <q-card-actions align="center">
        <!-- Always show login link -->
        <q-btn
          flat
          label="Already have an account? Login"
          to="/login"
        />
      </q-card-actions>
    </q-card>
  </q-page>
</template>

<script setup>
import { ref } from 'vue'; // Remove computed and onMounted
import { useRouter } from 'vue-router';
import { startRegistration } from '@simplewebauthn/browser';
import axios from 'boot/axios';
// Remove auth store import

const loading = ref(false);
const errorMessage = ref('');
const successMessage = ref('');
const router = useRouter();
// Remove auth store usage

// Remove isLoggedIn computed property

const username = ref('');
const email = ref('');
const fullName = ref('');

// Remove onMounted hook

async function handleRegister()
{
  // Validate all fields
  if (!username.value || !email.value || !fullName.value)
  {
    errorMessage.value = 'Please fill in all required fields.';
    return;
  }
  // Basic email validation
  if (!/.+@.+\..+/.test(email.value))
  {
    errorMessage.value = 'Please enter a valid email address.';
    return;
  }

  loading.value = true;
  errorMessage.value = '';
  successMessage.value = '';

  try
  {
    // Prepare payload - always include all fields
    const payload = {
      username: username.value,
      email: email.value,
      fullName: fullName.value,
    };

    // 1. Get options from server
    const optionsRes = await axios.post('/api/auth/generate-registration-options', payload);
    const options = optionsRes.data;

    // 2. Start registration ceremony in browser
    const regResp = await startRegistration(options);

    // 3. Send response to server for verification
    const verificationRes = await axios.post('/api/auth/verify-registration', {
      registrationResponse: regResp,
    });

    if (verificationRes.data.verified)
    {
      // Simplify success message and always redirect
      successMessage.value = 'Registration successful! Redirecting to login...';
      setTimeout(() =>
      {
        router.push('/login');
      }, 2000);
    }
    else
    {
      errorMessage.value = 'Registration failed.';
    }
  }
  catch (error)
  {
    console.error('Registration error:', error);
    const message = error.response?.data?.error || error.message || 'An unknown error occurred during registration.';
    // Handle specific simplewebauthn errors
    if (error.name === 'InvalidStateError')
    {
      errorMessage.value = 'Authenticator already registered. Try logging in instead.';
    }
    else if (error.name === 'NotAllowedError')
    {
      errorMessage.value = 'Registration ceremony was cancelled or timed out.';
    }
    else if (error.response?.status === 409)
    {
      // More specific message for username conflict
      errorMessage.value = error.response?.data?.error || 'Username or passkey might already be registered.';
    }
    else
    {
      errorMessage.value = `Registration failed: ${message}`;
    }
  }
  finally
  {
    loading.value = false;
  }
}
</script>
