<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary to-blue-700 px-4">
    <div class="max-w-md w-full">
      <div class="bg-white rounded-2xl shadow-2xl p-8">
        <!-- Loading State -->
        <div v-if="isProcessing" class="text-center">
          <div class="mb-6">
            <div class="w-16 h-16 mx-auto border-4 border-primary/20 border-t-primary rounded-full animate-spin"/>
          </div>
          <h2 class="text-xl font-bold text-gray-900 mb-2">
            Authenticating...
          </h2>
          <p class="text-gray-600">
            Please wait while we complete your sign in
          </p>
        </div>

        <!-- Success State -->
        <div v-else-if="success" class="text-center">
          <div class="mb-6">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="h-16 w-16 mx-auto text-green-500"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <h2 class="text-xl font-bold text-gray-900 mb-2">
            Sign In Successful!
          </h2>
          <p class="text-gray-600 mb-6">
            Redirecting you now...
          </p>
        </div>

        <!-- Error State -->
        <div v-else-if="errorMessage" class="text-center">
          <div class="mb-6">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="h-16 w-16 mx-auto text-red-500"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <h2 class="text-xl font-bold text-gray-900 mb-2">
            Authentication Failed
          </h2>
          <p class="text-gray-600 mb-6">
            {{ errorMessage }}
          </p>

          <!-- Retry Button -->
          <NuxtLink
            to="/auth/login"
            class="inline-block px-6 py-3 bg-primary hover:bg-blue-700 text-white font-semibold rounded-lg transition"
          >
            Try Again
          </NuxtLink>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useAuthStore } from '~/store/auth'

definePageMeta({
  layout: false, // Don't use default layout
})

const authStore = useAuthStore()
const route = useRoute()
const router = useRouter()

const isProcessing = ref(true)
const success = ref(false)
const errorMessage = ref<string | null>(null)

// Error messages mapping
const errorMessages: Record<string, string> = {
  invalid_state: 'Security validation failed. Please try again.',
  unauthorized: 'Your Discord account is not authorized to access this system.',
  auth_failed: 'Discord authentication failed. Please try again.',
  server_error: 'An unexpected server error occurred. Please try again later.',
}

onMounted(async () => {
  try {
    // Check for error query parameter
    const errorParam = route.query.error as string
    if (errorParam) {
      errorMessage.value = errorMessages[errorParam] || errorParam
      isProcessing.value = false
      return
    }

    // Success case - cookies are already set by backend
    // Just verify auth and redirect
    const isAuth = await authStore.checkAuth()

    if (isAuth) {
      success.value = true

      // Short delay to show success message, then redirect to games list
      // Using navigateTo with external:false ensures proper client-side navigation
      // which carries the authenticated state
      setTimeout(() => {
        navigateTo('/', { replace: true })
      }, 500)
    } else {
      errorMessage.value = 'Authentication verification failed. Please try again.'
    }
  } catch (err: any) {
    console.error('OAuth callback error:', err)
    errorMessage.value = err.message || 'An unexpected error occurred'
  } finally {
    isProcessing.value = false
  }
})
</script>

<style scoped>
/* Additional component styles if needed */
</style>
