<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
    <div class="max-w-md w-full space-y-8">
      <div class="text-center">
        <Icon name="eos-icons:loading" size="48" class="mx-auto text-primary animate-spin" />
        <h2 class="mt-6 text-3xl font-extrabold text-gray-900 dark:text-white">
          Completing Authorization
        </h2>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          Processing OAuth2 callback...
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  layout: false,
  title: "OAuth2 Callback"
})

onMounted(() => {
  try {
    const urlParams = new URLSearchParams(window.location.search)
    const hashParams = new URLSearchParams(window.location.hash.substring(1))
    
    // Check for authorization code (Authorization Code flow)
    const code = urlParams.get('code')
    const state = urlParams.get('state')
    const error = urlParams.get('error')
    
    // Check for access token (Implicit flow)
    const accessToken = hashParams.get('access_token')
    const tokenType = hashParams.get('token_type')
    const expiresIn = hashParams.get('expires_in')
    
    if (error) {
      // Send error back to parent window
      window.opener?.postMessage({
        type: 'oauth2_callback',
        error: error,
        errorDescription: urlParams.get('error_description')
      }, window.location.origin)
    } else if (code) {
      // Send authorization code back to parent window
      window.opener?.postMessage({
        type: 'oauth2_callback',
        code: code,
        state: state
      }, window.location.origin)
    } else if (accessToken) {
      // Send access token back to parent window (Implicit flow)
      window.opener?.postMessage({
        type: 'oauth2_callback',
        accessToken: accessToken,
        tokenType: tokenType,
        expiresIn: expiresIn ? parseInt(expiresIn) : null,
        state: hashParams.get('state')
      }, window.location.origin)
    } else {
      // No valid response found
      window.opener?.postMessage({
        type: 'oauth2_callback',
        error: 'invalid_response',
        errorDescription: 'No authorization code or access token found in callback'
      }, window.location.origin)
    }
    
    // Close the popup window
    setTimeout(() => {
      window.close()
    }, 1000)
    
  } catch (error) {
    console.error('OAuth callback error:', error)
    window.opener?.postMessage({
      type: 'oauth2_callback',
      error: 'callback_error',
      errorDescription: error.message
    }, window.location.origin)
    
    setTimeout(() => {
      window.close()
    }, 1000)
  }
})
</script> 