<template>
  <q-page class="flex flex-center">
    <q-card style="width: 400px; max-width: 90vw;">
      <q-card-section>
        <!-- Update title based on login status from store -->
        <div class="text-h6">
          {{ isLoggedIn ? 'Register New Passkey' : 'Register Passkey' }}
        </div>
      </q-card-section>

      <q-card-section>
        <q-input
          v-model="username"
          label="Username"
          outlined
          dense
          class="q-mb-md"
          :rules="[val => !!val || 'Username is required']"
          @keyup.enter="handleRegister"
          :disable="isLoggedIn"
          :hint="isLoggedIn ? 'Registering a new passkey for your current account.' : ''"
          :readonly="isLoggedIn"
        />
        <q-btn
          :label="isLoggedIn ? 'Register New Passkey' : 'Register Passkey'"
          color="primary"
          class="full-width"
          @click="handleRegister"
          :loading="loading"
          :disable="loading || (!username && !isLoggedIn)"
        />
        <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">
        <!-- Hide login link if already logged in based on store state -->
        <q-btn
          v-if="!isLoggedIn"
          flat
          label="Already have an account? Login"
          to="/login"
        />
      </q-card-actions>
    </q-card>
  </q-page>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'; // Import computed
import { useRouter } from 'vue-router';
import { startRegistration } from '@simplewebauthn/browser';
import axios from 'boot/axios';
import { useAuthStore } from 'stores/auth'; // Import the auth store

const loading = ref(false);
const errorMessage = ref('');
const successMessage = ref('');
const router = useRouter();
const authStore = useAuthStore(); // Use the auth store

// Computed properties to get state from the store
const isLoggedIn = computed(() => authStore.isAuthenticated);

const username = ref(''); // Local ref for username input

// Check auth status on component mount using the store action
onMounted(async() => 
{
  if (!authStore.isAuthenticated) 
  {
    await authStore.checkAuthStatus();
    if (authStore.error) 
    {
      errorMessage.value = authStore.error;
    }
  }
  
  if (!isLoggedIn.value) 
  {
    username.value = ''; // Clear username if not logged in
  }
  else 
  {
    username.value = authStore.user?.username || ''; // Use username from store if logged in
  }
});

async function handleRegister() 
{
  const currentUsername = isLoggedIn.value ? authStore.user?.username : username.value;
  if (!currentUsername) 
  {
    errorMessage.value = 'Username is missing.';
    return;
  }
  loading.value = true;
  errorMessage.value = '';
  successMessage.value = '';

  try 
  {
    // 1. Get options from server
    const optionsRes = await axios.post('/api/auth/generate-registration-options', {
      username: currentUsername, // Use username from store
    });
    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) 
    {
      // Adjust success message based on login state
      successMessage.value = isLoggedIn.value
        ? 'New passkey registered successfully!'
        : 'Registration successful! Redirecting to login...';
      if (!isLoggedIn.value) 
      {
        // Redirect to login page only if they weren't logged in
        setTimeout(() => 
        {
          router.push('/login');
        }, 2000);
      }
      else 
      {
        // Maybe redirect to a profile page or dashboard if already logged in
        // setTimeout(() => { router.push('/dashboard'); }, 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) 
    {
      errorMessage.value = 'This passkey seems to be registered already.';
    }
    else 
    {
      errorMessage.value = `Registration failed: ${message}`;
    }
  }
  finally 
  {
    loading.value = false;
  }
}
</script>
