<template>
  <q-page class="flex flex-center bg-theme">
    <img
      src="/stylepoint.png"
      alt="StylePoint Logo"
      class="drop-shadow 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>
        <div
          class="
      text-h4
      text-center"
        >
          <small>Login</small>
        </div>
      </q-card-section>

      <q-separator />

      <q-card-section class="row justify-center">
        <q-btn
          icon="key"
          round
          @click="handleLogin"
          :loading="loading"
          size="xl"
          class="bg-theme shadow-5"
        />
        <div
          v-if="errorMessage"
          class="text-negative q-mt-md"
        >
          {{ errorMessage }}
        </div>
      </q-card-section>

      <q-card-actions align="center">
        <q-btn
          outline
          color="secondary"
          label="Don't have an account? Register"
          to="/register"
        />
      </q-card-actions>
    </q-card>
  </q-page>
</template>

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

const productName = process.env.PRODUCT_NAME;

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

async function handleLogin()
{
  loading.value = true;
  errorMessage.value = '';

  try
  {
    // 1. Get options from server
    const optionsRes = await axios.post('/api/auth/generate-authentication-options');
    const options = optionsRes.data;

    // 2. Start authentication ceremony in browser
    const authResp = await startAuthentication(options);

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

    if (verificationRes.data.verified)
    {
      authStore.isAuthenticated = true;
      authStore.user = verificationRes.data.user;
      authStore.error = null;
      router.push('/');
    }
    else
    {
      errorMessage.value = 'Authentication failed.';
      // Optionally update store state on failure
      authStore.isAuthenticated = false;
      authStore.user = null;
      authStore.error = 'Authentication failed.';
    }
  }
  catch (error)
  {
    console.error('Login error:', error);
    const message = error.response?.data?.error || error.message || 'An unknown error occurred during login.';
    // Handle specific simplewebauthn errors if needed
    if (error.name === 'NotAllowedError')
    {
      errorMessage.value = 'Authentication ceremony was cancelled or timed out.';
    }
    else if (error.response?.status === 404 && error.response?.data?.error?.includes('User not found'))
    {
      errorMessage.value = 'User not found. Please check your username or register.';
    }
    else if (error.response?.status === 404 && error.response?.data?.error?.includes('Authenticator not found'))
    {
      errorMessage.value = 'No registered passkey found for this user or device. Try registering first.';
    }
    else
    {
      errorMessage.value = `Login failed: ${message}`;
    }
    // Optionally update store state on error
    authStore.isAuthenticated = false;
    authStore.user = null;
    authStore.error = `Login failed: ${message}`;
  }
  finally
  {
    loading.value = false;
  }
}
</script>