<template>
  <q-page class="flex flex-center bg-theme">
    <img
      src="/stylepoint.png"
      alt="StylePoint Logo"
      class="logo q-mb-md absolute"
      style="max-width: 300px; width: 100%; top: 75px;"
    >
    <q-card
      style="width: 400px; max-width: 90vw;"
      dark
      class="bg-blurred"
      flat
      bordered
    >
      <q-card-section>
        <!-- Update title -->
        <div class="text-h4 text-center">
          Register Account
        </div>
      </q-card-section>

      <q-separator />

      <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-input
          v-model="registrationToken"
          label="Registration Token"
          outlined
          class="q-mb-md"
          :rules="[val => !!val || 'Registration Token is required']"
          :readonly="!showTokenInput"
          @keyup.enter="handleRegister"
        />
        <q-btn
          label="Register Account"
          color="primary"
          class="full-width"
          @click="handleRegister"
          :loading="loading"
          :disable="loading || !username || !email || !fullName || (showTokenInput && !registrationToken)"
        />
        <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-section>
        <!-- Always show login link -->
        <q-btn
          color="secondary"
          flat
          label="Already have an account? Login"
          to="/login"
          class="full-width"
        />
      </q-card-section>
    </q-card>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'; // Add onMounted
import { useRouter, useRoute } from 'vue-router'; // Add useRoute
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();
const route = useRoute(); // Get route object
// Remove auth store usage

// Remove isLoggedIn computed property

const username = ref('');
const email = ref('');
const fullName = ref('');
const registrationToken = ref(''); // Add registrationToken ref
const showTokenInput = ref(false); // Control visibility of token input

// Check for token in route params when component mounts
onMounted(() =>
{
  const tokenFromRoute = route.params.token;
  if (tokenFromRoute && typeof tokenFromRoute === 'string')
  {
    registrationToken.value = tokenFromRoute;
    showTokenInput.value = false;
  }
  else
  {
    showTokenInput.value = true; // Show input if no token in route
  }
});

// Remove onMounted hook

async function handleRegister()
{
  // Validate all fields including registration token if input is shown
  if (!username.value || !email.value || !fullName.value || (showTokenInput.value && !registrationToken.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 + registrationToken
    const payload = {
      username: username.value,
      email: email.value,
      fullName: fullName.value,
      registrationToken: registrationToken.value, // Add registrationToken to payload
    };

    // 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>
